Exemplo n.º 1
0
static void AddEnvironmentVariable(struct environment* env,const char* varName, const char* valueString)
{
    size_t len;
    size_t envSize = MAX_PATH - (env->p_head-env->env);
    StringCbCopyA(env->p_head, envSize, varName);
    StringCbCatA(env->p_head, envSize, "=");
    StringCbCatA(env->p_head, envSize, valueString);
    StringCbCatA(env->p_head, envSize, "\0");
    len = strnlen_s(env->p_head, envSize);
    env->p_head += (len + 1);
}
__inline void TraceA(const char *format, ...)
{
    if(g_bDebug)
    {
        if (format)
        {
            va_list arglist;
            char str[4096];

            va_start(arglist, format);
            StringCchVPrintfA(str, sizeof(str), format, arglist);
            StringCbCatA(str, sizeof(str), "\n");
            if (g_fLogFile)
            {
                FILE *fout = fopen(g_fLogFile, "a+t");
                if (fout)
                {
                    fprintf(fout, str);
                    fclose(fout);
                }
            }

            printf(str);

            if (g_bDebugString)
            {
                
                OutputDebugStringA(str);
            }

            va_end(arglist);
        }
    }
}
Exemplo n.º 3
0
static void dump(const char *name, const void *ptr, size_t siz)
{
    char buf[256], sz[16];

    StringCbCopyA(buf, sizeof(buf), name);
    StringCbCatA(buf, sizeof(buf), ": ");

    const BYTE *pb = reinterpret_cast<const BYTE *>(ptr);
    while (siz--)
    {
        StringCbPrintfA(sz, sizeof(sz), "%02X ", *pb++);
        StringCbCatA(buf, sizeof(buf), sz);
    }

    trace("%s\n", buf);
}
Exemplo n.º 4
0
int
mkfulldir_internal (char *path)
{
    char *token;
    struct _stat st;
    static char tokpath[_MAX_PATH];
    static char trail[_MAX_PATH];

    StringCbCopyA (tokpath, _MAX_PATH, path);
    trail[0] = '\0';

    token = strtok (tokpath, "\\/");

    if (tokpath[0] == '\\' && tokpath[1] == '\\')
    {   /* unc */
        trail[0] = tokpath[0];
        trail[1] = tokpath[1];
        trail[2] = '\0';
        if (token)
        {
            StringCbCatA (trail, _MAX_PATH, token);
            StringCbCatA (trail, _MAX_PATH, "\\");
            token = strtok (NULL, "\\/");
            if (token)
            {   /* get share name */
                StringCbCatA (trail, _MAX_PATH, token);
                StringCbCatA (trail, _MAX_PATH, "\\");
            }
            token = strtok (NULL, "\\/");
        }
    }

    if (tokpath[1] == ':')
    {   /* drive letter */
        StringCbCatA (trail, _MAX_PATH, tokpath);
        StringCbCatA (trail, _MAX_PATH, "\\");
        token = strtok (NULL, "\\/");
    }

    while (token != NULL)
    {
        int x;
        StringCbCatA (trail, _MAX_PATH, token);
        x = _mkdir (trail);
        StringCbCatA (trail, _MAX_PATH, "\\");
        token = strtok (NULL, "\\/");
    }

    return _stat (path, &st);
}
Exemplo n.º 5
0
SC_HANDLE register_service_exA(
    SC_HANDLE scm_handle,
    PCSTR test_name,
    PCSTR service_name, // LPCSTR lpServiceName,
    PCSTR extra_args OPTIONAL,
    DWORD dwDesiredAccess,
    DWORD dwServiceType,
    DWORD dwStartType,
    DWORD dwErrorControl,
    LPCSTR lpLoadOrderGroup OPTIONAL,
    LPDWORD lpdwTagId OPTIONAL,
    LPCSTR lpDependencies OPTIONAL,
    LPCSTR lpServiceStartName OPTIONAL,
    LPCSTR lpPassword OPTIONAL)
{
    SC_HANDLE service;
    CHAR service_cmd[MAX_PATH+150];

    /* Retrieve our full path */
    if (!GetModuleFileNameA(NULL, service_cmd, MAX_PATH))
    {
        skip("GetModuleFileNameW failed with error %lu!\n", GetLastError());
        return NULL;
    }

    /*
     * Build up our custom command line. The first parameter is the test name,
     * the second parameter is the flag used to decide whether we should start
     * as a service.
     */
    StringCbCatA(service_cmd, sizeof(service_cmd), " ");
    StringCbCatA(service_cmd, sizeof(service_cmd), test_name);
    StringCbCatA(service_cmd, sizeof(service_cmd), " ");
    StringCbCatA(service_cmd, sizeof(service_cmd), service_name);
    if (extra_args)
    {
        StringCbCatA(service_cmd, sizeof(service_cmd), " ");
        StringCbCatA(service_cmd, sizeof(service_cmd), extra_args);
    }

    trace("service_cmd \"%s\"\n", service_cmd);

    service = CreateServiceA(scm_handle, service_name, service_name,
                             dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl,
                             service_cmd, lpLoadOrderGroup, lpdwTagId, lpDependencies,
                             lpServiceStartName, lpPassword);
    if (!service && GetLastError() == ERROR_ACCESS_DENIED)
    {
        skip("Not enough access right to create service.\n");
        return NULL;
    }

    ok(service != NULL, "CreateService failed: %lu\n", GetLastError());
    return service;
}
Exemplo n.º 6
0
BOOL FormatNtfs (int driveNo, int clusterSize)
{
	char dllPath[MAX_PATH] = {0};
	WCHAR dir[8] = { (WCHAR) driveNo + 'A', 0 };
	PFORMATEX FormatEx;
	HMODULE hModule;
	int i;
	
	if (GetSystemDirectory (dllPath, MAX_PATH))
	{
		StringCbCatA(dllPath, sizeof(dllPath), "\\fmifs.dll");
	}
	else
		StringCbCopyA(dllPath, sizeof(dllPath), "C:\\Windows\\System32\\fmifs.dll");
	
	hModule = LoadLibrary (dllPath);

	if (hModule == NULL)
		return FALSE;

	if (!(FormatEx = (PFORMATEX) GetProcAddress (GetModuleHandle ("fmifs.dll"), "FormatEx")))
	{
		FreeLibrary (hModule);
		return FALSE;
	}

	StringCbCatW (dir, sizeof(dir), L":\\");

	FormatExError = TRUE;
	
	// Windows sometimes fails to format a volume (hosted on a removable medium) as NTFS.
	// It often helps to retry several times.
	for (i = 0; i < 50 && FormatExError; i++)
	{
		FormatExError = FALSE;
		FormatEx (dir, FMIFS_HARDDISK, L"NTFS", L"", TRUE, clusterSize * FormatSectorSize, FormatExCallback);
	}

	// The device may be referenced for some time after FormatEx() returns
	Sleep (4000);

	FreeLibrary (hModule);
	return FormatExError? FALSE : TRUE;
}
Exemplo n.º 7
0
/* create a new log, taking a name and a size in entries (not words) */
osi_log_t *osi_LogCreate(char *namep, size_t size)
{
    osi_log_t *logp;
    osi_fdType_t *typep;
    char tbuffer[256];
    LARGE_INTEGER bigFreq;
    LARGE_INTEGER bigTemp;
    LARGE_INTEGER bigJunk;

    if (osi_Once(&osi_logOnce)) {
        QueryPerformanceFrequency(&bigFreq);
        if (bigFreq.LowPart == 0 && bigFreq.HighPart == 0)
            osi_logFreq = 0;
        else {
            /* turn frequency into ticks per 10 micros */
            bigTemp.LowPart = 100000;
            bigTemp.HighPart = 0;
            osi_logTixToMicros = 10;
            bigFreq = LargeIntegerDivide(bigFreq, bigTemp, &bigJunk);

            /* check if resolution is too fine or to gross for this to work */
            if (bigFreq.HighPart > 0 || bigFreq.LowPart < 8)
                osi_logFreq = 0;	/* too big to represent as long */
            else
                osi_logFreq = bigFreq.LowPart;
        }

        /* done with init */
        osi_EndOnce(&osi_logOnce);
    }

    logp = malloc(sizeof(osi_log_t));
    memset(logp, 0, sizeof(osi_log_t));
    {
        size_t namelen = strlen(namep) + 1;

        logp->namep = malloc(namelen * sizeof(char));
        StringCchCopyA(logp->namep, namelen, namep);
    }
    osi_QAdd((osi_queue_t **) &osi_allLogsp, &logp->q);

    /* compute size we'll use */
    if (size == 0) size = osi_logSize;

    /* handle init for this size */
    logp->alloc = size;
    logp->datap = malloc(size * sizeof(osi_logEntry_t));

    /* init strings array */
    logp->maxstringindex = size/3;
    logp->stringindex = 0;
    logp->stringsp = malloc(logp->maxstringindex * OSI_LOG_STRINGSIZE);

    /* and sync */
    thrd_InitCrit(&logp->cs);

    StringCbCopyA(tbuffer, sizeof(tbuffer), "log:");
    StringCbCatA(tbuffer, sizeof(tbuffer), namep);
    typep = osi_RegisterFDType(tbuffer, &osi_logFDOps, logp);
    if (typep) {
        /* add formatting info */
        osi_AddFDFormatInfo(typep, OSI_DBRPC_REGIONINT, 0,
                            "Thread ID", OSI_DBRPC_HEX);
        osi_AddFDFormatInfo(typep, OSI_DBRPC_REGIONSTRING, 1,
                            "Time (mics)", 0);
    }

    return logp;
}
Exemplo n.º 8
0
// печатает в буфер key_name_buffer текстовое описание нажатой комбинации кнопок
// Кодировка ANSI (для экономии места, всё равно названия клавиш английские)
VOID HwHotKeys_PrintFullKeyname(DWORD scancode)
{
	key_name_buffer[0] = 0;
	if (!scancode) // если нулевой сканкод - то пустую строку делаем.
	{
		return;
	}

	if (scancode & key_flag_sl) // L_Shift
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_SL);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}
	if (scancode & key_flag_sr) // R_Shift
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_SR);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}
	if (scancode & key_flag_ss) // Shift
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_SS);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}

	if (scancode & key_flag_cl) // L_Ctrl
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_CL);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}
	if (scancode & key_flag_cr) // R_Ctrl
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_CR);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}
	if (scancode & key_flag_cc) // Ctrl
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_CC);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}

	if (scancode & key_flag_al) // L_Alt
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_AL);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}
	if (scancode & key_flag_ar) // R_Alt
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_AR);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}
	if (scancode & key_flag_aa) // Alt
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_AA);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}

	if (scancode & key_flag_wl) // L_Win
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_WL);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}
	if (scancode & key_flag_wr) // R_Win
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_WR);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}
	if (scancode & key_flag_ww) // Win
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), t_WW);
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), " + ");
	}

	if ((scancode & 0x1FF) < sizeof(key_tab)) // защита от ошибочных данных - чтобы не выйти из таблицы имён.
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), key_tab[(scancode & 0x1FF)]);
	}
	else
	{
		StringCbCatA(key_name_buffer, sizeof(key_name_buffer), "out of range");
	}

	INT_PTR tmp1 = mir_strlen(key_name_buffer); // допечатываем в конеце строки сканкод - для удобства работы с пока ещё не известными (безимянными) кнопками
	StringCbPrintfA(key_name_buffer + tmp1, sizeof(key_name_buffer) - tmp1, " (%03X)", (scancode & 0x1FF));

	return;
}
Exemplo n.º 9
0
int getAFSServer(const char *service, const char *protocol, const char *cellName,
                 unsigned short afsdbPort,  /* network byte order */
                 int *cellHostAddrs, char cellHostNames[][MAXHOSTCHARS],
                 unsigned short ports[],    /* network byte order */
                 unsigned short ipRanks[],
                 int *numServers, int *ttl)
{
#ifndef DNSAPI_ENV
    SOCKET commSock;
    SOCKADDR_IN sockAddr;
    PDNS_HDR  pDNShdr;
    char buffer[BUFSIZE];
    char query[1024];
    int rc;

#ifdef DEBUG
    fprintf(stderr, "getAFSServer: cell %s, cm_dnsEnabled=%d\n", cellName, cm_dnsEnabled);
#endif

    *numServers = 0;
    *ttl = 0;

#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
    if (cm_dnsEnabled == -1) { /* not yet initialized, eg when called by klog */
        cm_InitDNS(1);         /* assume enabled */
    }
#endif
    if (cm_dnsEnabled == 0) {  /* possibly we failed in cm_InitDNS above */
        fprintf(stderr, "DNS initialization failed, disabled\n");
        return -1;
    }
  
    if (service == NULL || protocol == NULL || cellName == NULL) {
        fprintf(stderr, "invalid input\n");
        return -1;
    }

    sockAddr = setSockAddr(dns_addr, DNS_PORT);
  
    commSock = socket( AF_INET, SOCK_DGRAM, 0 );
    if ( commSock < 0 )
    {
        /*afsi_log("socket() failed\n");*/
        fprintf(stderr, "getAFSServer: socket() failed, errno=%d\n", errno);
        return (-1);
    } 

    StringCbCopyA(query, sizeof(query), cellName);
    if (query[strlen(query)-1] != '.') {
        StringCbCatA(query, sizeof(query), ".");
    }

    rc = send_DNS_AFSDB_Query(query,commSock,sockAddr, buffer);
    if (rc < 0) {
        closesocket(commSock);
        fprintf(stderr,"getAFSServer: send_DNS_AFSDB_Query failed\n");
        return -1;
    }
    
    pDNShdr = get_DNS_Response(commSock,sockAddr, buffer);
  
    /*printReplyBuffer_AFSDB(pDNShdr);*/
    if (pDNShdr)
        processReplyBuffer_AFSDB(commSock, pDNShdr, cellHostAddrs, cellHostNames, ports, ipRanks, numServers, ttl);

    closesocket(commSock);
    if (*numServers == 0)
        return(-1);
    else
        return 0;
#else /* DNSAPI_ENV */
    PDNS_RECORD pDnsCell, pDnsIter, pDnsVol, pDnsVolIter, pDnsCIter;
    int i;
    char query[1024];

    *numServers = 0;
    *ttl = 0;

    if (service == NULL || protocol == NULL || cellName == NULL)
        return -1;

#ifdef AFS_FREELANCE_CLIENT
    if ( cm_stricmp_utf8N(cellName, "Freelance.Local.Root") == 0 )
        return -1;
#endif /* AFS_FREELANCE_CLIENT */

    /* query the SRV _afs3-vlserver._udp records of cell */
    StringCbPrintf(query, sizeof(query), "_%s._%s.%s", service, protocol, cellName);
    if (query[strlen(query)-1] != '.') {
        StringCbCatA(query, sizeof(query), ".");
    }

    if (DnsQuery_A(query, DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &pDnsCell, NULL) == ERROR_SUCCESS) {
        /* go through the returned records */
        for (pDnsIter = pDnsCell;pDnsIter; pDnsIter = pDnsIter->pNext) {
            /* if we find an SRV record, we found the service */
            if (pDnsIter->wType == DNS_TYPE_SRV) {
                StringCbCopyA(cellHostNames[*numServers], sizeof(cellHostNames[*numServers]),
                              pDnsIter->Data.SRV.pNameTarget);
                ipRanks[*numServers] = pDnsIter->Data.SRV.wPriority;
                ports[*numServers] = htons(pDnsIter->Data.SRV.wPort);
                (*numServers)++;

                if (!*ttl) 
                    *ttl = pDnsIter->dwTtl;
                if (*numServers == AFSMAXCELLHOSTS) 
                    break;
            }
        }

        for (i=0;i<*numServers;i++) 
            cellHostAddrs[i] = 0;

        /* now check if there are any A records in the results */
        for (pDnsIter = pDnsCell; pDnsIter; pDnsIter = pDnsIter->pNext) {
            if(pDnsIter->wType == DNS_TYPE_A)
                /* check if its for one of the service */
                for (i=0;i<*numServers;i++)
                    if(cm_stricmp_utf8(pDnsIter->pName, cellHostNames[i]) == 0)
                        cellHostAddrs[i] = pDnsIter->Data.A.IpAddress;
        }

        for (i=0;i<*numServers;i++) {
            /* if we don't have an IP yet, then we should try resolving the afs3-vlserver hostname
            in a separate query. */
            if (!cellHostAddrs[i]) {
                if (DnsQuery_A(cellHostNames[i], DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, &pDnsVol, NULL) == ERROR_SUCCESS) {
                    for (pDnsVolIter = pDnsVol; pDnsVolIter; pDnsVolIter=pDnsVolIter->pNext) {
                        /* if we get an A record, keep it */
                        if (pDnsVolIter->wType == DNS_TYPE_A && cm_stricmp_utf8(cellHostNames[i], pDnsVolIter->pName)==0) {
                            cellHostAddrs[i] = pDnsVolIter->Data.A.IpAddress;
                            break;
                        }
                        /* if we get a CNAME, look for a corresponding A record */
                        if (pDnsVolIter->wType == DNS_TYPE_CNAME && cm_stricmp_utf8(cellHostNames[i], pDnsVolIter->pName)==0) {
                            for (pDnsCIter=pDnsVolIter; pDnsCIter; pDnsCIter=pDnsCIter->pNext) {
                                if (pDnsCIter->wType == DNS_TYPE_A && cm_stricmp_utf8(pDnsVolIter->Data.CNAME.pNameHost, pDnsCIter->pName)==0) {
                                    cellHostAddrs[i] = pDnsCIter->Data.A.IpAddress;
                                    break;
                                }
                            }
                            if (cellHostAddrs[i]) 
                                break;
                            /* TODO: if the additional section is missing, then do another lookup for the CNAME */
                        }
                    }
                    /* we are done with the service lookup */
                    DnsRecordListFree(pDnsVol, DnsFreeRecordListDeep);
                }
            }
        }
        DnsRecordListFree(pDnsCell, DnsFreeRecordListDeep);
    }
    else {
        /* query the AFSDB records of cell */
        StringCbCopyA(query, sizeof(query), cellName);
        if (query[strlen(query)-1] != '.') {
            StringCbCatA(query, sizeof(query), ".");
        }

        if (DnsQuery_A(query, DNS_TYPE_AFSDB, DNS_QUERY_STANDARD, NULL, &pDnsCell, NULL) == ERROR_SUCCESS) {
            /* go through the returned records */
            for (pDnsIter = pDnsCell;pDnsIter; pDnsIter = pDnsIter->pNext) {
                /* if we find an AFSDB record with Preference set to 1, we found a service instance */
                if (pDnsIter->wType == DNS_TYPE_AFSDB && pDnsIter->Data.Afsdb.wPreference == 1) {
                    StringCbCopyA(cellHostNames[*numServers], sizeof(cellHostNames[*numServers]),
                                   pDnsIter->Data.Afsdb.pNameExchange);
                    ipRanks[*numServers] = 0;
                    ports[*numServers] = afsdbPort;
                    (*numServers)++;

                    if (!*ttl) 
                        *ttl = pDnsIter->dwTtl;
                    if (*numServers == AFSMAXCELLHOSTS) 
                        break;
                }
            }

            for (i=0;i<*numServers;i++) 
                cellHostAddrs[i] = 0;

            /* now check if there are any A records in the results */
            for (pDnsIter = pDnsCell; pDnsIter; pDnsIter = pDnsIter->pNext) {
                if(pDnsIter->wType == DNS_TYPE_A)
                    /* check if its for one of the service */
                    for (i=0;i<*numServers;i++)
                        if(cm_stricmp_utf8(pDnsIter->pName, cellHostNames[i]) == 0)
                            cellHostAddrs[i] = pDnsIter->Data.A.IpAddress;
            }

            for (i=0;i<*numServers;i++) {
                /* if we don't have an IP yet, then we should try resolving the service hostname
                in a separate query. */
                if (!cellHostAddrs[i]) {
                    if (DnsQuery_A(cellHostNames[i], DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, &pDnsVol, NULL) == ERROR_SUCCESS) {
                        for (pDnsVolIter = pDnsVol; pDnsVolIter; pDnsVolIter=pDnsVolIter->pNext) {
                            /* if we get an A record, keep it */
                            if (pDnsVolIter->wType == DNS_TYPE_A && cm_stricmp_utf8(cellHostNames[i], pDnsVolIter->pName)==0) {
                                cellHostAddrs[i] = pDnsVolIter->Data.A.IpAddress;
                                break;
                            }
                            /* if we get a CNAME, look for a corresponding A record */
                            if (pDnsVolIter->wType == DNS_TYPE_CNAME && cm_stricmp_utf8(cellHostNames[i], pDnsVolIter->pName)==0) {
                                for (pDnsCIter=pDnsVolIter; pDnsCIter; pDnsCIter=pDnsCIter->pNext) {
                                    if (pDnsCIter->wType == DNS_TYPE_A && cm_stricmp_utf8(pDnsVolIter->Data.CNAME.pNameHost, pDnsCIter->pName)==0) {
                                        cellHostAddrs[i] = pDnsCIter->Data.A.IpAddress;
                                        break;
                                    }
                                }
                                if (cellHostAddrs[i]) 
                                    break;
                                /* TODO: if the additional section is missing, then do another lookup for the CNAME */
                            }
                        }
                        /* we are done with the service lookup */
                        DnsRecordListFree(pDnsVol, DnsFreeRecordListDeep);
                    }
                }
            }
            DnsRecordListFree(pDnsCell, DnsFreeRecordListDeep);
        }
    }

    if ( *numServers > 0 )
        return 0;
    else        
        return -1;
#endif /* DNSAPI_ENV */
}
Exemplo n.º 10
0
CToshHandler::CToshHandler(TToshParams& aParams)
{
	iParams = aParams;

	memset(&iDevInfo,0,sizeof(iDevInfo));

	memset(&iPrevDevInfoList,0,sizeof(iPrevDevInfoList));
	

	iOpenedObexApi = false;
	iCID = 0;
	iSDPSSRESULT = NULL;

	iRFCOMMCID = 0;
//	iHFile = 0;


		GetModuleFileName(AfxGetInstanceHandle(), iTmpObexFilePath, MAX_PATH);
	
	 /* Search backward. */
	CHAR ch('\\');
	CHAR* pdest = strrchr( iTmpObexFilePath, ch );

	if( pdest != NULL )
	{
		if( MAX_PATH > pdest - iTmpObexFilePath)
			*(pdest+1) = NULL;
	}	
	
	
	StringCbCatA(iTmpObexFilePath,MAX_PATH,KWmxpJarPathRelativeToReleaseExe);

	//////////prepare tosh bt sdp struct iWmxpToshSDPPattern in ram
	iWmxpToshSDPPattern = NULL;
	iWmxpToshSDPPatternSize = 0;

	BTUUIDINFO aBTUUIDINFO;
	aBTUUIDINFO.wUUIDType = 128;
	
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[0] = 0x2b;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[1] = 0xc2;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[2] = 0xb9;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[3] = 0x2e;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[4] = 0x39;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[5] = 0x92;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[6] = 0x11;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[7] = 0xdc;

	((unsigned char*)&(aBTUUIDINFO.BtUUID))[8] = 0x83;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[9] = 0x14;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[10] = 0x08;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[11] = 0x00;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[12] = 0x20;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[13] = 0x0c;
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[14] = 0x9a;			
	((unsigned char*)&(aBTUUIDINFO.BtUUID))[15] = 0x66;	

	

	
	
	//BTUUIDLIST aBTUUIDLIST; cannot static because the declaration was BTUUIDINFO BtUUIDInfo[]; so we need to alloc for the first one too
	BTUUIDLIST* aPBTUUIDLIST = (PBTUUIDLIST) malloc(sizeof(BTUUIDLIST) + sizeof(BTUUIDINFO));
	aPBTUUIDLIST->dwUUIDInfoNum=1;
	memcpy(&(aPBTUUIDLIST->BtUUIDInfo[0]) ,&aBTUUIDINFO, sizeof(BTUUIDINFO));

	iWmxpToshSDPPattern = NULL;
	iWmxpToshAttrIdList = NULL;
	iMemSDP_SSA_Result = NULL;
	
	long status;
	if(BtMakeServiceSearchPattern2(aPBTUUIDLIST, &iWmxpToshSDPPatternSize, &iWmxpToshSDPPattern, &status))
	{
		;//ok 	

		//ShowHex(iWmxpToshSDPPattern,iWmxpToshSDPPatternSize);
			
		
		BTUNIVATTRIBUTE mask = 0;
		mask |= TOSBTAPI_ATR_PROTOCOLDESCRIPTORLIST;
		mask |= TOSBTAPI_ATR_SERVICERECORDHANDLE;
		if(BtMakeAttributeIDList2(mask, &iWmxpToshAttrIdListSize, &iWmxpToshAttrIdList, &iStatus))
			mydebug::log("th164");
		else
		{
			AfxMessageBox("BtMakeAttributeIDList2 failed");
			delete iWmxpToshAttrIdList;
			iWmxpToshAttrIdList = NULL;		
		}
			
	}
	else
	{
		AfxMessageBox("BtMakeServiceSearchPattern2 failed");
		delete iWmxpToshSDPPattern;
		iWmxpToshSDPPattern = NULL;
	}

	if(iWmxpToshSDPPattern ==NULL || aPBTUUIDLIST==NULL)
		AfxMessageBox("SearchPattern or UUID list generation failed");

	mydebug::log("th165");

	free(aPBTUUIDLIST);

	mydebug::log("th166");
	////////////////////////////

	
}
Exemplo n.º 11
0
// Creates a volume header in memory
int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *header, int ea, int mode, Password *password,
		   int pkcs5_prf, char *masterKeydata, PCRYPTO_INFO *retInfo,
		   unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize,
		   unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode)
{
	unsigned char *p = (unsigned char *) header;
	static KEY_INFO keyInfo;

	int nUserKeyLen = password->Length;
	PCRYPTO_INFO cryptoInfo = crypto_open ();
	static char dk[MASTER_KEYDATA_SIZE];
	int x;
	int retVal = 0;
	int primaryKeyOffset;

	if (cryptoInfo == NULL)
		return ERR_OUTOFMEMORY;

	memset (header, 0, TC_VOLUME_HEADER_EFFECTIVE_SIZE);

	VirtualLock (&keyInfo, sizeof (keyInfo));
	VirtualLock (&dk, sizeof (dk));

	/* Encryption setup */

	if (masterKeydata == NULL)
	{
		// We have no master key data (creating a new volume) so we'll use the TrueCrypt RNG to generate them

		int bytesNeeded;

		switch (mode)
		{

		default:
			bytesNeeded = EAGetKeySize (ea) * 2;	// Size of primary + secondary key(s)
		}

		if (!RandgetBytes (hwndDlg, keyInfo.master_keydata, bytesNeeded, TRUE))
			return ERR_CIPHER_INIT_WEAK_KEY;
	}
	else
	{
		// We already have existing master key data (the header is being re-encrypted)
		memcpy (keyInfo.master_keydata, masterKeydata, MASTER_KEYDATA_SIZE);
	}

	// User key 
	memcpy (keyInfo.userKey, password->Text, nUserKeyLen);
	keyInfo.keyLength = nUserKeyLen;
	keyInfo.noIterations = get_pkcs5_iteration_count (pkcs5_prf, FALSE, bBoot);

	// User selected encryption algorithm
	cryptoInfo->ea = ea;

	// User selected PRF
	cryptoInfo->pkcs5 = pkcs5_prf;
	cryptoInfo->bTrueCryptMode = FALSE;

	// Mode of operation
	cryptoInfo->mode = mode;

	// Salt for header key derivation
	if (!RandgetBytes (hwndDlg, keyInfo.salt, PKCS5_SALT_SIZE, !bWipeMode))
		return ERR_CIPHER_INIT_WEAK_KEY; 

	// PBKDF2 (PKCS5) is used to derive primary header key(s) and secondary header key(s) (XTS) from the password/keyfiles
	switch (pkcs5_prf)
	{
	case SHA512:
		derive_key_sha512 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt,
			PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize());
		break;

	case SHA256:
		derive_key_sha256 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt,
			PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize());
		break;

	case RIPEMD160:
		derive_key_ripemd160 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt,
			PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize());
		break;

	case WHIRLPOOL:
		derive_key_whirlpool (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt,
			PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize());
		break;

	default:		
		// Unknown/wrong ID
		TC_THROW_FATAL_EXCEPTION;
	} 

	/* Header setup */

	// Salt
	mputBytes (p, keyInfo.salt, PKCS5_SALT_SIZE);	

	// Magic
	mputLong (p, 0x56455241);

	// Header version
	mputWord (p, VOLUME_HEADER_VERSION);
	cryptoInfo->HeaderVersion = VOLUME_HEADER_VERSION;

	// Required program version to handle this volume
	mputWord (p, requiredProgramVersion != 0 ? requiredProgramVersion : TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION);

	// CRC of the master key data
	x = GetCrc32(keyInfo.master_keydata, MASTER_KEYDATA_SIZE);
	mputLong (p, x);

	// Reserved fields
	p += 2 * 8;

	// Size of hidden volume (if any)
	cryptoInfo->hiddenVolumeSize = hiddenVolumeSize;
	mputInt64 (p, cryptoInfo->hiddenVolumeSize);

	cryptoInfo->hiddenVolume = cryptoInfo->hiddenVolumeSize != 0;

	// Volume size
	cryptoInfo->VolumeSize.Value = volumeSize;
	mputInt64 (p, volumeSize);

	// Encrypted area start
	cryptoInfo->EncryptedAreaStart.Value = encryptedAreaStart;
	mputInt64 (p, encryptedAreaStart);

	// Encrypted area size
	cryptoInfo->EncryptedAreaLength.Value = encryptedAreaLength;
	mputInt64 (p, encryptedAreaLength);

	// Flags
	cryptoInfo->HeaderFlags = headerFlags;
	mputLong (p, headerFlags);

	// Sector size
	if (sectorSize < TC_MIN_VOLUME_SECTOR_SIZE
		|| sectorSize > TC_MAX_VOLUME_SECTOR_SIZE
		|| sectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
	{
		TC_THROW_FATAL_EXCEPTION;
	}

	cryptoInfo->SectorSize = sectorSize;
	mputLong (p, sectorSize);

	// CRC of the header fields
	x = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC);
	p = header + TC_HEADER_OFFSET_HEADER_CRC;
	mputLong (p, x);

	// The master key data
	memcpy (header + HEADER_MASTER_KEYDATA_OFFSET, keyInfo.master_keydata, MASTER_KEYDATA_SIZE);


	/* Header encryption */

	switch (mode)
	{

	default:
		// The secondary key (if cascade, multiple concatenated)
		memcpy (cryptoInfo->k2, dk + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea));
		primaryKeyOffset = 0;
	}

	retVal = EAInit (cryptoInfo->ea, dk + primaryKeyOffset, cryptoInfo->ks);
	if (retVal != ERR_SUCCESS)
		return retVal;

	// Mode of operation
	if (!EAInitMode (cryptoInfo))
		return ERR_OUTOFMEMORY;


	// Encrypt the entire header (except the salt)
	EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET,
		HEADER_ENCRYPTED_DATA_SIZE,
		cryptoInfo);


	/* cryptoInfo setup for further use (disk format) */

	// Init with the master key(s) 
	retVal = EAInit (cryptoInfo->ea, keyInfo.master_keydata + primaryKeyOffset, cryptoInfo->ks);
	if (retVal != ERR_SUCCESS)
		return retVal;

	memcpy (cryptoInfo->master_keydata, keyInfo.master_keydata, MASTER_KEYDATA_SIZE);

	switch (cryptoInfo->mode)
	{

	default:
		// The secondary master key (if cascade, multiple concatenated)
		memcpy (cryptoInfo->k2, keyInfo.master_keydata + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea));
	}

	// Mode of operation
	if (!EAInitMode (cryptoInfo))
		return ERR_OUTOFMEMORY;


