Example #1
0
/*
 * Handle open from generic layer.
 *
 * This is called by the diskslice code on first open in order to get the 
 * basic device geometry paramters.
 */
static int
aac_disk_open(struct disk *dp)
{
	struct aac_disk	*sc;

	fwprintf(NULL, HBA_FLAGS_DBG_FUNCTION_ENTRY_B, "");

	sc = (struct aac_disk *)dp->d_drv1;
	
	if (sc == NULL) {
		printf("aac_disk_open: No Softc\n");
		return (ENXIO);
	}

	/* check that the controller is up and running */
	if (sc->ad_controller->aac_state & AAC_STATE_SUSPEND) {
		printf("Controller Suspended controller state = 0x%x\n",
		       sc->ad_controller->aac_state);
		return(ENXIO);
	}

	sc->ad_flags |= AAC_DISK_OPEN;
	return (0);
}
Example #2
0
// Dump a parse tree node in a form helpful to someone debugging the behavior of this program.
static void dump_node(indent_t node_indent, const parse_node_t &node, const wcstring &source)
{
    int nextc_idx = node.source_start + node.source_length;
    wchar_t prevc = node.source_start > 0 ? source[node.source_start - 1] : L' ';
    wchar_t nextc = nextc_idx < source.size() ? source[nextc_idx] : L' ';
    wchar_t prevc_str[4] = {prevc, 0, 0, 0};
    wchar_t nextc_str[4] = {nextc, 0, 0, 0};
    if (prevc < L' ')
    {
        prevc_str[0] = L'\\';
        prevc_str[1] = L'c';
        prevc_str[2] = prevc + '@';
    }
    if (nextc < L' ')
    {
        nextc_str[0] = L'\\';
        nextc_str[1] = L'c';
        nextc_str[2] = nextc + '@';
    }
    fwprintf(stderr, L"{off %4d, len %4d, indent %2u, kw %ls, %ls} [%ls|%ls|%ls]\n",
            node.source_start, node.source_length, node_indent,
            keyword_description(node.keyword), token_type_description(node.type),
            prevc_str, source.substr(node.source_start, node.source_length).c_str(), nextc_str);
}
void WriteLog(wchar_t* pMsg)
{
#ifdef _DEBUG
    // write error or other information into log file
    ::EnterCriticalSection(&gCS);

    try
    {
        SYSTEMTIME oT;
        ::GetLocalTime(&oT);
        //FILE* pLog = _wfopen(pLogFile, L"a");
        FILE* pLog = nullptr;
        _wfopen_s(&pLog, pLogFile, L"a");

        if (pLog)
        {
            fwprintf(pLog, L"%02d/%02d/%04d, %02d:%02d:%02d\n    %s\n",
                     oT.wMonth, oT.wDay, oT.wYear, oT.wHour, oT.wMinute, oT.wSecond, pMsg);
            fclose(pLog);
        }
        else
        {
            wprintf(L"Unable to open log file: %s\n", pLogFile);
            throw;
        }
    }
    catch (...)
    {
        wprintf(L"Exception when trying to open or write log file: %s\n", pLogFile);
    }

    ::LeaveCriticalSection(&gCS);
#else
    (void)(pMsg);
#endif
}
void xmlwriter::CreateChild(LPCTSTR  sTag,LPCTSTR  sValue)
{
	fwprintf(fp,_T("\n"));
	//Indent properly
	for(int iTmp =0;iTmp<iLevel;iTmp++)
		fwprintf(fp,_T("\t"));
	fwprintf(fp,_T("<%s"),sTag);
	//Add Attributes
	while(0 < vectAttrData.size()/2)
	{
		LPTSTR sTmp = vectAttrData.back();
		fwprintf(fp,_T(" %s="), sTmp);
		vectAttrData.pop_back();
		sTmp = vectAttrData.back();
		fwprintf(fp,_T("\"%s\""), sTmp);
		vectAttrData.pop_back();
	}
	vectAttrData.clear();
	//add value and close tag
	fwprintf(fp,_T(">%s</%s>"),sValue,sTag);
}
void xmlwriter::Createtag(LPTSTR  sTag)
{
	fwprintf(fp,_T("\n"));
	//Indent properly
	for(int iTmp =0;iTmp<iLevel;iTmp++)
		fwprintf(fp,_T("\t"));
	fwprintf(fp,_T("<%s"),sTag);
	//Add Attributes
	while(0 < vectAttrData.size()/2)
	{
		LPTSTR sTmp = vectAttrData.back();
		fwprintf(fp,_T(" %s="), sTmp);
		vectAttrData.pop_back();
		sTmp = vectAttrData.back();
		fwprintf(fp,_T("\"%s\""), sTmp);
		vectAttrData.pop_back();
	}
	vectAttrData.clear();
	fwprintf(fp,_T(">"));
	sTagStack.push(sTag);
	iLevel++;

}
Example #6
0
bool WScriptJsrt::PrintException(LPCSTR fileName, JsErrorCode jsErrorCode)
{
    LPCWSTR errorTypeString = ConvertErrorCodeToMessage(jsErrorCode);
    JsValueRef exception;
    ChakraRTInterface::JsGetAndClearException(&exception);
    if (exception != nullptr)
    {
        if (jsErrorCode == JsErrorCode::JsErrorScriptCompile || jsErrorCode == JsErrorCode::JsErrorScriptException)
        {
            AutoString errorMessage;
            size_t errorMessageLength = 0;

            JsValueRef errorString = JS_INVALID_REFERENCE;

            IfJsrtErrorFail(ChakraRTInterface::JsConvertValueToString(exception, &errorString), false);
            IfJsrtErrorFail(ChakraRTInterface::JsStringToPointerUtf8Copy(errorString, &errorMessage, &errorMessageLength), false);
            AutoWideString wideErrorMessage;
            NarrowStringToWideDynamic(*errorMessage, &wideErrorMessage);

            if (jsErrorCode == JsErrorCode::JsErrorScriptCompile)
            {
                JsPropertyIdRef linePropertyId = JS_INVALID_REFERENCE;
                JsValueRef lineProperty = JS_INVALID_REFERENCE;

                JsPropertyIdRef columnPropertyId = JS_INVALID_REFERENCE;
                JsValueRef columnProperty = JS_INVALID_REFERENCE;

                int line;
                int column;

                IfJsrtErrorFail(ChakraRTInterface::JsGetPropertyIdFromNameUtf8("line", &linePropertyId), false);
                IfJsrtErrorFail(ChakraRTInterface::JsGetProperty(exception, linePropertyId, &lineProperty), false);
                IfJsrtErrorFail(ChakraRTInterface::JsNumberToInt(lineProperty, &line), false);

                IfJsrtErrorFail(ChakraRTInterface::JsGetPropertyIdFromNameUtf8("column", &columnPropertyId), false);
                IfJsrtErrorFail(ChakraRTInterface::JsGetProperty(exception, columnPropertyId, &columnProperty), false);
                IfJsrtErrorFail(ChakraRTInterface::JsNumberToInt(columnProperty, &column), false);

                CHAR shortFileName[_MAX_PATH];
                CHAR ext[_MAX_EXT];
                _splitpath_s(fileName, nullptr, 0, nullptr, 0, shortFileName, _countof(shortFileName), ext, _countof(ext));
                fwprintf(stderr, _u("%ls\n\tat code (%S%S:%d:%d)\n"), *wideErrorMessage, shortFileName, ext, (int)line + 1, (int)column + 1);
            }
            else
            {
                JsValueType propertyType = JsUndefined;
                JsPropertyIdRef stackPropertyId = JS_INVALID_REFERENCE;
                JsValueRef stackProperty = JS_INVALID_REFERENCE;
                AutoString errorStack;
                size_t errorStackLength = 0;

                JsErrorCode errorCode = ChakraRTInterface::JsGetPropertyIdFromNameUtf8("stack", &stackPropertyId);

                if (errorCode == JsErrorCode::JsNoError)
                {
                    errorCode = ChakraRTInterface::JsGetProperty(exception, stackPropertyId, &stackProperty);
                    if (errorCode == JsErrorCode::JsNoError)
                    {
                        errorCode = ChakraRTInterface::JsGetValueType(stackProperty, &propertyType);
                    }
                }

                if (errorCode != JsErrorCode::JsNoError || propertyType == JsUndefined)
                {
                    const char *fName = fileName != nullptr ? fileName : "(unknown)";
                    // do not mix char/wchar. print them separately
                    fprintf(stderr, "thrown at %s:\n^\n", fName);
                    fwprintf(stderr, _u("%ls\n"), *wideErrorMessage);
                }
                else
                {
                    IfJsrtErrorFail(ChakraRTInterface::JsStringToPointerUtf8Copy(stackProperty, &errorStack, &errorStackLength), false);
                    AutoWideString wideErrorStack;
                    NarrowStringToWideDynamic(*errorStack, &wideErrorStack);
                    fwprintf(stderr, _u("%ls\n"), *wideErrorStack);
                }
            }
        }
        else
        {
            fwprintf(stderr, _u("Error : %ls\n"), errorTypeString);
        }
        return true;
    }
    else
    {
        fwprintf(stderr, _u("Error : %ls\n"), errorTypeString);
    }
    return false;
}
Example #7
0
CLIENT *
clnttcp_create (struct sockaddr_in *raddr, u_long prog, u_long vers,
		int *sockp, u_int sendsz, u_int recvsz)
{
  CLIENT *h;
  struct ct_data *ct;
  struct rpc_msg call_msg;

  h = (CLIENT *) mem_alloc (sizeof (*h));
  ct = (struct ct_data *) mem_alloc (sizeof (*ct));
  if (h == NULL || ct == NULL)
    {
      struct rpc_createerr *ce = &get_rpc_createerr ();
#ifdef USE_IN_LIBIO
      if (_IO_fwide (stderr, 0) > 0)
	(void) fwprintf (stderr, L"%s",
			   _("clnttcp_create: out of memory\n"));
      else
#endif
	(void) fputs (_("clnttcp_create: out of memory\n"), stderr);
      ce->cf_stat = RPC_SYSTEMERROR;
      ce->cf_error.re_errno = ENOMEM;
      goto fooy;
    }

  /*
   * If no port number given ask the pmap for one
   */
  if (raddr->sin_port == 0)
    {
      u_short port;
      if ((port = pmap_getport (raddr, prog, vers, IPPROTO_TCP)) == 0)
	{
	  mem_free ((caddr_t) ct, sizeof (struct ct_data));
	  mem_free ((caddr_t) h, sizeof (CLIENT));
	  return ((CLIENT *) NULL);
	}
      raddr->sin_port = htons (port);
    }

  /*
   * If no socket given, open one
   */
  if (*sockp < 0)
    {
      *sockp = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
      (void) bindresvport (*sockp, (struct sockaddr_in *) 0);
      if ((*sockp < 0)
	  || (connect (*sockp, (struct sockaddr *) raddr,
			 sizeof (*raddr)) < 0))
	{
	  struct rpc_createerr *ce = &get_rpc_createerr ();
	  ce->cf_stat = RPC_SYSTEMERROR;
	  ce->cf_error.re_errno = errno;
	  if (*sockp >= 0)
	    (void) close (*sockp);
	  goto fooy;
	}
      ct->ct_closeit = TRUE;
    }
  else
    {
      ct->ct_closeit = FALSE;
    }

  /*
   * Set up private data struct
   */
  ct->ct_sock = *sockp;
  ct->ct_wait.tv_usec = 0;
  ct->ct_waitset = FALSE;
  ct->ct_addr = *raddr;

  /*
   * Initialize call message
   */
  call_msg.rm_xid = _create_xid ();
  call_msg.rm_direction = CALL;
  call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
  call_msg.rm_call.cb_prog = prog;
  call_msg.rm_call.cb_vers = vers;

  /*
   * pre-serialize the static part of the call msg and stash it away
   */
  xdrmem_create (&(ct->ct_xdrs), ct->ct_mcall, MCALL_MSG_SIZE,
		 XDR_ENCODE);
  if (!xdr_callhdr (&(ct->ct_xdrs), &call_msg))
    {
      if (ct->ct_closeit)
	{
	  (void) close (*sockp);
	}
      goto fooy;
    }
  ct->ct_mpos = XDR_GETPOS (&(ct->ct_xdrs));
  XDR_DESTROY (&(ct->ct_xdrs));

  /*
   * Create a client handle which uses xdrrec for serialization
   * and authnone for authentication.
   */
  xdrrec_create (&(ct->ct_xdrs), sendsz, recvsz,
		 (caddr_t) ct, readtcp, writetcp);
  h->cl_ops = &tcp_ops;
  h->cl_private = (caddr_t) ct;
  h->cl_auth = authnone_create ();
  return h;

fooy:
  /*
   * Something goofed, free stuff and barf
   */
  mem_free ((caddr_t) ct, sizeof (struct ct_data));
  mem_free ((caddr_t) h, sizeof (CLIENT));
  return ((CLIENT *) NULL);
}
void HuffmanCodec::buildEncodeCodes()
{
	long long freqTable[256];

	memset(freqTable, 0, sizeof(freqTable));

	while (!reader->atEnd())
	{
		byte next;
		reader->readByte(next);
		freqTable[next]++;
	}

	priority_queue<pll> pq;

	for (int i = 0; i < 256; i++)
	{
		nodes[i].c = i;
		pq.push(pll(-freqTable[i], i));
	}

	int nodesCount = 256;

	for (int i = 0; i < 255; i++)
	{
		pll top = pq.top();
		pq.pop();
		pll top2 = pq.top();
		pq.pop();
		int nextNodeIndex = nodesCount++;

		int left = top.second, right = top2.second;
		if (left > right)
			swap(left, right);

		nodes[nextNodeIndex].leftChildIndex = left;
		nodes[nextNodeIndex].rightChildIndex = right;
		nodes[top.second].parentIndex = nextNodeIndex;
		nodes[top2.second].parentIndex = nextNodeIndex;

		pq.push(pll(top.first + top2.first, nextNodeIndex));
	}

	rootIndex = nodesCount - 1;
	nodes[rootIndex].parentIndex = -1;

	for (int i = 0; i < 256; i++)
	{
		codeLengths[i] = 0;
		int ci = i;
		int &cLen = codeLengths[i];
		while (true)
		{
			HuffmanTreeNode &cur = nodes[ci];
			if (cur.parentIndex == -1)
				break;
			int curCode = 1;
			if (nodes[cur.parentIndex].leftChildIndex == ci)
				curCode = 0;
			codes[i][cLen++] = curCode;
			ci = cur.parentIndex;
		}
		reverse(codes[i], codes[i] + cLen);
	}

	fwprintf(stderr, L"Table was built\n");
}
Example #9
0
/****
 * GetEventMessageDescription
 *
 * DESC:
 *     Gets the specified message string from the event. If the event does not 
 *     contain the specified message, the function returns NULL.
 *
 * ARGS:
 *     hMetaData - Handle to open metadata for an event
 *     hEvent - Handle to open event
 *
 * RETURNS:
 *     If a message has been found, returns a string containing the message.
 *     Otherwise if no message has been found, returns NULL
 *
 *     Note: Caller is responsible for freeing the memory used by the string
 */