#ifdef VOLFORMAT
	if (showKeys && !bInPlaceEncNonSys)
	{
		BOOL dots3 = FALSE;
		int i, j;

		j = EAGetKeySize (ea);

		if (j > NBR_KEY_BYTES_TO_DISPLAY)
		{
			dots3 = TRUE;
			j = NBR_KEY_BYTES_TO_DISPLAY;
		}

		MasterKeyGUIView[0] = 0;
		for (i = 0; i < j; i++)
		{
			char tmp2[8] = {0};
			StringCbPrintfA (tmp2, sizeof(tmp2), "%02X", (int) (unsigned char) keyInfo.master_keydata[i + primaryKeyOffset]);
			StringCbCatA (MasterKeyGUIView, sizeof(MasterKeyGUIView), tmp2);
		}

		HeaderKeyGUIView[0] = 0;
		for (i = 0; i < NBR_KEY_BYTES_TO_DISPLAY; i++)
		{
			char tmp2[8];
			StringCbPrintfA (tmp2, sizeof(tmp2), "%02X", (int) (unsigned char) dk[primaryKeyOffset + i]);
			StringCbCatA (HeaderKeyGUIView, sizeof(HeaderKeyGUIView), tmp2);
		}

		if (dots3)
		{
			DisplayPortionsOfKeys (hHeaderKey, hMasterKey, HeaderKeyGUIView, MasterKeyGUIView, !showKeys);
		}
		else
		{
			SendMessage (hMasterKey, WM_SETTEXT, 0, (LPARAM) MasterKeyGUIView);
			SendMessage (hHeaderKey, WM_SETTEXT, 0, (LPARAM) HeaderKeyGUIView);
		}
	}
#endif	// #ifdef VOLFORMAT

	burn (dk, sizeof(dk));
	burn (&keyInfo, sizeof (keyInfo));

	*retInfo = cryptoInfo;
	return 0;
}
Exemplo n.º 12
0
khm_int32 KHMAPI
khm_krb5_find_ccache_for_identity(khm_handle ident, krb5_context *pctx,
                                  void * buffer, khm_size * pcbbuf)
{
    krb5_context        ctx = 0;
    krb5_ccache         cache = 0;
    krb5_error_code     code;
    apiCB *             cc_ctx = 0;
    struct _infoNC **   pNCi = NULL;
    int                 i;
    khm_int32           t;
    wchar_t *           ms = NULL;
    khm_size            cb;
    krb5_timestamp      expiration = 0;
    krb5_timestamp      best_match_expiration = 0;
    char                best_match_ccname[256] = "";
    khm_handle          csp_params = NULL;
    khm_handle          csp_plugins = NULL;

    if (!buffer || !pcbbuf)
    return KHM_ERROR_GENERAL;

    ctx = *pctx;

    if (!pcc_initialize ||
        !pcc_get_NC_info ||
        !pcc_free_NC_info ||
        !pcc_shutdown)
        goto _skip_cc_iter;

    code = pcc_initialize(&cc_ctx, CC_API_VER_2, NULL, NULL);
    if (code)
        goto _exit;

    code = pcc_get_NC_info(cc_ctx, &pNCi);

    if (code) 
        goto _exit;

    for(i=0; pNCi[i]; i++) {
        if (pNCi[i]->vers != CC_CRED_V5)
            continue;

        code = (*pkrb5_cc_resolve)(ctx, pNCi[i]->name, &cache);
        if (code)
            continue;

        /* need a function to check the cache for the identity
         * and determine if it has valid tickets.  If it has 
         * the right identity and valid tickets, store the 
         * expiration time and the cache name.  If it has the
         * right identity but no valid tickets, store the ccache
         * name and an expiration time of zero.  if it does not
         * have the right identity don't save the name.
         * 
         * Keep searching to find the best cache available.
         */

        if (KHM_SUCCEEDED(khm_get_identity_expiration_time(ctx, cache, 
                                                           ident, 
                                                           &expiration))) {
            if ( expiration > best_match_expiration ) {
                best_match_expiration = expiration;
                StringCbCopyA(best_match_ccname, 
                              sizeof(best_match_ccname),
                              "API:");
                StringCbCatA(best_match_ccname,
                             sizeof(best_match_ccname),
                             pNCi[i]->name);
                expiration = 0;
            }
        }

        if(ctx != NULL && cache != NULL)
            (*pkrb5_cc_close)(ctx, cache);
        cache = 0;
    }

 _skip_cc_iter:

    if (KHM_SUCCEEDED(kmm_get_plugins_config(0, &csp_plugins))) {
        khc_open_space(csp_plugins, L"Krb5Cred\\Parameters",  0, &csp_params);
        khc_close_space(csp_plugins);
        csp_plugins = NULL;
    }

#ifdef DEBUG
    if (csp_params == NULL) {
        assert(FALSE);
    }
#endif

    if (csp_params &&
        KHM_SUCCEEDED(khc_read_int32(csp_params, L"MsLsaList", &t)) && t) {
        code = (*pkrb5_cc_resolve)(ctx, "MSLSA:", &cache);
        if (code == 0 && cache) {
            if (KHM_SUCCEEDED(khm_get_identity_expiration_time(ctx, cache, 
                                                               ident, 
                                                               &expiration))) {
                if ( expiration > best_match_expiration ) {
                    best_match_expiration = expiration;
                    StringCbCopyA(best_match_ccname, sizeof(best_match_ccname),
                                  "MSLSA:");
                    expiration = 0;
                }
            }
        }

        if (ctx != NULL && cache != NULL)
            (*pkrb5_cc_close)(ctx, cache);

        cache = 0;
    }

    if (csp_params &&
        khc_read_multi_string(csp_params, L"FileCCList", NULL, &cb)
        == KHM_ERROR_TOO_LONG &&
        cb > sizeof(wchar_t) * 2) {

        wchar_t * t;
        char ccname[MAX_PATH + 6];

        ms = PMALLOC(cb);

#ifdef DEBUG
        assert(ms);
#endif

        khc_read_multi_string(csp_params, L"FileCCList", ms, &cb);
        for(t = ms; t && *t; t = multi_string_next(t)) {
            StringCchPrintfA(ccname, ARRAYLENGTH(ccname),
                             "FILE:%S", t);

            code = (*pkrb5_cc_resolve)(ctx, ccname, &cache);
            if (code)
                continue;

            if (KHM_SUCCEEDED(khm_get_identity_expiration_time(ctx, cache, 
                                                               ident, 
                                                               &expiration))) {
                if ( expiration > best_match_expiration ) {
                    best_match_expiration = expiration;
                    StringCbCopyA(best_match_ccname,
                                  sizeof(best_match_ccname),
                                  ccname);
                    expiration = 0;
                }
            }

            if (ctx != NULL && cache != NULL)
                (*pkrb5_cc_close)(ctx, cache);
            cache = 0;
        }

        PFREE(ms);
    }
 _exit:
    if (csp_params)
        khc_close_space(csp_params);

    if (pNCi)
        (*pcc_free_NC_info)(cc_ctx, &pNCi);

    if (cc_ctx)
        (*pcc_shutdown)(&cc_ctx);

    if (best_match_ccname[0]) {
        
        if (*pcbbuf = AnsiStrToUnicode((wchar_t *)buffer, 
                                       *pcbbuf,
                                       best_match_ccname)) {

            *pcbbuf = (*pcbbuf + 1) * sizeof(wchar_t);

            return KHM_ERROR_SUCCESS;
        }

    }

    return KHM_ERROR_GENERAL;
}
Exemplo n.º 13
0
BOOL CALLBACK ExpandVolSizeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static EXPAND_VOL_THREAD_PARAMS *pVolExpandParam;

	WORD lw = LOWORD (wParam);

	switch (msg)
	{
	case WM_INITDIALOG:
		{
			char szTemp[4096];

			pVolExpandParam = (EXPAND_VOL_THREAD_PARAMS*)lParam;

			EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), !pVolExpandParam->bIsDevice);
			EnableWindow (GetDlgItem (hwndDlg, IDC_KB), !pVolExpandParam->bIsDevice);
			EnableWindow (GetDlgItem (hwndDlg, IDC_MB), !pVolExpandParam->bIsDevice);
			EnableWindow (GetDlgItem (hwndDlg, IDC_GB), !pVolExpandParam->bIsDevice);
			EnableWindow (GetDlgItem (hwndDlg, IDC_TB), !pVolExpandParam->bIsDevice);

			EnableWindow (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE),
				!(pVolExpandParam->bIsLegacy && pVolExpandParam->bIsDevice));
			SendDlgItemMessage (hwndDlg, IDC_INIT_NEWSPACE, BM_SETCHECK,
				pVolExpandParam->bInitFreeSpace ? BST_CHECKED : BST_UNCHECKED, 0);

			if (!pVolExpandParam->bIsDevice)
				SetCurrentVolSize(hwndDlg,pVolExpandParam->oldSize);

			SendMessage (GetDlgItem (hwndDlg, IDC_BOX_HELP), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE);

			GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->oldSize,pVolExpandParam->bIsDevice);

			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szTemp);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pVolExpandParam->szVolumeName);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pVolExpandParam->FileSystem]);

			if (pVolExpandParam->bIsDevice)
			{
				GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->newSize,TRUE);
			}
			else
			{
				char szHostFreeStr[256];

				SetWindowText (GetDlgItem (hwndDlg, IDT_NEW_SIZE), "");
				GetSpaceString(szHostFreeStr,sizeof(szHostFreeStr),pVolExpandParam->hostSizeFree,FALSE);
				StringCbPrintfA (szTemp,sizeof(szTemp),"%s available on host drive", szHostFreeStr);
			}

			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szTemp);

			// set help text
			if (pVolExpandParam->bIsDevice)
			{
				StringCbPrintfA (szTemp,sizeof(szTemp),"This is a device-based VeraCrypt volume.\n\nThe new volume size will be choosen automatically as the size of the host device.");
				if (pVolExpandParam->bIsLegacy)
					StringCbCatA(szTemp,sizeof(szTemp)," Note: filling the new space with random data is not supported for legacy volumes.");
			}
			else
			{
				StringCbPrintfA (szTemp, sizeof(szTemp),"Please specify the new size of the VeraCrypt volume (must be at least %I64u KB larger than the current size).",TC_MINVAL_FS_EXPAND/1024);
			}
			SetWindowText (GetDlgItem (hwndDlg, IDC_BOX_HELP), szTemp);

		}
		return 0;


	case WM_COMMAND:
		if (lw == IDCANCEL)
		{
			EndDialog (hwndDlg, lw);
			return 1;
		}

		if (lw == IDOK)
		{
			char szTemp[4096];

			pVolExpandParam->bInitFreeSpace = IsButtonChecked (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE));
			if (!pVolExpandParam->bIsDevice) // for devices new size is set by calling function
			{				
				GetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTemp, sizeof (szTemp));
				pVolExpandParam->newSize = _atoi64(szTemp) * GetSizeBoxMultiplier(hwndDlg);
			}

			EndDialog (hwndDlg, lw);
			return 1;
		}

		return 0;
	}

	return 0;
}