LPWSTR GetEventMessageDescription(EVT_HANDLE hMetadata, EVT_HANDLE hEvent)
{
	// The raw message string
    LPWSTR pBuffer = NULL;	
	// The processed message string (make it safe for JSON encoding)
	LPWSTR done = NULL;	
	// Size of the message string
    DWORD dwBufferSize = 0;	
	// Number of bytes used for message string
    DWORD dwBufferUsed = 0;		
	// Type of message string to retrieve from event log
	EVT_FORMAT_MESSAGE_FLAGS flags = EvtFormatMessageEvent;

	// Attempt to read provider-specific message from this event
    if (!EvtFormatMessage(hMetadata, hEvent, 0, 0, NULL, flags, dwBufferSize, pBuffer, &dwBufferUsed))
    {
		// An error occurred. Retrieve this error
        DWORD dwError = GetLastError();

		// If the error was due to our destination buffer being too small
        if (dwError == ERROR_INSUFFICIENT_BUFFER)
        {
            if ((flags == EvtFormatMessageKeyword))
                pBuffer[dwBufferSize-1] = L'\0';
            else
                dwBufferSize = dwBufferUsed;

			// Re-allocate our buffer with the required size
            pBuffer = (LPWSTR)malloc(dwBufferSize * sizeof(WCHAR));

			// If the re-allocation was successful
            if (pBuffer)
            {
				// Re-attempt to retrieve event message
                EvtFormatMessage(hMetadata, hEvent, 0, 0, NULL, flags, dwBufferSize, pBuffer, &dwBufferUsed);

                if ((flags == EvtFormatMessageKeyword))
                    pBuffer[dwBufferUsed-1] = L'\0';

				// Replace new lines with "\n" characters for client to handle
				// This makes the string JSON friendly
				done = repl_wcs(pBuffer, L"\\", L"\\\\");
            }
            else
            {
				// Allocation failed
                fwprintf(stderr, L"[Error][GetEventMessageDescription]: malloc failed\n");
            }
        }
        else if (dwError == ERROR_EVT_MESSAGE_NOT_FOUND)
		{
			// Message was not found. Will return NULL
		}
		else if (dwError == ERROR_EVT_MESSAGE_ID_NOT_FOUND) 
		{
			// Message ID not found. Will return NULL
		}
        else
        {
			// Unexpected error. Output to screen
            fwprintf(stderr, L"[Error][GetEventMessageDescription]: EvtFormatMessage failed with %u\n", dwError);
        }
    }

	// Return the JSON-friendly string 
    return done;
}
Example #10
0
/****
 * ProcessResults
 *
 * DESC:
 *     Creates a remote context 
 *
 * ARGS:
 *     hRemote - Remote session context
 *     hResults - An open set of results
 *     outputFormat - 0 for JSON, otherwise XML
 *     mode - last record vs dump results
 *     debug - set to 0 (none) 1 (basic) or 2 (verbose)
 */
DWORD64 ProcessResults(EVT_HANDLE hRemote, EVT_HANDLE hResults, int outputFormat, int mode, int debug)
{
    DWORD64 status = ERROR_SUCCESS;
    EVT_HANDLE hEvents[CHUNK_SIZE + 1];
    DWORD dwReturned = 0;
	BOOL completed = FALSE;	
	BOOL firstRecordCompleted = FALSE;

	// Print header information for our events
	if( outputFormat == OUTPUT_FORMAT_JSON ) {
		// Note: Marc requested this to be removed
		//wprintf(L"[");
	} else {
		wprintf(L"%s||%s||%s||%s||%s||%s||%s||%s\n\n", L"RecordID", L"EventID", L"Channel", L"Provider", L"Computer", L"TimeCreated", L"Task", L"Level");
	}

	// Begin an infinite loop, as we want to continue reading records as long as they are available.
	// The break-condition is a manual one at the bottom (i.e. no more records found)
    while (TRUE)
    {
        // Get a block of events from the result set.
        if (EvtNext(hResults, CHUNK_SIZE, hEvents, INFINITE, 0, &dwReturned))
        {
			// Cycle through all the events that we received
			for (DWORD i = 0; i < dwReturned; i++)
			{
				// Only print the separator characters once the first record is completed
				if( firstRecordCompleted )
					wprintf(L"||");

				// Extract event details and output the screen
				DWORD64 result = DumpEventInfo(hRemote, hEvents[i], outputFormat, mode, debug);
				
				// Set flag indicating first record is completed so that
				// the top of our loop knows to begin printing the separator character
				firstRecordCompleted = TRUE;

				// Close the handle to the current event, as we are done
				EvtClose(hEvents[i]);

				// Clear the event handle so our cleanup routine does not attempt to re-close
				hEvents[i] = NULL;

				// If currently in "last record" mode			
				if( mode == MODE_FETCH_LAST_RECORD ) {
					// We do not need to process anymore events
					// Recall that all we were looking for was the record ID of the most recent record
					// This should be stored in "status" as, this is the variable that's returned
					status = result;

					completed = true;

					break;
				}
			}
        }
		else 
		{
			// Call to retrieve events failed. Get the error code
			status = GetLastError();

			// If the error was the result of not having any more records
            if (status == ERROR_NO_MORE_ITEMS)
            {
				// Exit the loop. No more records to process
				completed = TRUE;
            }
			else 
			{
				// Otherwise, notify user of the error
                fwprintf(stderr, L"Failed to fetch next batch with following error: %lu\n", status);
			}
		}

		// Cycle through all records that we received
		// Recall that dwReturned contains the number of records received
		for (DWORD i = 0; i < dwReturned; i++)
		{
			// If the event isn't already closed
			if (hEvents[i] != NULL) 
			{
				// Close the event record
				EvtClose(hEvents[i]);
			}
		}

		// Exit the loop if required (i.e. we're done)
		if( completed )
			break;
	}

	// Add closing tag if this is JSON
	if( outputFormat == OUTPUT_FORMAT_JSON ) {
		// Marc requested this to be removed
		// wprintf(L"]");
	}

    return status;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method: GetDetailedRightsForKID
// Description: Gets license state information for all rights granted for a 
//  Key ID.
// Parameters: KID - Key ID string.
//
///////////////////////////////////////////////////////////////////////////////
HRESULT CRightsReporter::GetDetailedRightsForKID(BSTR KID)
{
    HRESULT hr = S_OK;

    SYSTEMTIME FromDate;
    SYSTEMTIME UntilDate;

    DWORD      LicenseStateFlags = 0;

    // Initialize the date structures.
    ZeroMemory(&FromDate, sizeof(FromDate));
    ZeroMemory(&UntilDate, sizeof(UntilDate));

    // Get the license state information.
    hr = m_pLicenseQuery->QueryLicenseState(KID, 
                                            m_cLicenseStateRights,
                                            m_LicenseStateRights,
                                            m_LicenseStateResults);

    if (SUCCEEDED(hr))
    {
        // Loop through the rights, reporting data for each.
        for (int i = 0; i < m_cLicenseStateRights; i++)
        {
            // Report the right.
            fwprintf(m_pFile, L"%s\n", m_LicenseStateRights[i]);

            // Print data from the license state structure based on the 
            //  license state category.
            switch (m_LicenseStateResults[i].dwCategory)
            {
            case WM_DRM_LICENSE_STATE_NORIGHT:
                {
                    fwprintf(m_pFile, L"   Action not allowed.\n");
                    break;
                }
            case WM_DRM_LICENSE_STATE_UNLIM:
                {
                    fwprintf(m_pFile, L"   Action is allowed without restriction.\n");
                    break;
                }
            case WM_DRM_LICENSE_STATE_COUNT:
                {
                    fwprintf(m_pFile, 
                             L"   Action is allowed %d more times.\n", 
                             m_LicenseStateResults[i].dwCount[0]);
                    break;
                }
            case WM_DRM_LICENSE_STATE_FROM:
                {
                    FileTimeToSystemTime(&(m_LicenseStateResults[i].datetime[0]), &FromDate);
                    fwprintf(m_pFile, 
                             L"   Action is allowed without restriction beginning %02d/%02d/%4d.\n",
                             FromDate.wMonth, 
                             FromDate.wDay, 
                             FromDate.wYear);
                    break;
                }
            case WM_DRM_LICENSE_STATE_UNTIL:
                {
                    FileTimeToSystemTime(&(m_LicenseStateResults[i].datetime[0]), &UntilDate);
                    fwprintf(m_pFile, 
                             L"   Action is allowed without restriction until %02d/%02d/%4d.\n",
                             UntilDate.wMonth, 
                             UntilDate.wDay, 
                             UntilDate.wYear);
                    break;
                }
            case WM_DRM_LICENSE_STATE_FROM_UNTIL:
                {
                    FileTimeToSystemTime(&(m_LicenseStateResults[i].datetime[0]), &FromDate);
                    FileTimeToSystemTime(&(m_LicenseStateResults[i].datetime[1]), &UntilDate);
                    fwprintf(m_pFile, L"   Action is allowed without restriction between ");
                    fwprintf(m_pFile, 
                             L"%02d/%02d/%4d and %02d/%02d/%4d.\n",
                             FromDate.wMonth,
                             FromDate.wDay,
                             FromDate.wYear,
                             UntilDate.wMonth,
                             UntilDate.wDay,
                             UntilDate.wYear);
                    break;
                }
            case WM_DRM_LICENSE_STATE_COUNT_FROM:
                {
                    FileTimeToSystemTime(&(m_LicenseStateResults[i].datetime[0]), &FromDate);
                    fwprintf(m_pFile, 
                             L"   Action is allowed %d more times beginning %02d/%02d/%4d.\n",
                             m_LicenseStateResults[i].dwCount[0],
                             FromDate.wMonth, 
                             FromDate.wDay, 
                             FromDate.wYear);
                    break;
                }
            case WM_DRM_LICENSE_STATE_COUNT_UNTIL:
                {
                    FileTimeToSystemTime(&(m_LicenseStateResults[i].datetime[0]), &UntilDate);
                    fwprintf(m_pFile, 
                             L"   Action is allowed %d more times until %02d/%02d/%4d.\n",
                             m_LicenseStateResults[i].dwCount[0],
                             UntilDate.wMonth, 
                             UntilDate.wDay, 
                             UntilDate.wYear);
                    break;
                }
            case WM_DRM_LICENSE_STATE_COUNT_FROM_UNTIL:
                {
                    FileTimeToSystemTime(&(m_LicenseStateResults[i].datetime[0]), &FromDate);
                    FileTimeToSystemTime(&(m_LicenseStateResults[i].datetime[1]), &UntilDate);
                    fwprintf(m_pFile, 
                             L"   Action is allowed %d more times between ",
                             m_LicenseStateResults[i].dwCount[0]);
                    fwprintf(m_pFile, 
                             L"%02d/%02d/%4d and %02d/%02d/%4d.\n",
                             FromDate.wMonth,
                             FromDate.wDay,
                             FromDate.wYear,
                             UntilDate.wMonth,
                             UntilDate.wDay,
                             UntilDate.wYear);
                    break;
                }
            case WM_DRM_LICENSE_STATE_EXPIRATION_AFTER_FIRSTUSE:
                {
                    fwprintf(m_pFile, L"   Action expires after the first use.\n");
                    break;
                }
            } // End switch.

            // Check for other license information.
            
            LicenseStateFlags = m_LicenseStateResults[i].dwVague;

            // Vague.
            if ((LicenseStateFlags & DRM_LICENSE_STATE_DATA_VAGUE)
                == DRM_LICENSE_STATE_DATA_VAGUE)
            {
                fwprintf(m_pFile, 
                    L"   Note: License state data aggregated from multiple licenses.\n");
            }

            // OPLs.
            if ((LicenseStateFlags & DRM_LICENSE_STATE_DATA_OPL_PRESENT)
                == DRM_LICENSE_STATE_DATA_OPL_PRESENT)
            {
                fwprintf(m_pFile, 
                    L"   Note: This action is further restricted with Output Protection Levels.\n");
            }

            // SAP.
            if ((LicenseStateFlags & DRM_LICENSE_STATE_DATA_SAP_PRESENT)
                == DRM_LICENSE_STATE_DATA_SAP_PRESENT)
            {
                fwprintf(m_pFile, L"    Note: This action may only be performed using SAP.\n");
            }

            fwprintf(m_pFile, L"\n");

        } // End for.
    }

    return hr;
}
/* goodB2G uses the BadSource with the GoodSink */
void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_fprintf_65b_goodB2GSink(wchar_t * data)
{
    /* FIX: Specify the format disallowing a format string vulnerability */
    fwprintf(stdout, L"%s\n", data);
}
/* goodG2B uses the GoodSource with the BadSink */
void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_fprintf_65b_goodG2BSink(wchar_t * data)
{
    /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
    fwprintf(stdout, data);
}
Example #14
0
int main(int argc, char *argv[])
{
    set_main_thread();
    setup_fork_guards();

    wsetlocale(LC_ALL, L"");
    program_name=L"fish_indent";

    env_init();
    input_init();

    /* Types of output we support */
    enum
    {
        output_type_plain_text,
        output_type_ansi,
        output_type_html
    } output_type = output_type_plain_text;

    /* Whether to indent (true) or just reformat to one job per line (false) */
    bool do_indent = true;

    while (1)
    {
        const struct option long_options[] =
        {
            { "no-indent", no_argument, 0, 'i' },
            { "help", no_argument, 0, 'h' },
            { "version", no_argument, 0, 'v' },
            { "html", no_argument, 0, 1 },
            { "ansi", no_argument, 0, 2 },
            { 0, 0, 0, 0 }
        };

        int opt_index = 0;
        int opt = getopt_long(argc, argv, "hvi", long_options, &opt_index);
        if (opt == -1)
            break;

        switch (opt)
        {
            case 0:
            {
                break;
            }

            case 'h':
            {
                print_help("fish_indent", 1);
                exit(0);
                assert(0 && "Unreachable code reached");
                break;
            }

            case 'v':
            {
                fwprintf(stderr, _(L"%ls, version %s\n"), program_name, get_fish_version());
                exit(0);
                assert(0 && "Unreachable code reached");
                break;
            }

            case 'i':
            {
                do_indent = false;
                break;
            }

            case 1:
            {
                output_type = output_type_html;
                break;
            }

            case 2:
            {
                output_type = output_type_ansi;
                break;
            }

            case '?':
            {
                exit(1);
            }
        }
    }

    const wcstring src = read_file(stdin);
    const wcstring output_wtext = prettify(src, do_indent);

    /* Maybe colorize */
    std::vector<highlight_spec_t> colors;
    if (output_type != output_type_plain_text)
    {
        highlight_shell_no_io(output_wtext, colors, output_wtext.size(), NULL, env_vars_snapshot_t::current());
    }

    std::string colored_output;
    switch (output_type)
    {
        case output_type_plain_text:
            colored_output = no_colorize(output_wtext);
            break;

        case output_type_ansi:
            colored_output = ansi_colorize(output_wtext, colors);
            break;

        case output_type_html:
            colored_output = html_colorize(output_wtext, colors);
            break;
    }

    fputs(colored_output.c_str(), stdout);
    return 0;
}
Example #15
0
int wmain (int argc,wchar_t ** argv)
{
	CAppData::stdfunc();
	
	SetRegKey(argc,argv);

	if (!SetLanguageSpecifigHandles(argv[0]))
		return 1;

	CArrayFP<CDatabase*> aDatabases;
	
	WORD wCurrentThread=0;

	aDatabases.Add(CDatabase::FromDefaults(TRUE));
	aDatabases[0]->SetNamePtr(alloccopy(L"DEFAULTX"));
	aDatabases[0]->SetThreadId(wCurrentThread);

    int i,helps=0;
#ifndef WIN32
    if (getenv("TZ")==NULL)
		fprintf(stderr,"Timezone is not set. Database may contain invalid file times.\nFor example type "SET TZ=GMT+1" for central european time.\n");
#endif
    for (i=1;i<argc;i++)
    {
        if (argv[i][0]=='-' || argv[i][0]=='/')
        {
            switch (argv[i][1])
			{
			case L'X':
				if (argv[i][2]==L'\0')
				{
					if (i<argc-1)
						i++; // RegKeyName already set
				}
				break;
			case 'l':
			case 'L':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && 
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else if (argv[i][2]=='1')
				{
					aDatabases.GetLast()->AddLocalRoots();
					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				else 
				{
					CStringW* pStr;
					if (argv[i][2]==L'\0' && i+1<argc)
						pStr=new CStringW(argv[++i]);
					else
						pStr=new CStringW(argv[i]+2);
					
					if ((*pStr)[0]==L'\"')
						pStr->DelChar(0);
					if (pStr->LastChar()==L'\"')
						pStr->DelLastChar();
					while (pStr->LastChar()==L'\\')
						pStr->DelLastChar();
					
					if (pStr->GetLength()>1)
					{
						if ((*pStr)[1]==':' && pStr->GetLength()==2)
							aDatabases.GetLast()->AddRoot(pStr->GiveBuffer());
						else if (FileSystem::IsDirectory(*pStr))
							aDatabases.GetLast()->AddRoot(pStr->GiveBuffer());
						else
							fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr);
					}
					else
						fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr);
					delete pStr;

					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 'e':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && 
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else 
				{
					CStringW* pStr;
					if (argv[i][2]=='\0' && i+1<argc)
						pStr=new CStringW(argv[++i]);
					else
						pStr=new CStringW(argv[i]+2);
					
					if ((*pStr)[0]==L'\"')
						pStr->DelChar(0);
					if (pStr->LastChar()==L'\"')
						pStr->DelLastChar();
					while (pStr->LastChar()==L'\\')
						pStr->DelLastChar();
					
					if (pStr->GetLength()>0)
						aDatabases.GetLast()->SetExcludedFiles(*pStr);

					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 'E':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && 
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else 
				{
					CStringW* pStr;
					if (argv[i][2]=='\0' && i+1<argc)
						pStr=new CStringW(argv[++i]);
					else
						pStr=new CStringW(argv[i]+2);
					
					if ((*pStr)[0]==L'\"')
						pStr->DelChar(0);
					if (pStr->LastChar()==L'\"')
						pStr->DelLastChar();
					while (pStr->LastChar()==L'\\')
						pStr->DelLastChar();
					
					if (pStr->GetLength()>1)
					{
						if (!aDatabases.GetLast()->AddExcludedDirectory(*pStr))
							fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr);
					}
					else
						fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr);
					delete pStr;

					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 't':
			case 'T':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 &&
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else if (argv[i][2]==L'c' || argv[i][2]==L'C')
				{
                       if (argv[i][3]==L'\0')
                           aDatabases.GetLast()->SetCreatorPtr(alloccopy(argv[++i]));
                       else
                           aDatabases.GetLast()->SetCreatorPtr(alloccopy(argv[i]+2));

					   aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				else if (argv[i][2]==L'd' || argv[i][2]==L'D')
				{
                       if (argv[i][3]==L'\0')
                           aDatabases.GetLast()->SetDescriptionPtr(alloccopy(argv[++i]));
                       else
                           aDatabases.GetLast()->SetDescriptionPtr(alloccopy(argv[i]+2));

					   aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 'i':
			case 'I':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 &&
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else
				{
                    aDatabases.GetLast()->SetFlag(CDatabase::flagIncrementalUpdate,TRUE);
					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 'c':
			case 'C':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 &&
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else if (argv[i][2]==L'A' || argv[i][2]==L'a')
				{
					aDatabases.GetLast()->SetFlag(CDatabase::flagAnsiCharset,TRUE);
					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				else if (argv[i][2]==L'U' || argv[i][2]==L'u')
				{
					aDatabases.GetLast()->SetFlag(CDatabase::flagAnsiCharset,FALSE);
					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				
				break;
			case 'N':
			case 'n':
				wCurrentThread++;
				break;
			case 'q':
			case 'Q':
				nQuiet=TRUE;
				break;
			case 'v':
			case 'V':
				printf("%s\n",szVersionStr);
				return 0;
			case 'd':
				{
					// Using database file
					CStringW sFile;
					if (argv[i][2]=='\0')
						sFile=argv[++i];
					else
						sFile=(argv[i]+2);
					
					if (aDatabases.GetSize()==1 && wcscmp(aDatabases[0]->GetName(),L"DEFAULTX")==0)
					{
						aDatabases[0]->SetNamePtr(alloccopy(L"PARAMX"));
						aDatabases[0]->SetArchiveNamePtr(sFile.GiveBuffer());
					}
					else 
					{
						CDatabase* pDatabase=CDatabase::FromFile(sFile,(int)sFile.GetLength());
						if (pDatabase!=NULL)
						{
                            aDatabases.Add(pDatabase);
							pDatabase->SetNamePtr(alloccopy(L"PARAMX"));
							pDatabase->SetThreadId(wCurrentThread);
						}
					}
					

			
				}
				break;
			case 'D':
				{
					// Loading database 'name' from registry, cannot be changed 
					CStringW sName;
					if (argv[i][2]=='\0')
						sName=argv[++i];
					else
						sName=(argv[i]+2);

					if (CDatabase::FindByName(aDatabases,sName,(int)sName.GetLength())==NULL)
					{
						CDatabase* pDatabase=CDatabase::FromName(HKCU,
							CString(g_szRegKey)+"\\Databases",sName);

						if (pDatabase!=NULL)
						{
							pDatabase->SetFlag(CDatabase::flagGlobalUpdate);
							// Is only default loaded
							if (aDatabases.GetSize()==1 && wcscmp(aDatabases[0]->GetName(),L"DEFAULTX")==0)
							{
								delete aDatabases[0];
								aDatabases[0]=pDatabase;
							}
							else
							{
								aDatabases.Add(pDatabase);
								pDatabase->SetThreadId(wCurrentThread);
							}
						}
					}
				}
				break;
			case 'h':
			case 'H':
			case '?':
				helps=1;
				break;
			default:
				helps=1;
				break;
			}
       }
    }
    if (helps==1)
    {
#ifdef WIN32
		fprintf(stdout,"%s\n",szVersionStr);
#else
        fprintf(stdout,"%s\nusage updatedb",szVersionStr);
#endif

		HRSRC hRc=FindResource(GetLanguageSpecificResourceHandle(),MAKEINTRESOURCE(IDR_UPDATEDBHELP),"HELPTEXT");
		HGLOBAL hGlobal=LoadResource(GetLanguageSpecificResourceHandle(),hRc);
		LPCSTR pStr=(LPCSTR)LockResource(hGlobal);

		// Counting length
		int len;
		for (len=0;pStr[len]!='\0';len++)
		{
			if (pStr[len]=='E' && pStr[len+1]=='O' && pStr[len+2]=='F')
				break;
		}


		fwrite(pStr,1,len,stdout);
		
		FreeLibrary(GetLanguageSpecificResourceHandle());
		return 1;
    }

	// Checking databases
	// First, check that there is database 
	if (aDatabases.GetSize()==0)
		CDatabase::LoadFromRegistry(HKCU,CString(g_szRegKey)+"\\Databases",aDatabases);   
	else if (aDatabases.GetSize()==1 && wcsncmp(aDatabases[0]->GetName(),L"DEFAULTX",8)==0)
	{
		aDatabases.RemoveAll();
		CDatabase::LoadFromRegistry(HKCU,CString(g_szRegKey)+"\\Databases",aDatabases);   

		// No registry values?
		if (aDatabases.GetSize()==0)
		{
			aDatabases.Add(CDatabase::FromDefaults(TRUE));
			aDatabases[0]->SetNamePtr(alloccopy(L"DEFAULTX"));
		}
	}
		
		
	CDatabase::CheckValidNames(aDatabases);
	CDatabase::CheckDoubleNames(aDatabases);
	
	
	for (int i=0;i<aDatabases.GetSize();)
	{
		if (!aDatabases[i]->IsGloballyUpdated())
			aDatabases.RemoveAt(i);
		else 
		{
			if ((wcsncmp(aDatabases[i]->GetName(),L"PARAMX",6)==0 ||
				wcsncmp(aDatabases[i]->GetName(),L"DEFAULTX",8)==0))
			{
				BOOL bNameChanged=FALSE;
				if (aDatabases[i]->GetRoots()==0)
				{
					BOOL bFree;
					LPWSTR pFile=aDatabases[i]->GetResolvedArchiveName(bFree);
					CDatabaseInfo* pDatabaseInfo=CDatabaseInfo::GetFromFile(pFile);
					if (bFree)
						delete[] pFile;
					if (pDatabaseInfo!=NULL)
					{
						CDatabase* pDatabase;
						if (!pDatabaseInfo->sExtra2.IsEmpty())
							pDatabase=CDatabase::FromExtraBlock(pDatabaseInfo->sExtra2);
						if (pDatabase==NULL && !pDatabaseInfo->sExtra1.IsEmpty())
							pDatabase=CDatabase::FromExtraBlock(pDatabaseInfo->sExtra1);
						
						wprintf(ID2W(IDS_UPDATEDB32USINGEXISTINGSETTINGS),
							aDatabases[i]->GetArchiveName(),pDatabase->GetName());
						
						pDatabase->SetArchiveType(aDatabases[i]->GetArchiveType());
						pDatabase->SetArchiveName(aDatabases[i]->GetArchiveName());
						
						delete aDatabases[i];
						aDatabases[i]=pDatabase;

						delete pDatabaseInfo;
						bNameChanged=TRUE;
					}
				}

				if (!bNameChanged)
				{
					ULONG_PTR nFirst=LastCharIndex(aDatabases[i]->GetArchiveName(),L'\\')+1;
					int nLength=LastCharIndex(aDatabases[i]->GetArchiveName()+nFirst,L'.');
					if (nLength==-1)
						nLength=istrlenw(aDatabases[i]->GetArchiveName()+nFirst);

					

					aDatabases[i]->SetNamePtr(alloccopy(aDatabases[i]->GetArchiveName()+nFirst,nLength));
				}
			}

			
			i++;
		}
	}

	// Starting to update
	WORD dwTheads=CDatabase::CheckIDs(aDatabases);
    if (dwTheads==0)
	{
		FreeLibrary(GetLanguageSpecificResourceHandle());
		return FALSE;
	}
	if (dwTheads==1)
	{
		CDatabaseUpdater Updater(aDatabases,aDatabases.GetSize(),UpdateProc);
		Updater.Update(FALSE);
	}
	else
	{
		WORD wThread;

		ppUpdaters=new CDatabaseUpdater*[dwTheads+1];

		for (wThread=0;wThread<dwTheads;wThread++)
		{
			ppUpdaters[wThread]=new CDatabaseUpdater(aDatabases,aDatabases.GetSize(),							
				UpdateProc,wThread,(DWORD)0);
		}
		ppUpdaters[dwTheads]=NULL;

		// Starting
		DWORD dwRunning=0;
		UpdateError ueCode;
		for (wThread=0;wThread<dwTheads;wThread++)
		{
			ueCode=ppUpdaters[wThread]->Update(TRUE);
			if (ueCode==ueSuccess)
				dwRunning++;
			else
			{
				delete ppUpdaters[wThread];
				ppUpdaters[wThread]=UPDATER_EXITED(ueCode);
			}
		}
		
		if (dwRunning==0)
			delete ppUpdaters;
		else
		{
			while (ppUpdaters!=NULL)
				Sleep(100);
		}
	}

	FinishRegKey();

	FreeLibrary(GetLanguageSpecificResourceHandle());

	return 1;
}
Example #16
0
int main(int argc, char **argv) {
    program_name = L"fish_key_reader";
    bool continuous_mode = false;
    const char *short_opts = "+cd:D:";
    const struct option long_opts[] = {{"continuous", no_argument, NULL, 'c'},
                                       {"debug-level", required_argument, NULL, 'd'},
                                       {"debug-stack-frames", required_argument, NULL, 'D'},
                                       {NULL, 0, NULL, 0}};
    int opt;
    while ((opt = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
        switch (opt) {
            case 0: {
                fprintf(stderr, "getopt_long() unexpectedly returned zero\n");
                exit(1);
            }
            case 'c': {
                continuous_mode = true;
                break;
            }
            case 'd': {
                char *end;
                long tmp;

                errno = 0;
                tmp = strtol(optarg, &end, 10);

                if (tmp >= 0 && tmp <= 10 && !*end && !errno) {
                    debug_level = (int)tmp;
                } else {
                    fwprintf(stderr, _(L"Invalid value '%s' for debug-level flag"), optarg);
                    exit(1);
                }
                break;
            }
            case 'D': {
                char *end;
                long tmp;

                errno = 0;
                tmp = strtol(optarg, &end, 10);

                if (tmp > 0 && tmp <= 128 && !*end && !errno) {
                    debug_stack_frames = (int)tmp;
                } else {
                    fwprintf(stderr, _(L"Invalid value '%s' for debug-stack-frames flag"), optarg);
                    exit(1);
                }
                break;
            }
            default: {
                // We assume getopt_long() has already emitted a diagnostic msg.
                exit(1);
            }
        }
    }

    argc -= optind;
    if (argc != 0) {
        fprintf(stderr, "Expected no arguments, got %d\n", argc);
        return 1;
    }

    if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO)) {
        fprintf(stderr, "Stdin and stdout must be attached to a tty, redirection not allowed.\n");
        return 1;
    }

    setup_and_process_keys(continuous_mode);
    return 0;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method: GetRightsForKID
// Description: Prints "is allowed" rights information to a report file for 
//  a given Key ID.
// Parameters: KID - Key ID string.
//
///////////////////////////////////////////////////////////////////////////////
HRESULT CRightsReporter::GetRightsForKID(BSTR KID)
{
    HRESULT hr = S_OK;

    // Get the rights information.
    if (SUCCEEDED(hr))
    {
        hr = m_pLicenseQuery->QueryActionAllowed(KID, 
                                                NULL, 
                                                m_cIsAllowedRights, 
                                                m_IsAllowedRights, 
                                                m_IsAllowedResults);
    }

    // Print the results to the output file.
    if (SUCCEEDED(hr))
    {
        // Loop through the results, reporting on each.
        for (int i = 0; i < m_cIsAllowedRights; i++)
        {
            fwprintf(m_pFile, L"%-35.35s - ", m_IsAllowedRights[i]);

            // Check the query result.
            if (m_IsAllowedResults[i] == 0)
            {
                fwprintf(m_pFile, L"Allowed\n\n");
            }
            else
            {
                // The action is not allowed.
                fwprintf(m_pFile, L"Not Allowed\n");

                // If the action is not allowed, check the result against the
                //  possible failure flags and report the reasons.
                
                // The DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED flag is set for any
                //  not allowed result. Only list it if no other reason is 
                //  provided.
                if ((m_IsAllowedResults[i] & 0xFFFFFFFF)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED)
                {
                    fwprintf(m_pFile, L"   Not allowed for an unspecified reason.\n");
                }

                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NO_LICENSE)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NO_LICENSE)
                {
                    fwprintf(m_pFile, L"   No license for this KID.\n");
                }

                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NO_RIGHT)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NO_RIGHT)
                {
                    fwprintf(m_pFile, L"   License does not grant this right.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_EXHAUSTED)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_EXHAUSTED)
                {
                    fwprintf(m_pFile, L"   Licensed counts for this right exhausted.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_EXPIRED)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_EXPIRED)
                {
                    fwprintf(m_pFile, L"   License expired.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NOT_STARTED)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NOT_STARTED)
                {
                    fwprintf(m_pFile, L"   License is not yet in effect.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_APPSEC_TOO_LOW)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_APPSEC_TOO_LOW)
                {
                    fwprintf(m_pFile, L"   Application security level is too low.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_REQ_INDIV)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_REQ_INDIV)
                {
                    fwprintf(m_pFile, L"   License requires security update.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_COPY_OPL_TOO_LOW)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_COPY_OPL_TOO_LOW)
                {
                    fwprintf(m_pFile, L"   Cannot copy to the configured device.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_COPY_OPL_EXCLUDED)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_COPY_OPL_EXCLUDED)
                {
                    fwprintf(m_pFile, L"   Configured device excluded from license.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NO_CLOCK_SUPPORT)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NO_CLOCK_SUPPORT)
                {
                    fwprintf(m_pFile, L"   License requires a secure clock.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NO_METERING_SUPPORT)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_NO_METERING_SUPPORT)
                {
                    fwprintf(m_pFile, L"   License requires metering.\n");
                }


                if ((m_IsAllowedResults[i] & DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_CHAIN_DEPTH_TOO_HIGH)
                    == DRM_ACTION_ALLOWED_QUERY_NOT_ENABLED_CHAIN_DEPTH_TOO_HIGH)
                {
                    fwprintf(m_pFile, L"   Incomplete license chain.\n");
                }

                // Print a newline character for spacing between entries.
                fwprintf(m_pFile, L"\n");
            }
        } // End for loop.
    }

    return hr;
}
Example #18
0
void ReadSettings()
{
	Interpolation = CfgReadInt( L"MIXING",L"Interpolation", 4 );

	EffectsDisabled = CfgReadBool( L"MIXING", L"Disable_Effects", false );
	postprocess_filter_dealias = CfgReadBool( L"MIXING", L"DealiasFilter", false );
	FinalVolume = ((float)CfgReadInt( L"MIXING", L"FinalVolume", 100 )) / 100;
		if ( FinalVolume > 1.0f) FinalVolume = 1.0f;

	AdvancedVolumeControl = CfgReadBool(L"MIXING", L"AdvancedVolumeControl", false);
	VolumeAdjustCdb = CfgReadFloat(L"MIXING", L"VolumeAdjustC(dB)", 0);
	VolumeAdjustFLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFL(dB)", 0);
	VolumeAdjustFRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustFR(dB)", 0);
	VolumeAdjustBLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBL(dB)", 0);
	VolumeAdjustBRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustBR(dB)", 0);
	VolumeAdjustSLdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSL(dB)", 0);
	VolumeAdjustSRdb = CfgReadFloat(L"MIXING", L"VolumeAdjustSR(dB)", 0);
	VolumeAdjustLFEdb = CfgReadFloat(L"MIXING", L"VolumeAdjustLFE(dB)", 0);
	VolumeAdjustC = powf(10, VolumeAdjustCdb / 10);
	VolumeAdjustFL = powf(10, VolumeAdjustFLdb / 10);
	VolumeAdjustFR = powf(10, VolumeAdjustFRdb / 10);
	VolumeAdjustBL = powf(10, VolumeAdjustBLdb / 10);
	VolumeAdjustBR = powf(10, VolumeAdjustBRdb / 10);
	VolumeAdjustSL = powf(10, VolumeAdjustSLdb / 10);
	VolumeAdjustSR = powf(10, VolumeAdjustSRdb / 10);
	VolumeAdjustLFE = powf(10, VolumeAdjustLFEdb / 10);

	SynchMode = CfgReadInt( L"OUTPUT", L"Synch_Mode", 0);
	numSpeakers = CfgReadInt( L"OUTPUT", L"SpeakerConfiguration", 0);
	dplLevel = CfgReadInt( L"OUTPUT", L"DplDecodingLevel", 0);
	SndOutLatencyMS = CfgReadInt(L"OUTPUT",L"Latency", 100);

	if((SynchMode == 0) && (SndOutLatencyMS < LATENCY_MIN_TS)) // can't use low-latency with timestretcher atm
		SndOutLatencyMS = LATENCY_MIN_TS;
	else if(SndOutLatencyMS < LATENCY_MIN)
		SndOutLatencyMS = LATENCY_MIN;

	wchar_t omodid[128];

	if ( IsVistaOrGreater2() ) {		// XA2 for WinXP, morder modern gets Portaudio
		CfgReadStr(L"OUTPUT", L"Output_Module", omodid, 127, PortaudioOut->GetIdent());
	}
	else {
		CfgReadStr(L"OUTPUT", L"Output_Module", omodid, 127, XAudio2Out->GetIdent());
	}

	// find the driver index of this module:
	OutputModule = FindOutputModuleById( omodid );

	CfgReadStr( L"DSP PLUGIN",L"Filename",dspPlugin,255,L"");
	dspPluginModule = CfgReadInt(L"DSP PLUGIN",L"ModuleNum",0);
	dspPluginEnabled= CfgReadBool(L"DSP PLUGIN",L"Enabled",false);

	// Read DSOUNDOUT and WAVEOUT configs:
	CfgReadStr( L"WAVEOUT", L"Device", Config_WaveOut.Device, L"default" );
	Config_WaveOut.NumBuffers = CfgReadInt( L"WAVEOUT", L"Buffer_Count", 4 );

	DSoundOut->ReadSettings();
	PortaudioOut->ReadSettings();

	SoundtouchCfg::ReadSettings();
	DebugConfig::ReadSettings();

	// Sanity Checks
	// -------------

	Clampify( SndOutLatencyMS, LATENCY_MIN, LATENCY_MAX );

	if( mods[OutputModule] == NULL )
	{
		// Unsupported or legacy module.
		fwprintf( stderr, L"* SPU2-X: Unknown output module '%s' specified in configuration file.\n", omodid );
		fprintf( stderr, "* SPU2-X: Defaulting to DirectSound (%S).\n", DSoundOut->GetIdent() );
		OutputModule = FindOutputModuleById( DSoundOut->GetIdent() );
	}
}
Example #19
0
/*
 * XDR an array of arbitrary elements
 * *addrp is a pointer to the array, *sizep is the number of elements.
 * If addrp is NULL (*sizep * elsize) bytes are allocated.
 * elsize is the size (in bytes) of each element, and elproc is the
 * xdr procedure to call to handle each element of the array.
 */
bool_t
xdr_array (XDR *xdrs, caddr_t *addrp, u_int *sizep, u_int maxsize, u_int elsize, xdrproc_t elproc)
{
  u_int i;
  caddr_t target = *addrp;
  u_int c;		/* the actual element count */
  bool_t stat = TRUE;
  u_int nodesize;

  /* like strings, arrays are really counted arrays */
  if (!xdr_u_int (xdrs, sizep))
    {
      return FALSE;
    }
  c = *sizep;
  /*
   * XXX: Let the overflow possibly happen with XDR_FREE because mem_free()
   * doesn't actually use its second argument anyway.
   */
  if ((c > maxsize || c > UINT_MAX / elsize) && (xdrs->x_op != XDR_FREE))
    {
      return FALSE;
    }
  nodesize = c * elsize;

  /*
   * if we are deserializing, we may need to allocate an array.
   * We also save time by checking for a null array if we are freeing.
   */
  if (target == NULL)
    switch (xdrs->x_op)
      {
      case XDR_DECODE:
	if (c == 0)
	  return TRUE;
	*addrp = target = mem_alloc (nodesize);
	if (target == NULL)
	  {
#ifdef USE_IN_LIBIO
	    if (_IO_fwide (stderr, 0) > 0)
	      (void) fwprintf (stderr, L"%s",
				 _("xdr_array: out of memory\n"));
	    else
#endif
	      (void) fputs (_("xdr_array: out of memory\n"), stderr);
	    return FALSE;
	  }
	memset (target, 0, nodesize);
	break;

      case XDR_FREE:
	return TRUE;
      default:
	break;
      }

  /*
   * now we xdr each element of array
   */
  for (i = 0; (i < c) && stat; i++)
    {
      stat = (*elproc) (xdrs, target, LASTUNSIGNED);
      target += elsize;
    }

  /*
   * the array may need freeing
   */
  if (xdrs->x_op == XDR_FREE)
    {
      mem_free (*addrp, nodesize);
      *addrp = NULL;
    }
  return stat;
}
Example #20
0
int MalieExec::ExportStrByCode(void)
{
	CMalie_VMParse vm(this);
	vector<wstring> chapterName;
	vector<DWORD> chapterIndex;
	vector<DWORD> chapterRegion;
	vector<Malie_Moji> && moji = vm.ParseScenario(chapterName,chapterIndex);

	if (!chapterName.size())
	{
		vector<DWORD>::iterator it = unique(chapterIndex.begin(),chapterIndex.end());
		chapterIndex.erase(it,chapterIndex.end());
	}

	auto exportFunc = [&](pair<DWORD,wstring>(&x),FILE *fp){
		fwprintf(fp,L"○%08d○\n%s●%08d●\n%s◇%08d◇\n\n\n",
			x.first,x.second.c_str(),x.first,x.second.c_str(),x.first);
	};

	fprintf(stderr,"\nStarting dumping text to file...\n");

	if (chapterIndex.size())
	{
		chapterRegion = chapterIndex;
		chapterRegion.erase(chapterRegion.begin());
		chapterRegion.push_back(moji.size());
		for (size_t i=0;i<chapterIndex.size();++i)
		{
			wstring && name = i<chapterName.size()?
				stringf(L"%02d %ls.txt",i,chapterName[i].c_str()):
				stringf(L"%02d.txt",i);

			FILE *fp;
			_wfopen_s(&fp,name.c_str(),L"wt,ccs=UNICODE");

			for_each(moji.begin()+chapterIndex[i],moji.begin()+chapterRegion[i],[&](Malie_Moji x)
			{
				wstring kotoba;
				if (!x.name.empty())
				{
					kotoba = x.name+L"※";
				}
				kotoba += ParseString(x.index);

				exportFunc(pair<DWORD,wstring>(x.index,kotoba),fp);
				fflush(fp);
			});

			fclose(fp);
		}
	}
	else
	{
		FILE *fp;
		_wfopen_s(&fp,L"MalieMoji.txt",L"wb");
        fwrite("\xff\xfe", 1, 2, fp);

        //for_each(moji.begin(), moji.end(), [&](Malie_Moji x)
        //{
        //    wstring kotoba;
        //    if (!x.name.empty())
        //    {
        //        kotoba = x.name + L"※";
        //    }
        //    kotoba += ParseString(x.index);

        //    exportFunc(pair<DWORD, wstring>(x.index, kotoba), fp);
        //});
        auto write_crln = [](FILE* fp) {
            fwrite(L"\r\n", 2, 2, fp);
        };
        for (auto& x : moji) {
            wchar_t tag[100];
            auto cnt = swprintf_s(tag, L"#%05d %s", x.index, x.name.c_str());
            fwrite(tag, 2, cnt, fp);
            write_crln(fp);

            auto s = GetString(x.index);
            MalieString str(s);
            str.init();
            auto v = str.export_str();
            
            for (auto& s : v) {
                fwrite(s.c_str(), 2, s.length(), fp);
                write_crln(fp);
            }
        }

		fclose(fp);

        fp = fopen("str.txt", "wb");
        fwrite("\xff\xfe", 1, 2, fp);
        auto fp2 = fopen("str.idx", "wb");
        auto write_tbl = [&](map<int, wstring>& tbl) {
            for (auto& itr : tbl) {
                fwrite(&itr.first, 1, 4, fp2);
                fwrite(itr.second.c_str(), 2, itr.second.length(), fp);
                write_crln(fp);
            }
        };
        write_tbl(vm.get_name_data_table());
        write_tbl(vm.get_sel_data_table());
        
        fclose(fp);
        fclose(fp2);
	}

	fprintf(stderr,"Done.\n");
	return 0;
}
Example #21
0
/****
 * DumpEventInfo
 *
 * DESC:
 *     This function has two purposes depending on the mode. It will
 *     either (1) Print the contents of an event (if normal mode) or
 *     (2) return the latest record ID (if "last record" mode)
 *
 * ARGS:
 *     hRemote - Remote session context
 *     hResults - An open set of results
 *     outputFormat - 0 for JSON, otherwise XML
 *     mode - last record vs print results
 *     debug - set to 0 (none) 1 (basic) or 2 (verbose)
 *
 * REMARKS:
 */
DWORD64 DumpEventInfo(EVT_HANDLE hRemote, EVT_HANDLE hEvent, INT outputFormat, INT mode, INT debug)
{
    DWORD64 dwError = ERROR_SUCCESS;
    DWORD dwBufferSize = 0;
    DWORD dwBufferUsed = 0;
    DWORD dwPropertyCount = 0;
    LPWSTR pwsBuffer = NULL;
	rapidxml::xml_document<WCHAR> doc;

	if( debug >= DEBUG_L2 ) {
		wprintf(L"[DumpEventInfo]: Attempting to read event XML with no buffer\n" );
	}

    // Attempt to read the event as an XML string
	//
	// Note: We are expecting this call to fail, as we have NOT provided a buffer. Therefore
	// the purpose of this call is to fail, and have dwBufferUsed updated with required space	
    if (!EvtRender(NULL, hEvent, EvtRenderEventXml, dwBufferSize, pwsBuffer, &dwBufferUsed, &dwPropertyCount)) 
	{
		// Reading was NOT successful, as expected
		if( debug >= DEBUG_L2 ) {
			wprintf(L"[DumpEventInfo]: Required buffer space: %lu\n", dwBufferUsed );
		}

		// Get the error code
		dwError = GetLastError();

		if( debug >= DEBUG_L2 ) {
			wprintf(L"[DumpEventInfo]: Raw error code is: %lu\n", dwError );
		}

		// If call failed due to insufficient buffer (as we should expect)
        if (dwError == ERROR_INSUFFICIENT_BUFFER)
        {
			if( debug >= DEBUG_L2 ) {
				wprintf(L"[DumpEventInfo]: Last error code is insufficient buffer (as expecteted)\n" );
			}

			// Adjust the buffer size to the required amount as indicated by dwBufferUsed		
            dwBufferSize = dwBufferUsed;

			if( debug >= DEBUG_L2 ) {
				wprintf(L"[DumpEventInfo]: Attempting to reallocate buffer size: %lu\n", dwBufferSize );
			}

			// Re-allocate our buffer with the required size
            pwsBuffer = (LPWSTR)malloc(dwBufferSize);

			// If allocaton was successful
            if (pwsBuffer)
            {
				if( debug >= DEBUG_L2 ) {
					wprintf(L"[DumpEventInfo]: Allocation successful. Re-attempting to read event data\n" );
				}

				// Re-attempt to read event (as XML) now that we have appropriate buffer size
                if( EvtRender(NULL, hEvent, EvtRenderEventXml, dwBufferSize, pwsBuffer, &dwBufferUsed, &dwPropertyCount) ) 
				{
					if( debug >= DEBUG_L2 ) {
						wprintf(L"[DumpEventInfo]: Read successful. Last error code is: %lu\n", dwError );
					}

					// Reading was successful
					dwError = GetLastError();

					if( debug >= DEBUG_L2 ) {
						wprintf( L"[DumpEventInfo]: Raw XML: %s\n", pwsBuffer );
					}

					// Parse the XML string into our XML reader
					doc.parse<0>( pwsBuffer );

					if( debug >= DEBUG_L2 ) {
						wprintf( L"[DumpEventInfo]: XML parsing successful\n" );
					}

					// Retrieve the <Event> node
					rapidxml::xml_node<WCHAR> *nodeEvent = doc.first_node(L"Event");

					// Retrieve the <System> node
					rapidxml::xml_node<WCHAR> *nodeSystem = nodeEvent->first_node(L"System");
					// Children of the <System> node
					// You will recongize these as elements when viewing the event log in your viewer
					rapidxml::xml_node<WCHAR> *nodeEventID = nodeSystem->first_node(L"EventID");
					rapidxml::xml_node<WCHAR> *nodeChannel = nodeSystem->first_node(L"Channel");
					rapidxml::xml_node<WCHAR> *nodeEventRecordID = nodeSystem->first_node(L"EventRecordID");
					rapidxml::xml_node<WCHAR> *nodeProvider = nodeSystem->first_node(L"Provider");
					rapidxml::xml_node<WCHAR> *nodeComputer = nodeSystem->first_node(L"Computer");
					rapidxml::xml_node<WCHAR> *nodeTimeCreated = nodeSystem->first_node(L"TimeCreated");
					rapidxml::xml_node<WCHAR> *nodeTask = nodeSystem->first_node(L"Task");
					rapidxml::xml_node<WCHAR> *nodeLevel = nodeSystem->first_node(L"Level");

					if( debug >= DEBUG_L2 ) {
						wprintf( L"[DumpEventInfo]: Extracting XML elements successful\n" );
					}

					// Recall there are two modes. The default mode will parse the event log XML, and the "last record" mode
					// (called MODE_FETCH_LAST_RECORD) will fetch only the last record and exit afterwards. 
					if( mode == MODE_FETCH_LAST_RECORD ) {
						if( debug >= DEBUG_L2 ) {
							wprintf( L"[DumpEventInfo]: Record ID is '%s'\n", nodeEventRecordID->value() );
						}

						DWORD64 lastRecord = _wcstoui64( nodeEventRecordID->value(), NULL, 10 );

						if( debug >= DEBUG_L2 ) {
							wprintf( L"[DumpEventInfo]: Record ID converted to 64-bit number: %I64d\n", lastRecord );
						}

						return lastRecord;
					}

					// Extract the publisher name from the <Provider> node
					// We will need this to lookup the message string for this publisher
					LPWSTR pwszPublisherName = nodeProvider->first_attribute(L"Name")->value();

					if( debug >= DEBUG_L2 ) {
						wprintf( L"[DumpEventInfo] Publisher is: %s\n", pwszPublisherName );
					}

					// Setup an empty string to read the message string
					LPWSTR pwsMessage = NULL;

					// Get the handle to the provider's metadata that contains the message strings.
					EVT_HANDLE hProviderMetadata = EvtOpenPublisherMetadata(hRemote, pwszPublisherName, NULL, 0, 0);

					// If a provider handle was found
					if( hProviderMetadata != NULL ) 
					{
						if( debug >= DEBUG_L2 ) {
							wprintf( L"[DumpEventInfo] Publisher metadata found. Attempting to get message string\n");
						}

						// Get the message string associated with this event type
						pwsMessage = GetEventMessageDescription(hProviderMetadata, hEvent);

						// If a message was not found, default to an empty string
						if( pwsMessage == NULL ) {
							// Why are we setting to empty string?
							//pwsMessage = L"";

							if( debug >= DEBUG_L2 ) {
								wprintf( L"[DumpEventInfo] Message string not found. Assume empty\n");
							}
						}
					}
					else 
					{
						// Publisher/provider cannot be found. Do not display an error message. It occurs all too often when a 
						// publisher is not found, and skews the JSON results. when it prints itself to the main screen
						// printf("Error: EvtOpenPublisherMetadata for %s failed with %d\n", pwszPublisherName, GetLastError());						

						// Default the publisher to an empty string so we can continue
						pwszPublisherName = L"";

						if( debug >= DEBUG_L2 ) {
							wprintf( L"[DumpEventInfo] Publisher metadata not found. Assume empty\n");
						}
					}

					// We have all the results; print them to the screen
					if( outputFormat == OUTPUT_FORMAT_JSON ) 
					{
						wprintf(L"{\"record_id\":\"%s\",\"event_id\":\"%s\",\"logname\":\"%s\",\"source\":\"%s\",\"computer\":\"%s\",\"time_created\":\"%s\",\"task\":\"%s\",\"level\":\"%s\"", 
							nodeEventRecordID->value(), 
							nodeEventID->value(), 
							nodeChannel->value(), 
							nodeProvider->first_attribute(L"Name")->value(), 
							nodeComputer->value(), 
							nodeTimeCreated->first_attribute(L"SystemTime")->value(),
							nodeTask->value(),
							nodeLevel->value());
						
						// If a message string was found
						if( pwsMessage != NULL ) 
						{
							wprintf(L",\"message\":\"%s\"}", pwsMessage);

							if( debug >= DEBUG_L2 ) {
								wprintf( L"[DumpEventInfo] Attempting to free pwsMessage\n");
							}

							free(pwsMessage);

							if( debug >= DEBUG_L2 ) {
								wprintf( L"[DumpEventInfo] pwsMessage successfully freed\n");
							}
						} 
						else 
						{
							wprintf(L",\"message\":\"\"}");

							if( debug >= DEBUG_L2 ) {
								wprintf( L"[DumpEventInfo] No pwsMessage found to free\n");
							}
						}
					} 
					else 
					{
						// Note: A new line is not printed yet (see next steps)
						wprintf(L"%s||%s||%s||%s||%s||%s||%s||%s||", 
							nodeEventRecordID->value(), 
							nodeEventID->value(), 
							nodeChannel->value(), 
							nodeProvider->first_attribute(L"Name")->value(), 
							nodeComputer->value(), 
							nodeTimeCreated->first_attribute(L"SystemTime")->value(),
							nodeTask->value(),
							nodeLevel->value());

						// If a message string was found
						if( pwsMessage != NULL ) 
						{
							wprintf(L"%s\n", pwsMessage);
							free(pwsMessage);
						} 
						else 
						{
							wprintf(L"(no message provided)\n");
						}
					}
				} 
				else
				{
					// Reading was NOT successful

					// This time we were not expecting it to fail. Get the error code
					dwError = GetLastError();

					// Print error results to the screen
					fwprintf(stderr, L"[DumpEventInfo] Failed to render results with: %d\n", GetLastError());

					// Free up our allocation
					free(pwsBuffer);
				}				
            }
            else
            {
				// Allocation was unsuccessful
                fwprintf(stderr, L"[DumpEventInfo] malloc failed\n");
                dwError = ERROR_OUTOFMEMORY;
            }
        }
	}

	if( debug >= DEBUG_L2 ) {
		wprintf( L"[DumpEventInfo]: Data dump completed\n" );
	}

    return dwError;
}
Example #22
0
/*  
 *  getopt
 *
 *  Description:
 *      This funtion will parse command line options passed in the argv
 *      array in a program's main() routine.
 *
 *  Parameters:
 *      argc
 *          The argument count passed to main()
 *      argv
 *          The argument array passed to main()
 *      option_string
 *          The string of options.  The string contains letters representing
 *          the single character options.  If an option requires an argument
 *          to follow, a ":" is placed after the option in the option string.
 *          (That implies that ":" is not a valid option character).  Options
 *          are preceded by "optflag" character (default is "-").  Two
 *          option characters together (i.e., "--" when using the default
 *          option flag) on the command line signals getopt to stop processing
 *          options and return EOF.
 *
 *  Returns:
 *      This function will return the character of the current option, "?"
 *      if the option on the command line is invalid, or EOF once the end
 *      of the options has been reached.  Any errors encountered during
 *      the processing of the command line will result in messages displayed
 *      to STDERR unless the variable opterr is set to 0.  If an invalid
 *      option is found, the offending option character is stored in the
 *      variable optopt since the return value is "?".  (Note that an
 *      invalid option is either one not found in the option string or
 *      an option that should be followed with an argument, but is not.)
 *
 *  Comments:
 *      Like the UNIX version of getopt, this function must be used with care.
 *      If EOF is returned, getopt should never be called again.  If it
 *      is, the behavior should be considered "undefined".  If an option
 *      that requires an argument is, instead, followed by another
 *      option, the second option will mistakenly be taken as the argument.
 *      This is unfortunate, but is consistent with the UNIX version.
 *
 */
int getopt( int             argc,
            TCHAR * const *argv,
            const TCHAR   *option_string)
{
    int         current_option;
    const TCHAR     *option_index;
    static int  array_index = 0;
    static int  end_of_options = 0;

    /*
     *  If we have already detected the end of the options array, return EOF.
     */
    if (end_of_options)
    {
        return EOF;
    }

    /*
     *  Check to see if we are at the end of our options array.
     */
    if (optind >= argc)
    {
        end_of_options = 1;
        return EOF;
    }

    /*
     *  We will support multiple arguments following a single argument flag.
     *  We will do this by using the static variable array_index.
     *  If array_index is 0, make sure that argv[optind][array_index]
     *  is optflag.  If not, we can assume we are at the end of the options.
     */
    if (!array_index)
    {
        /*
         *  Verify that the first character is the options flag.  If not,
         *  return EOF.
         */
        if (argv[optind][0] != optflag)
        {
            end_of_options = 1;
            return EOF;
        }

        /*
         *  Command line program historically denote a "STDIN" parameter
         *  as a single "-".  To be consistent with the UNIX version of
         *  getopt, we will return EOF if we see a singe optflag character,
         *  but we will not increment the optind value.
         */
        if (argv[optind][1] == '\0')
        {
            end_of_options = 1;
            return EOF;
        }

        /*
         *  If we see two optflag characters together, we will assume
         *  we should stop processing options.  We will increment the
         *  optind value so that the calling routine can process any
         *  addition arguments passed into main().
         */
        if (argv[optind][1] == optflag && argv[optind][2] == '\0')
        {
            optind++;
            end_of_options = 1;
            return EOF;
        }

        /*
         *  Move the array_index past the option flag
         */
        array_index++;
    }

    /*
     *  Get the next option character.
     */
    optopt = current_option = argv[optind][array_index++];

    /*
     *  Verify that it is a valid option.
     */
    if (current_option != ':' &&
        (option_index = _tcschr(option_string, current_option)) != NULL)
    {
        /*
         *  Check to see if this option should have an argument by looking
         *  at the next character in the option_string.
         */
        if (*(option_index+1) == ':')
        {
            /*
             *  Check to see if the argument is sitting beside the
             *  option in the argv array element.
             */
            if (argv[optind][array_index] != '\0')
            {
                /*
                 *  Take the remainder of the argv element to be the string.
                 */
                optarg = &argv[optind][array_index];
            }
            else
            {
                /*
                 *  The argument must be in the next argv element.  We
                 *  will increment optind and try to locate the argument
                 *  there.
                 */
                optind++;

                /*
                 *  If we do not have an argument, we should report an error.
                 */
                if (optind >= argc)
                {
                    /*
                     *  Since we could not find an argument for the option,
                     *  we will report an error if the opterr variable has
                     *  not been set to 0.
                     */
                    if (opterr)
                    {
                        fwprintf(   stderr,
                                    L"%s: option requires an argument -- %c\n",
                                    argv[0],
                                    current_option);
                    }

                    /*
                     *  Re-assign the current option value so that we
                     *  return a '?' on errors.
                     */
                    current_option = '?';
                }
                else
                {
                    /*
                     *  We've found the argument in the next argv element.
                     *  We will assign the address to optarg and then
                     *  move optind to point to the next element.
                     */
                    optarg = argv[optind];
                }
            }

            /*
             *  Since this option took an argument, we will want to
             *  advance the optind value and reset the array_index
             *  in preparation for the next call to getopt().
             */
            optind++;
            array_index = 0;
        }
    }
    else
    {
        /*
         *  Since we have an illegal argument, we will report it if
         *  the opterr variable has not been set to 0.
         */
        if (opterr)
        {
            fwprintf(   stderr,
                        L"%s: illegal option -- %c\n",
                        argv[0],
                        current_option);
        }

        /*
         *  Re-assign the current option value so that we
         *  return a '?' on errors.
         */
        current_option = '?';
    }

    /*
     *  If we are processing options in a single argv element and
     *  we have reached the end of the string, reset the array_index
     *  value and advance optind.
     */
    if (array_index && argv[optind][array_index] == '\0')
    {
        array_index = 0;
        optind++;
    }

    return current_option;
}
Example #23
0
/****
 * ParseEventLogInternal
 *
 * DESC:
 *     Gets the most recent event log record
 *
 * ARGS:
 *     server - IP or host to connect to
 *     domain - domain within the host (empty string for none)
 *     username - username within the domain
 *     password - password for above user
 *     logName - event log to open (default to "Application" if NULL)
 *     query - XPath query to retrieve (see remarks)
 *     outputFormat - set to 0 (JSON) otherwise XML
 *     debug - set to 0 (none) 1 (basic) or 2 (verbose)
 *     mode - mode to run the parser (see remarks)
 *
 * REMARKS:
 *     XPath:
 * 
 *     The Windows Event log is structurally an XML document. You
 *     may therefore use XPath queries to retrieve the information 
 *     you want. Pre-defined XPath queries have been built into the
 *     supplementary Perl module. However, you are free to modify
 *     that module to include newer queries, based on your requirements
 *
 *     mode:
 *
 *     Can be set to either MODE_FETCH_LAST_RECORD or MODE_DEFAULT. The
 *     former will simply return the Event Log Record ID of the topmost
 *     (i.e. the latest) event record. The latter will do the actual
 *     processing of parsing an event log record to the screen.
 *
 *     Note: As per previous discussions, output format is forced as
 *     JSON here. To re-allow XML, simply replace OUTPUT_FORMAT_JSON
 *     with outputFormat, in the line of code, below
 */
DWORD64 ParseEventLogInternal(LPWSTR server, LPWSTR domain, LPWSTR username, LPWSTR password, LPWSTR logName, LPWSTR query, INT outputFormat, INT debug, INT mode) {	
	bool getLastRecord = false;
	DWORD64 result = 0;

	if( debug > DEBUG_L1 ) {
		wprintf(L"[ParseEventLogInternal]: Attempting to connect to '%s' on domain '%s' using %s:%s...\n", server, domain, username, password);
	}

	// If no domain was supplied
	if( wcslen(domain) == 0 ) {
		// Official MSDN specs request NULL instead of an empty string
		domain = NULL;

		if( debug >= DEBUG_L1 ) {
			wprintf(L"[ParseEventLogInternal]: Empty domain supplied. Default to NULL\n");
		}		
	}
		
	// If a blank query was supplied, assume no query (NULL)
	if( lstrlen(query) == 0 )
		query = NULL;

	// If the supplied query is our special token that retrieves the last record
	if( lstrcmpW( query, L"LAST_RECORD") == 0 ) {
		if( debug >= DEBUG_L1 ) {
			wprintf(L"[ParseEventLogInternal]: Mode is last record fetch\n");
		}

		// Flag the processing routine to only fetch the lastest record
		getLastRecord = true;

		// Force an empty query so that the last record is not affected by query filters
		// An empty query means it will get ALL records, in which case we are guaranteed
		// the latest record (i.e. the record ID we want) is the first to be retrieved
		query = NULL;
	} else {
		if( debug >= DEBUG_L1 ) {
			if( query == NULL ) {
				wprintf(L"[ParseEventLogInternal]: (no query specified)\n");
			} else {
				wprintf(L"[ParseEventLogInternal]: Using query: %s\n", query);
			}
		}
	}

	// Create a remote context to the external server
    EVT_HANDLE hRemote = CreateRemoteSession(server, domain, username, password);

    if (hRemote != NULL)
    {
		// NOTE: Reaching here does not mean the connection succeeded. It merely 
		// means that we successfully created the remote context

		if( debug >= DEBUG_L1 ) {
			wprintf(L"[ParseEventLogInternal]: Attempting to query the EventLog...\n\n", hRemote);
		}

		// Attempt to query event log in reverse chronological order (newest to oldest)
		EVT_HANDLE hResults = EvtQuery( hRemote, logName, query, EvtQueryChannelPath | EvtQueryReverseDirection);

		// If the query was successful
		if (hResults != NULL) 
		{
			// Process the first event found
			DumpEventInfo(hRemote, hResults, outputFormat, getLastRecord ? MODE_FETCH_LAST_RECORD : 0, debug);

			// Process subsequent events
			result = ProcessResults(hRemote, hResults, outputFormat, getLastRecord ? MODE_FETCH_LAST_RECORD : 0, debug);
		}
		else
		{
			// Query was not successful. Get the error code
			DWORD dwError = GetLastError();

			if (dwError == ERROR_EVT_CHANNEL_NOT_FOUND) 
			{
				fwprintf(stderr, L"[Error][ParseEventLog]: Could not open the '%s' log on this machine.\n", logName);
			}
			else if (dwError == ERROR_EVT_INVALID_QUERY)
			{
				// You can call the EvtGetExtendedStatus function to try to get 
				// additional information as to what is wrong with the query.
				fwprintf(stderr, L"[Error][ParseEventLog]: The specified search query is not valid.\n");
			}
			else
			{
				fwprintf(stderr, L"[Error][ParseEventLog]: Could not read event logs due to the following Windows error: %lu.\n", dwError);
			}
		}

		// Close the handle to the query we opened
		EvtClose(hRemote);
    }
	else 
	{
        fwprintf(stderr, L"[Error][ParseEventLog]: Failed to connect to remote computer. Error code is %d.\n", GetLastError());
	}

	return result;
}
Example #24
0
/**
* Load the character map table from a file.
*
* @param cm     Character Map to load the table into.
* @param path   The path of the file to load.
* @return       Zero if the file is loaded fine, nonzero otherwise.
*/
static int charmap_load(CHARMAP* cm, const char* path)
{
  FILE* is = NULL;
  int section = 0;
  int error_code = 0;

  /* Open */
  is = fopen(path, "rt");
  if(!is) {
    perror("path");
    return 1;
  }

  /* Load */
  while(!feof(is)) {
    wchar_t unicode[MAX_UNICODE_SEQ];
    int ulen = 0;

    char buf[256];
    char flag[256];

    int scanned = 0;

    /* Scan a single token first */
    scanned = fscanf(is, "%255s", buf);
    if(scanned < 0) break;
    if(scanned == 0) {
      fprintf(stderr, "%s: Character map syntax error\n", path);
      return 1;
    }

    /* Handle the first argument */
    if(strcmp(buf, "section") == 0) {    /* Section division */
      section++;
      continue;
    }
    else if(buf[0] == '#') {             /* Comment */
      fscanf(is, "%*[^\n]");
      continue;
    }
    else {
      char* bp = buf;
      int u;

      do {
        if(sscanf(bp, "%x", &u) == 1) {   /* Unicode */
          unicode[ulen++] = u;
        }
        else {
          fprintf(stderr, "%s: Syntax error at '%s'\n", path, buf);
          return 1;
        }

        bp = strchr(bp, ':');
        if(bp) bp++;
      } while(bp && ulen < MAX_UNICODE_SEQ-1);
      unicode[ulen] = L'\0';
    }

    /* Scan some more */
    scanned = fscanf(is, "%255s\t%255s", buf, flag);
    if(scanned < 0) break;

    /* Input count checking */
    switch(scanned) {
      case 0: case 1:
        fprintf(stderr, "%s: Character map syntax error\n", path);
        return 1;

      default:
        if(charmap_add(cm, section, buf, unicode, flag)) {
          size_t i = 0;

#ifndef __BEOS__
#if defined __GLIBC__ && __GLIBC__ == 2 && __GLIBC_MINOR__ >=2 || __GLIBC__ > 2 || __APPLE__
          fwprintf(stderr, L"Unable to add sequence '%ls', unicode ", buf);
          for(i = 0; i < wcslen(unicode); i++) fwprintf(stderr, L"%04X ", (int)unicode[i]);
          fwprintf(stderr, L"in section %d\n", section);
#endif
#endif

          error_code = 1;
        }
    }
  }

  /* Close */
  fclose(is);

  return error_code;
}
Example #25
0
int _getopt_internal_r_w ( int argc, wchar_t *const *argv, const wchar_t *optstring, const struct option_w *longopts, int *longind, int long_only, struct _getopt_data_w *d, int posixly_correct )
{
	int print_errors = d->opterr;

	if ( argc < 1 )
	{
		return -1;
	}

	d->optarg = NULL;

	if ( d->optind == 0 || !d->__initialized )
	{
		if ( d->optind == 0 )
		{
			d->optind = 1;
		}

		optstring = _getopt_initialize_w ( optstring, d, posixly_correct );
		d->__initialized = 1;
	}
	else if ( optstring[0] == L'-' || optstring[0] == L'+' )
	{
		optstring++;
	}

	if ( optstring[0] == L':' )
	{
		print_errors = 0;
	}

	if ( d->__nextchar == NULL || *d->__nextchar == L'\0' )
	{
		if ( d->__last_nonopt > d->optind )
		{
			d->__last_nonopt = d->optind;
		}

		if ( d->__first_nonopt > d->optind )
		{
			d->__first_nonopt = d->optind;
		}

		if ( d->__ordering == PERMUTE )
		{
			if ( d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind )
			{
				exchange_w ( ( wchar_t ** ) argv, d );
			}
			else if ( d->__last_nonopt != d->optind )
			{
				d->__first_nonopt = d->optind;
			}

			while ( d->optind < argc && ( argv[d->optind][0] != L'-' || argv[d->optind][1] == L'\0' ) )
			{
				d->optind++;
			}

			d->__last_nonopt = d->optind;
		}

		if ( d->optind != argc && !wcscmp ( argv[d->optind], L"--" ) )
		{
			d->optind++;

			if ( d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind )
			{
				exchange_w ( ( wchar_t ** ) argv, d );
			}
			else if ( d->__first_nonopt == d->__last_nonopt )
			{
				d->__first_nonopt = d->optind;
			}

			d->__last_nonopt = argc;
			d->optind = argc;
		}

		if ( d->optind == argc )
		{
			if ( d->__first_nonopt != d->__last_nonopt )
			{
				d->optind = d->__first_nonopt;
			}

			return -1;
		}

		if ( ( argv[d->optind][0] != L'-' || argv[d->optind][1] == L'\0' ) )
		{
			if ( d->__ordering == REQUIRE_ORDER )
			{
				return -1;
			}

			d->optarg = argv[d->optind++];
			return 1;
		}

		d->__nextchar = ( argv[d->optind] + 1 + ( longopts != NULL && argv[d->optind][1] == L'-' ) );
	}

	if ( longopts != NULL && ( argv[d->optind][1] == L'-' || ( long_only && ( argv[d->optind][2] || !wcschr ( optstring, argv[d->optind][1] ) ) ) ) )
	{
		wchar_t *nameend;
		unsigned int namelen;
		const struct option_w *p;
		const struct option_w *pfound = NULL;
		struct option_list
		{
			const struct option_w *p;
			struct option_list *next;
		} *ambig_list = NULL;
		int exact = 0;
		int indfound = -1;
		int option_index;

		for ( nameend = d->__nextchar; *nameend && *nameend != L'='; nameend++ );

		namelen = ( unsigned int ) ( nameend - d->__nextchar );

		for ( p = longopts, option_index = 0; p->name; p++, option_index++ )
			if ( !wcsncmp ( p->name, d->__nextchar, namelen ) )
			{
				if ( namelen == ( unsigned int ) wcslen ( p->name ) )
				{
					pfound = p;
					indfound = option_index;
					exact = 1;
					break;
				}
				else if ( pfound == NULL )
				{
					pfound = p;
					indfound = option_index;
				}
				else if ( long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val )
				{
					struct option_list *newp = ( struct option_list * ) alloca ( sizeof ( *newp ) );
					newp->p = p;
					newp->next = ambig_list;
					ambig_list = newp;
				}
			}

		if ( ambig_list != NULL && !exact )
		{
			if ( print_errors )
			{
				struct option_list first;
				first.p = pfound;
				first.next = ambig_list;
				ambig_list = &first;
				fwprintf ( stderr, L"%s: option '%s' is ambiguous; possibilities:", argv[0], argv[d->optind] );

				do
				{
					fwprintf ( stderr, L" '--%s'", ambig_list->p->name );
					ambig_list = ambig_list->next;
				}
				while ( ambig_list != NULL );

				fputwc ( L'\n', stderr );
			}

			d->__nextchar += wcslen ( d->__nextchar );
			d->optind++;
			d->optopt = 0;
			return L'?';
		}

		if ( pfound != NULL )
		{
			option_index = indfound;
			d->optind++;

			if ( *nameend )
			{
				if ( pfound->has_arg )
				{
					d->optarg = nameend + 1;
				}
				else
				{
					if ( print_errors )
					{
						if ( argv[d->optind - 1][1] == L'-' )
						{
							fwprintf ( stderr, L"%s: option '--%s' doesn't allow an argument\n", argv[0], pfound->name );
						}
						else
						{
							fwprintf ( stderr, L"%s: option '%c%s' doesn't allow an argument\n", argv[0], argv[d->optind - 1][0], pfound->name );
						}
					}

					d->__nextchar += wcslen ( d->__nextchar );
					d->optopt = pfound->val;
					return L'?';
				}
			}
			else if ( pfound->has_arg == 1 )
			{
				if ( d->optind < argc )
				{
					d->optarg = argv[d->optind++];
				}
				else
				{
					if ( print_errors )
					{
						fwprintf ( stderr, L"%s: option '--%s' requires an argument\n", argv[0], pfound->name );
					}

					d->__nextchar += wcslen ( d->__nextchar );
					d->optopt = pfound->val;
					return optstring[0] == L':' ? L':' : L'?';
				}
			}

			d->__nextchar += wcslen ( d->__nextchar );

			if ( longind != NULL )
			{
				*longind = option_index;
			}

			if ( pfound->flag )
			{
				* ( pfound->flag ) = pfound->val;
				return 0;
			}

			return pfound->val;
		}

		if ( !long_only || argv[d->optind][1] == L'-' || wcschr ( optstring, *d->__nextchar ) == NULL )
		{
			if ( print_errors )
			{
				if ( argv[d->optind][1] == L'-' )
				{
					fwprintf ( stderr, L"%s: unrecognized option '--%s'\n", argv[0], d->__nextchar );
				}
				else
				{
					fwprintf ( stderr, L"%s: unrecognized option '%c%s'\n", argv[0], argv[d->optind][0], d->__nextchar );
				}
			}

			d->__nextchar = ( wchar_t * ) L"";
			d->optind++;
			d->optopt = 0;
			return L'?';
		}
	}

	{
		wchar_t c = *d->__nextchar++;
		wchar_t *temp = ( wchar_t * ) wcschr ( optstring, c );

		if ( *d->__nextchar == L'\0' )
		{
			++d->optind;
		}

		if ( temp == NULL || c == L':' || c == L';' )
		{
			if ( print_errors )
			{
				fwprintf ( stderr, L"%s: invalid option -- '%c'\n", argv[0], c );
			}

			d->optopt = c;
			return L'?';
		}

		if ( temp[0] == L'W' && temp[1] == L';' )
		{
			wchar_t *nameend;
			const struct option_w *p;
			const struct option_w *pfound = NULL;
			int exact = 0;
			int ambig = 0;
			int indfound = 0;
			int option_index;

			if ( longopts == NULL )
			{
				goto no_longs;
			}

			if ( *d->__nextchar != L'\0' )
			{
				d->optarg = d->__nextchar;
				d->optind++;
			}
			else if ( d->optind == argc )
			{
				if ( print_errors )
				{
					fwprintf ( stderr, L"%s: option requires an argument -- '%c'\n", argv[0], c );
				}

				d->optopt = c;

				if ( optstring[0] == L':' )
				{
					c = L':';
				}
				else
				{
					c = L'?';
				}

				return c;
			}
			else
			{
				d->optarg = argv[d->optind++];
			}

			for ( d->__nextchar = nameend = d->optarg; *nameend && *nameend != L'='; nameend++ );

			for ( p = longopts, option_index = 0; p->name; p++, option_index++ )
				if ( !wcsncmp ( p->name, d->__nextchar, nameend - d->__nextchar ) )
				{
					if ( ( unsigned int ) ( nameend - d->__nextchar ) == wcslen ( p->name ) )
					{
						pfound = p;
						indfound = option_index;
						exact = 1;
						break;
					}
					else if ( pfound == NULL )
					{
						pfound = p;
						indfound = option_index;
					}
					else if ( long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val )
					{
						ambig = 1;
					}
				}

			if ( ambig && !exact )
			{
				if ( print_errors )
				{
					fwprintf ( stderr, L"%s: option '-W %s' is ambiguous\n", argv[0], d->optarg );
				}

				d->__nextchar += wcslen ( d->__nextchar );
				d->optind++;
				return L'?';
			}

			if ( pfound != NULL )
			{
				option_index = indfound;

				if ( *nameend )
				{
					if ( pfound->has_arg )
					{
						d->optarg = nameend + 1;
					}
					else
					{
						if ( print_errors )
						{
							fwprintf ( stderr, L"%s: option '-W %s' doesn't allow an argument\n", argv[0], pfound->name );
						}

						d->__nextchar += wcslen ( d->__nextchar );
						return L'?';
					}
				}
				else if ( pfound->has_arg == 1 )
				{
					if ( d->optind < argc )
					{
						d->optarg = argv[d->optind++];
					}
					else
					{
						if ( print_errors )
						{
							fwprintf ( stderr, L"%s: option '-W %s' requires an argument\n", argv[0], pfound->name );
						}

						d->__nextchar += wcslen ( d->__nextchar );
						return optstring[0] == L':' ? L':' : L'?';
					}
				}
				else
				{
					d->optarg = NULL;
				}

				d->__nextchar += wcslen ( d->__nextchar );

				if ( longind != NULL )
				{
					*longind = option_index;
				}

				if ( pfound->flag )
				{
					* ( pfound->flag ) = pfound->val;
					return 0;
				}

				return pfound->val;
			}

no_longs:
			d->__nextchar = NULL;
			return L'W';
		}

		if ( temp[1] == L':' )
		{
			if ( temp[2] == L':' )
			{
				if ( *d->__nextchar != L'\0' )
				{
					d->optarg = d->__nextchar;
					d->optind++;
				}
				else
				{
					d->optarg = NULL;
				}

				d->__nextchar = NULL;
			}
			else
			{
				if ( *d->__nextchar != L'\0' )
				{
					d->optarg = d->__nextchar;
					d->optind++;
				}
				else if ( d->optind == argc )
				{
					if ( print_errors )
					{
						fwprintf ( stderr, L"%s: option requires an argument -- '%c'\n", argv[0], c );
					}

					d->optopt = c;

					if ( optstring[0] == L':' )
					{
						c = L':';
					}
					else
					{
						c = L'?';
					}
				}
				else
				{
					d->optarg = argv[d->optind++];
				}

				d->__nextchar = NULL;
			}
		}

		return c;
	}
}
Example #26
0
/*****************************************************************************
 * vlc_exception_filter: handles unhandled exceptions, like segfaults
 *****************************************************************************/
LONG WINAPI vlc_exception_filter(struct _EXCEPTION_POINTERS *lpExceptionInfo)
{
    if(IsDebuggerPresent())
    {
        //If a debugger is present, pass the exception to the debugger
        //with EXCEPTION_CONTINUE_SEARCH
        return EXCEPTION_CONTINUE_SEARCH;
    }
    else
    {
        fprintf( stderr, "unhandled vlc exception\n" );

        FILE * fd = _wfopen ( crashdump_path, L"w, ccs=UTF-8" );

        if( !fd )
        {
            fprintf( stderr, "\nerror while opening file" );
            exit( 1 );
        }

        OSVERSIONINFO osvi;
        ZeroMemory( &osvi, sizeof(OSVERSIONINFO) );
        osvi.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
        GetVersionEx( &osvi );

        fwprintf( fd, L"[version]\nOS=%d.%d.%d.%d.%ls\nVLC=" VERSION_MESSAGE,
                osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber,
                osvi.dwPlatformId, osvi.szCSDVersion);

        const CONTEXT *const pContext = (const CONTEXT *)
            lpExceptionInfo->ContextRecord;
        const EXCEPTION_RECORD *const pException = (const EXCEPTION_RECORD *)
            lpExceptionInfo->ExceptionRecord;
        /* No nested exceptions for now */
        fwprintf( fd, L"\n\n[exceptions]\n%08x at %px", 
                pException->ExceptionCode, pException->ExceptionAddress );

        for( unsigned int i = 0; i < pException->NumberParameters; i++ )
            fwprintf( fd, L" | %p", pException->ExceptionInformation[i] );

#ifdef _WIN64
        fwprintf( fd, L"\n\n[context]\nRDI:%px\nRSI:%px\n" \
                    "RBX:%px\nRDX:%px\nRCX:%px\nRAX:%px\n" \
                    "RBP:%px\nRIP:%px\nRSP:%px\nR8:%px\n" \
                    "R9:%px\nR10:%px\nR11:%px\nR12:%px\n" \
                    "R13:%px\nR14:%px\nR15:%px\n",
                        pContext->Rdi,pContext->Rsi,pContext->Rbx,
                        pContext->Rdx,pContext->Rcx,pContext->Rax,
                        pContext->Rbp,pContext->Rip,pContext->Rsp,
                        pContext->R8,pContext->R9,pContext->R10,
                        pContext->R11,pContext->R12,pContext->R13,
                        pContext->R14,pContext->R15 );
#else
        fwprintf( fd, L"\n\n[context]\nEDI:%px\nESI:%px\n" \
                    "EBX:%px\nEDX:%px\nECX:%px\nEAX:%px\n" \
                    "EBP:%px\nEIP:%px\nESP:%px\n",
                        pContext->Edi,pContext->Esi,pContext->Ebx,
                        pContext->Edx,pContext->Ecx,pContext->Eax,
                        pContext->Ebp,pContext->Eip,pContext->Esp );
#endif

        fwprintf( fd, L"\n[stacktrace]\n#EIP|base|module\n" );

#ifdef _WIN64
        LPCVOID caller = (LPCVOID)pContext->Rip;
        LPVOID *pBase  = (LPVOID*)pContext->Rbp;
#else
        LPVOID *pBase  = (LPVOID*)pContext->Ebp;
        LPCVOID caller = (LPCVOID)pContext->Eip;
#endif
        for( unsigned frame = 0; frame <= 100; frame++ )
        {
            MEMORY_BASIC_INFORMATION mbi;
            wchar_t module[ 256 ];
            VirtualQuery( caller, &mbi, sizeof( mbi ) ) ;
            GetModuleFileName( mbi.AllocationBase, module, 256 );
            fwprintf( fd, L"%p|%ls\n", caller, module );

            if( IsBadReadPtr( pBase, 2 * sizeof( void* ) ) )
                break;

            /*The last BP points to NULL!*/
            caller = *(pBase + 1);
            if( !caller )
                break;
            pBase = *pBase;
            if( !pBase )
                break;
        }

        HANDLE hpid = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                        FALSE, GetCurrentProcessId());
        if (hpid) {
            HMODULE mods[1024];
            DWORD size;
            if (EnumProcessModules(hpid, mods, sizeof(mods), &size)) {
                fwprintf( fd, L"\n\n[modules]\n" );
                for (unsigned int i = 0; i < size / sizeof(HMODULE); i++) {
                    wchar_t module[ 256 ];
                    GetModuleFileName(mods[i], module, 256);
                    fwprintf( fd, L"%p|%ls\n", mods[i], module);
                }
            }
            CloseHandle(hpid);
        }

        fclose( fd );
        fflush( stderr );
        exit( 1 );
    }
}
Example #27
0
int job_reap( bool interactive )
{
    ASSERT_IS_MAIN_THREAD();
	job_t *jnext;	
	int found=0;
	
	static int locked = 0;
	
	locked++;	
	
	/*
	  job_read may fire an event handler, we do not want to call
	  ourselves recursively (to avoid infinite recursion).
	*/
	if( locked>1 )
		return 0;
    
    job_iterator_t jobs;
    jnext = jobs.next();
	while (jnext)
    {
        job_t *j = jnext;
        jnext = jobs.next();
		process_t *p;
		
		/*
		  If we are reaping only jobs who do not need status messages
		  sent to the console, do not consider reaping jobs that need
		  status messages
		*/
		if( (!job_get_flag( j, JOB_SKIP_NOTIFICATION ) ) && (!interactive) && (!job_get_flag( j, JOB_FOREGROUND )))
		{
			continue;
		}
	
		for( p=j->first_process; p; p=p->next )
		{
			int s;
			if( !p->completed )
				continue;
			
			if( !p->pid )
				continue;			
			
			s = p->status;
			
			proc_fire_event( L"PROCESS_EXIT", EVENT_EXIT, p->pid, ( WIFSIGNALED(s)?-1:WEXITSTATUS( s )) );			
			
			if( WIFSIGNALED(s) )
			{
				/* 
				   Ignore signal SIGPIPE.We issue it ourselves to the pipe
				   writer when the pipe reader dies.
				*/
				if( WTERMSIG(s) != SIGPIPE )
				{	
					int proc_is_job = ((p==j->first_process) && (p->next == 0));
					if( proc_is_job )
						job_set_flag( j, JOB_NOTIFIED, 1 );
					if( !job_get_flag( j, JOB_SKIP_NOTIFICATION ) )
					{
						if( proc_is_job )
							fwprintf( stdout,
									  _( L"%ls: Job %d, \'%ls\' terminated by signal %ls (%ls)" ),
									  program_name,
									  j->job_id, 
									  j->command_wcstr(),
									  sig2wcs(WTERMSIG(p->status)),
									  signal_get_desc( WTERMSIG(p->status) ) );
						else
							fwprintf( stdout,
									  _( L"%ls: Process %d, \'%ls\' from job %d, \'%ls\' terminated by signal %ls (%ls)" ),
									  program_name,
									  p->pid,
									  p->argv0(),
									  j->job_id,
									  j->command_wcstr(),
									  sig2wcs(WTERMSIG(p->status)),
									  signal_get_desc( WTERMSIG(p->status) ) );
						tputs(clr_eol,1,&writeb);
						fwprintf (stdout, L"\n" );
						found=1;						
					}
					
					/* 
					   Clear status so it is not reported more than once
					*/
					p->status = 0;
				}
			}						
		}
		
		/* 
		   If all processes have completed, tell the user the job has
		   completed and delete it from the active job list.  
		*/
		if( job_is_completed( j ) ) 
		{
			if( !job_get_flag( j, JOB_FOREGROUND) && !job_get_flag( j, JOB_NOTIFIED ) && !job_get_flag( j, JOB_SKIP_NOTIFICATION ) )
			{
				format_job_info( j, _( L"ended" ) );
				found=1;
			}
			proc_fire_event( L"JOB_EXIT", EVENT_EXIT, -j->pgid, 0 );			
			proc_fire_event( L"JOB_EXIT", EVENT_JOB_ID, j->job_id, 0 );			

			job_free(j);
		}		
		else if( job_is_stopped( j ) && !job_get_flag( j, JOB_NOTIFIED ) ) 
		{
			/* 
			   Notify the user about newly stopped jobs. 
			*/
			if( !job_get_flag( j, JOB_SKIP_NOTIFICATION ) )
			{
				format_job_info( j, _( L"stopped" ) );
				found=1;
			}			
			job_set_flag( j, JOB_NOTIFIED, 1 );
		}
	}

	if( found )
		fflush( stdout );

	locked = 0;
	
	return found;	
}
Example #28
0
/**
  Parse the argument list, return the index of the first non-switch
  arguments.
 */
static int fish_parse_opt( int argc, char **argv, const char **cmd_ptr )
{
	int my_optind;
	int force_interactive=0;
		
	while( 1 )
	{
		static struct option
			long_options[] =
			{
				{
					"command", required_argument, 0, 'c' 
				}
				,
				{
					"debug-level", required_argument, 0, 'd' 
				}
				,
				{
					"interactive", no_argument, 0, 'i' 
				}
				,
				{
					"login", no_argument, 0, 'l' 
				}
				,
				{
					"no-execute", no_argument, 0, 'n' 
				}
				,
				{
					"profile", required_argument, 0, 'p' 
				}
				,
				{
					"help", no_argument, 0, 'h' 
				}
				,
				{
					"version", no_argument, 0, 'v' 
				}
				,
				{ 
					0, 0, 0, 0 
				}
			}
		;
		
		int opt_index = 0;
		
		int opt = getopt_long( argc,
							   argv, 
							   GETOPT_STRING,
							   long_options, 
							   &opt_index );
		
		if( opt == -1 )
			break;
		
		switch( opt )
		{
			case 0:
			{
				break;
			}
			
			case 'c':		
			{
				*cmd_ptr = optarg;				
				is_interactive_session = 0;
				break;
			}
			
			case 'd':		
			{
				char *end;
				int tmp;

				errno = 0;
				tmp = strtol(optarg, &end, 10);
				
				if( tmp >= 0 && tmp <=10 && !*end && !errno )
				{
					debug_level=tmp;
				}
				else
				{
					debug( 0, _(L"Invalid value '%s' for debug level switch"), optarg );
					exit_without_destructors(1);
				}
				break;
			}
			
			case 'h':
			{
				*cmd_ptr = "__fish_print_help fish";
				break;
			}
			
			case 'i':
			{
				force_interactive = 1;
				break;				
			}
			
			case 'l':
			{
				is_login=1;
				break;				
			}
			
			case 'n':
			{
				no_exec=1;
				break;				
			}
			
			case 'p':
			{
				profile = optarg;
				break;				
			}
			
			case 'v':
			{
				fwprintf( stderr, 
						  _(L"%s, version %s\n"), 
						  PACKAGE_NAME,
						  PACKAGE_VERSION );
				exit_without_destructors( 0 );				
			}
			
			case '?':
			{
				exit_without_destructors( 1 );
			}
			
		}		
	}

	my_optind = optind;
	
	is_login |= (strcmp( argv[0], "-fish") == 0);
		
	/*
	  We are an interactive session if we have not been given an
	  explicit command to execute, _and_ stdin is a tty.
	 */
	is_interactive_session &= (*cmd_ptr == 0);
	is_interactive_session &= (my_optind == argc);
	is_interactive_session &= isatty(STDIN_FILENO);	

	/*
	  We are also an interactive session if we have are forced-
	 */
	is_interactive_session |= force_interactive;

	return my_optind;
}
Example #29
0
HRESULT Helpers::LoadScriptFromFile(LPCWSTR filename, LPCWSTR& contents, bool* isUtf8Out, LPCWSTR* contentsRawOut, UINT* lengthBytesOut, bool printFileOpenError)
{
    HRESULT hr = S_OK;
    LPCWSTR contentsRaw = nullptr;
    UINT lengthBytes = 0;
    bool isUtf8 = false;
    contents = nullptr;
    FILE * file;

    //
    // Open the file as a binary file to prevent CRT from handling encoding, line-break conversions,
    // etc.
    //
    if (_wfopen_s(&file, filename, L"rb") != 0)
    {
        if (printFileOpenError)
        {
            DWORD lastError = GetLastError();
            wchar_t wszBuff[512];
            fwprintf(stderr, L"Error in opening file '%s' ", filename);
            wszBuff[0] = 0;
            if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                nullptr,
                lastError,
                0,
                wszBuff,
                _countof(wszBuff),
                nullptr))
            {
                fwprintf(stderr, L": %s", wszBuff);
            }
            fwprintf(stderr, L"\n");
            IfFailGo(E_FAIL);
        }
        else
        {
            return E_FAIL;
        }
    }

    //
    // Determine the file length, in bytes.
    //
    fseek(file, 0, SEEK_END);
    lengthBytes = ftell(file);
    fseek(file, 0, SEEK_SET);
    contentsRaw = (LPCWSTR)HeapAlloc(GetProcessHeap(), 0, lengthBytes + sizeof(WCHAR));
    if (nullptr == contentsRaw)
    {
        fwprintf(stderr, L"out of memory");
        IfFailGo(E_OUTOFMEMORY);
    }

    //
    // Read the entire content as a binary block.
    //
    fread((void*)contentsRaw, sizeof(char), lengthBytes, file);
    fclose(file);
    *(WCHAR*)((byte*)contentsRaw + lengthBytes) = L'\0'; // Null terminate it. Could be LPCWSTR.

    //
    // Read encoding, handling any conversion to Unicode.
    //
    // Warning: The UNICODE buffer for parsing is supposed to be provided by the host.
    // This is not a complete read of the encoding. Some encodings like UTF7, UTF1, EBCDIC, SCSU, BOCU could be
    // wrongly classified as ANSI
    //
    byte * pRawBytes = (byte*)contentsRaw;
    if ((0xEF == *pRawBytes && 0xBB == *(pRawBytes + 1) && 0xBF == *(pRawBytes + 2)))
    {
        isUtf8 = true;
    }
    else if (0xFFFE == *contentsRaw || 0x0000 == *contentsRaw && 0xFEFF == *(contentsRaw + 1))
    {
        // unicode unsupported
        fwprintf(stderr, L"unsupported file encoding");
        IfFailGo(E_UNEXPECTED);
    }
    else if (0xFEFF == *contentsRaw)
    {
        // unicode LE
        contents = contentsRaw;
    }
    else
    {
        // Assume UTF8
        isUtf8 = true;
    }


    if (isUtf8)
    {
        utf8::DecodeOptions decodeOptions = utf8::doAllowInvalidWCHARs;

        UINT cUtf16Chars = utf8::ByteIndexIntoCharacterIndex(pRawBytes, lengthBytes, decodeOptions);
        contents = (LPCWSTR)HeapAlloc(GetProcessHeap(), 0, (cUtf16Chars + 1) * sizeof(WCHAR));
        if (nullptr == contents)
        {
            fwprintf(stderr, L"out of memory");
            IfFailGo(E_OUTOFMEMORY);
        }

        utf8::DecodeIntoAndNullTerminate((wchar_t*) contents, pRawBytes, cUtf16Chars, decodeOptions);
    }

Error:
    if (SUCCEEDED(hr) && isUtf8Out)
    {
        Assert(contentsRawOut);
        Assert(lengthBytesOut);
        *isUtf8Out = isUtf8;
        *contentsRawOut = contentsRaw;
        *lengthBytesOut = lengthBytes;
    }
    else if (contentsRaw && (contentsRaw != contents)) // Otherwise contentsRaw is lost. Free it if it is different to contents.
    {
        HeapFree(GetProcessHeap(), 0, (void*)contentsRaw);
    }

    if (contents && FAILED(hr))
    {
        HeapFree(GetProcessHeap(), 0, (void*)contents);
        contents = nullptr;
    }

    return hr;
}
Example #30
0
/**
   Print profiling information to the specified stream
*/
static void print_profile(const std::vector<profile_item_t*> &items,
                          FILE *out)
{
    for (size_t pos = 0; pos < items.size(); pos++)
    {
        const profile_item_t *me, *prev;
        size_t i;
        int my_time;

        me = items.at(pos);
        if (!me->skipped)
        {
            my_time=me->parse+me->exec;

            for (i=pos+1; i<items.size(); i++)
            {
                prev = items.at(i);
                if (prev->skipped)
                {
                    continue;
                }

                if (prev->level <= me->level)
                {
                    break;
                }

                if (prev->level > me->level+1)
                {
                    continue;
                }

                my_time -= prev->parse;
                my_time -= prev->exec;
            }

            if (me->cmd.size() > 0)
            {
                if (fwprintf(out, L"%d\t%d\t", my_time, me->parse+me->exec) < 0)
                {
                    wperror(L"fwprintf");
                    return;
                }

                for (i=0; i<me->level; i++)
                {
                    if (fwprintf(out, L"-") < 0)
                    {
                        wperror(L"fwprintf");
                        return;
                    }

                }
                if (fwprintf(out, L"> %ls\n", me->cmd.c_str()) < 0)
                {
                    wperror(L"fwprintf");
                    return;
                }

            }
        }
    }
}