void openssl_x509_info() { FILE *fp; wchar_t *pUtf8; X509 *x509Cert; long Nid, Version; ASN1_INTEGER *Serial; X509_NAME *issuer, *subject; X509_NAME_ENTRY *name_entry; ASN1_TIME *timea, *timeb; char msginfo[MAX1_LEN]; const unsigned char *uCert; unsigned char tmp[MAX4_LEN]; int certLen, i, eNum, msgLen, nUtf8; OpenSSL_add_all_algorithms(); printf("\nX509_Issuer info:\n"); fp = fopen(U2CERTF, "rb"); certLen = fread(tmp, 1, 4096, fp); fclose(fp); uCert = tmp; x509Cert = d2i_X509(NULL, &uCert, certLen); Version = X509_get_version(x509Cert); printf("\tX509 Version: %ld\n", Version); Serial = X509_get_serialNumber(x509Cert); printf("\tserialNumber is: "); for (i = 0; i < Serial->length; i++) printf("%02x", Serial->data[i]); printf("\n"); issuer = X509_get_issuer_name(x509Cert); eNum = sk_X509_NAME_ENTRY_num(issuer->entries); for (i = 0; i < eNum; i++) { name_entry = sk_X509_NAME_ENTRY_value(issuer->entries, i); if (name_entry->value->type == V_ASN1_UTF8STRING) { nUtf8 = 2 * name_entry->value->length; pUtf8 = (wchar_t *) malloc(nUtf8); if (pUtf8 == NULL) return; memset(pUtf8, 0, nUtf8); mbstowcs(pUtf8, (char *)name_entry->value->data, name_entry->value->length); wcstombs(msginfo, pUtf8, nUtf8); msgLen = nUtf8; msginfo[msgLen] = '\0'; free(pUtf8); pUtf8 = NULL; } else { msgLen = name_entry->value->length; memcpy(msginfo, name_entry->value->data, msgLen); msginfo[msgLen] = '\0'; } Nid = OBJ_obj2nid(name_entry->object); switch (Nid) { case NID_countryName: printf("\tissuer's countryName: %s\n", msginfo); break; case NID_stateOrProvinceName: printf("\tissuer's provinceName: %s\n", msginfo); break; case NID_localityName: printf("\tissuer's localityName: %s\n", msginfo); break; case NID_organizationName: printf("\tissuer's organizationName: %s\n", msginfo); break; case NID_organizationalUnitName: printf("\tissuer's organizationalUnitName: %s\n", msginfo); break; case NID_commonName: printf("\tissuer's commonName: %s\n", msginfo); break; case NID_pkcs9_emailAddress: printf("\tissuer's emailAddress: %s\n", msginfo); break; default: break; } } subject = X509_get_subject_name(x509Cert); eNum = sk_X509_NAME_ENTRY_num(subject->entries); for (i = 0; i < eNum; i++) { name_entry = sk_X509_NAME_ENTRY_value(subject->entries, i); if (name_entry->value->type == V_ASN1_UTF8STRING) { nUtf8 = 2 * name_entry->value->length; pUtf8 = (wchar_t *) malloc(nUtf8); if (pUtf8 == NULL) return; memset(pUtf8, 0, nUtf8); mbstowcs(pUtf8, (char *)name_entry->value->data, name_entry->value->length); wcstombs(msginfo, pUtf8, nUtf8); msgLen = nUtf8; msginfo[msgLen] = '\0'; free(pUtf8); pUtf8 = NULL; } else { msgLen = name_entry->value->length; memcpy(msginfo, name_entry->value->data, msgLen); msginfo[msgLen] = '\0'; } Nid = OBJ_obj2nid(name_entry->object); switch (Nid) { case NID_countryName: printf("\tsubject's countryName: %s\n", msginfo); break; case NID_stateOrProvinceName: printf("\tsubject's ProvinceName: %s\n", msginfo); break; case NID_localityName: printf("\tsubject's localityName: %s\n", msginfo); break; case NID_organizationName: printf("\tsubject's organizationName: %s\n", msginfo); break; case NID_organizationalUnitName: printf("\tsubject's organizationalUnitName: %s\n", msginfo); break; case NID_commonName: printf("\tsubject's commonName: %s\n", msginfo); break; case NID_pkcs9_emailAddress: printf("\tsubject's emailAddress: %s\n", msginfo); break; default: break; } } timea = X509_get_notAfter(x509Cert); timeb = X509_get_notBefore(x509Cert); printf("\tCert notAfter: %s, notBefore: %s\n", timea->data, timeb->data); X509_free(x509Cert); return; }
/* * This function is careful to do line breaks based on wchar_t's, not * bytes, so multi-byte characters are traced properly. * However, it doesn't know that DBCS characters are two columns wide, so it * will get those wrong and break too late. To get that right, it needs some * sort of function to tell it that a wchar_t is double-width, which we lack at * the moment. * * If wchar_t's are Unicode, it could perhaps use some sort of heuristic based * on which plane the character is in. */ static void trace_ds_s(char *s, Boolean can_break) { int len = strlen(s); int len0 = len + 1; int wlen; Boolean nl = False; wchar_t *w_buf; /* wchar_t translation of s */ wchar_t *w_cur; /* current wchar_t pointer */ wchar_t *w_chunk; /* transient wchar_t buffer */ char *mb_chunk; /* transient multibyte buffer */ if (!toggled(TRACING) || tracef == NULL || !len) return; /* Allocate buffers for chunks of output data. */ mb_chunk = Malloc(len0); w_chunk = (wchar_t *)Malloc(len0 * sizeof(wchar_t)); /* Convert the input string to wchar_t's. */ w_buf = (wchar_t *)Malloc(len0 * sizeof(wchar_t)); wlen = mbstowcs(w_buf, s, len); if (wlen < 0) Error("trace_ds_s: mbstowcs failed"); w_cur = w_buf; /* Check for a trailing newline. */ if (len && s[len-1] == '\n') { wlen--; nl = True; } if (!can_break && dscnt + wlen >= 75) { wtrace("...\n... "); dscnt = 0; } while (dscnt + wlen >= 75) { int plen = 75-dscnt; int mblen; if (plen) { memcpy(w_chunk, w_cur, plen * sizeof(wchar_t)); w_chunk[plen] = 0; mblen = wcstombs(mb_chunk, w_chunk, len0); if (mblen <= 0) Error("trace_ds_s: wcstombs 1 failed"); } else { mb_chunk[0] = '\0'; mblen = 0; } wtrace("%.*s ...\n... ", mblen, mb_chunk); dscnt = 4; w_cur += plen; wlen -= plen; } if (wlen) { int mblen; memcpy(w_chunk, w_cur, wlen * sizeof(wchar_t)); w_chunk[wlen] = 0; mblen = wcstombs(mb_chunk, w_chunk, len0); if (mblen <= 0) Error("trace_ds_s: wcstombs 2 failed"); wtrace("%.*s", mblen, mb_chunk); dscnt += wlen; } if (nl) { wtrace("\n"); dscnt = 0; } Free(mb_chunk); Free(w_buf); Free(w_chunk); }
// ---------------------------------------------------------------------------- BOOL LUKS_DumpLUKSDataToFile( MODULE_DETAILS_MAIN* mainDriver, WCHAR* filename, unsigned char* userKey, BOOL baseIVCypherOnHashLength, WCHAR* dumpFilename ) { BOOL retval; LUKS_HEADER_EXT LUKSHeader; int i; char hashTitle[MAX_PRETTYPRINTED_TITLE]; char cypherTitle[MAX_PRETTYPRINTED_TITLE]; int keySlot; BYTE* keyMaterial; char IVHashTitle[MAX_PRETTYPRINTED_TITLE]; char IVCypherTitle[MAX_PRETTYPRINTED_TITLE]; char sectorIVGenMethodTitle[MAX_PRETTYPRINTED_TITLE]; char filenameAsChar[FREEOTFE_MAX_FILENAME_LENGTH * 4]; FILE* hFile; WCHAR* tmpStringGUID; char* prettyPrintData; int prettyPrintDataLength; retval = TRUE; // Sanity; source file must exist if (retval) { retval = ( SDUCheckFileExists(filename) && (!(SDUCheckFileExists(dumpFilename))) ); } if (retval) { hFile = _wfopen(dumpFilename, TEXT("w+")); driver_AddStdDumpHeader(hFile, "LUKS Dump"); // Get the LUKS header from the volume... if (!(LUKS_ReadLUKSHeader(filename, &LUKSHeader))) { if (LUKS_IsLUKSVolume(filename)) { fprintf(hFile, "ERROR: Unable to read LUKS header?!\n"); } else { fprintf(hFile, "Unable to read LUKS header; this does not appear to be a LUKS volume.\n"); } } else { fprintf(hFile, "\n"); fprintf(hFile, "\n"); driver_AddStdDumpSection(hFile, "cryptsetup Style Dump"); wcstombs(filenameAsChar, filename, sizeof(filenameAsChar)); fprintf(hFile, "LUKS header information for %s\n", filenameAsChar); SecZeroMemory(filenameAsChar, sizeof(filenameAsChar)); fprintf(hFile, "\n"); fprintf(hFile, "Version: %d\n", LUKSHeader.rawHeader.version); fprintf(hFile, "Cipher name: %s\n", LUKSHeader.rawHeader.cipher_name); fprintf(hFile, "Cipher mode: %s\n", LUKSHeader.rawHeader.cipher_mode); fprintf(hFile, "Hash spec: %s\n", LUKSHeader.rawHeader.hash_spec); fprintf(hFile, "Payload offset: %d\n", LUKSHeader.rawHeader.payload_offset); fprintf(hFile, "MK bits: %d\n", (LUKSHeader.rawHeader.key_bytes * 8)); // Convert from bytes to bits fprintf(hFile, "MK digest: "); LUKS_PrettyHex( hFile, (BYTE*)(&(LUKSHeader.rawHeader.mk_digest)), LUKS_DIGESTSIZE ); fprintf(hFile, "\n"); fprintf(hFile, "MK salt: "); LUKS_PrettyHex( hFile, &(LUKSHeader.rawHeader.mk_digest_salt[0]), (LUKS_SALTSIZE / 2) ); fprintf(hFile, "\n"); fprintf(hFile, " "); LUKS_PrettyHex( hFile, &(LUKSHeader.rawHeader.mk_digest_salt[(LUKS_SALTSIZE / 2)]), (LUKS_SALTSIZE / 2) ); fprintf(hFile, "\n"); fprintf(hFile, "MK iterations: %d\n", LUKSHeader.rawHeader.mk_digest_iter); fprintf(hFile, "UUID: %s\n", LUKSHeader.rawHeader.uuid); fprintf(hFile, "\n"); for (i = 0; i < LUKS_NUMKEYS; i++) { if (LUKSHeader.rawHeader.key_slot[i].active != LUKS_KEY_ENABLED) { fprintf(hFile, "Key Slot %d: DISABLED\n", i); } else { fprintf(hFile, "Key Slot %d: ENABLED\n", i); fprintf(hFile, " Iterations: %d\n", LUKSHeader.rawHeader.key_slot[i].iterations); fprintf(hFile, " Salt: "); LUKS_PrettyHex( hFile, &(LUKSHeader.rawHeader.key_slot[i].salt[0]), (LUKS_SALTSIZE / 2) ); fprintf(hFile, "\n"); fprintf(hFile, " "); LUKS_PrettyHex( hFile, &(LUKSHeader.rawHeader.key_slot[i].salt[(LUKS_SALTSIZE / 2)]), (LUKS_SALTSIZE / 2) ); fprintf(hFile, "\n"); fprintf(hFile, " Key material offset: %d\n", LUKSHeader.rawHeader.key_slot[i].key_material_offset); fprintf(hFile, " AF stripes: %d\n", LUKSHeader.rawHeader.key_slot[i].stripes); } } fprintf(hFile, "\n"); fprintf(hFile, "\n"); driver_AddStdDumpSection(hFile, "Mapped FreeOTFE Drivers"); if (!(LUKS_MapToFreeOTFE(baseIVCypherOnHashLength, &LUKSHeader))) { fprintf(hFile, "One or more of the following:\n"); fprintf(hFile, "\n"); fprintf(hFile, " *) The hash algorithm\n"); fprintf(hFile, " *) The cypher\n"); fprintf(hFile, " *) The IV generation method\n"); fprintf(hFile, "\n"); fprintf(hFile, "specified in the LUKS header could not be mapped to a FreeOTFE equivalent.\n"); fprintf(hFile, "This may be because the required FreeOTFE driver hasn''t been installed and\n"); fprintf(hFile, "started, or because the required LUKS option is not supported in this\n"); fprintf(hFile, "version of FreeOTFE\n"); } else { strcpy(hashTitle, "ERROR: Unable to determine hash title?!"); driver_HashPrettyprintAlgTechTitle_ByDriverAndGUID_char( LUKSHeader.hashKernelModeDeviceName, LUKSHeader.hashGUID, hashTitle, sizeof(hashTitle) ); strcpy(IVCypherTitle, "ERROR: Unable to determine cypher title?!"); driver_CypherPrettyprintAlgTechTitle_ByDriverAndGUID_char( LUKSHeader.cypherKernelModeDeviceName, LUKSHeader.cypherGUID, cypherTitle, sizeof(cypherTitle) ); if (LUKSHeader.sectorIVGenMethod != SCTRIVGEN_ESSIV) { strcpy(IVHashTitle, "IV hash n/a"); strcpy(IVCypherTitle, "IV cypher n/a"); } else { strcpy(IVHashTitle, "ERROR: Unable to determine IV hash title?!"); driver_HashPrettyprintAlgTechTitle_ByDriverAndGUID_char( LUKSHeader.IVHashKernelModeDeviceName, LUKSHeader.IVHashGUID, IVHashTitle, sizeof(IVHashTitle) ); strcpy(IVCypherTitle, "ERROR: Unable to determine IV cypher title?!"); driver_CypherPrettyprintAlgTechTitle_ByDriverAndGUID_char( LUKSHeader.IVCypherKernelModeDeviceName, LUKSHeader.IVCypherGUID, IVCypherTitle, sizeof(IVCypherTitle) ); } fprintf(hFile, "Hash pretty title : %s\n", hashTitle); fprintf(hFile, "Hash driver KM name : "); driver_DumpWCHAR(hFile, LUKSHeader.hashKernelModeDeviceName); fprintf(hFile, "\n"); fprintf(hFile, "Hash GUID : "); GUIDToWCHAR(&(LUKSHeader.hashGUID), &tmpStringGUID); SDUwcstoupper(tmpStringGUID, tmpStringGUID); driver_DumpWCHAR(hFile, tmpStringGUID); SecZeroAndFreeWCHARMemory(tmpStringGUID); fprintf(hFile, "\n"); fprintf(hFile, "Cypher pretty title : %s\n", cypherTitle); fprintf(hFile, "Cypher driver KM name : "); driver_DumpWCHAR(hFile, LUKSHeader.cypherKernelModeDeviceName); fprintf(hFile, "\n"); fprintf(hFile, "Cypher GUID : "); GUIDToWCHAR(&(LUKSHeader.cypherGUID), &tmpStringGUID); SDUwcstoupper(tmpStringGUID, tmpStringGUID); driver_DumpWCHAR(hFile, tmpStringGUID); SecZeroAndFreeWCHARMemory(tmpStringGUID); fprintf(hFile, "\n"); driver_PrettyprintSectorIVGenMethod_char( LUKSHeader.sectorIVGenMethod, sectorIVGenMethodTitle, sizeof(sectorIVGenMethodTitle) ); fprintf(hFile, "Sector IV generation : %s\n", sectorIVGenMethodTitle); if (LUKSHeader.sectorIVGenMethod == SCTRIVGEN_ESSIV) { fprintf(hFile, " IV hash pretty title : %s\n", IVHashTitle); fprintf(hFile, " IV hash driver KM name : "); driver_DumpWCHAR(hFile, LUKSHeader.IVHashKernelModeDeviceName); fprintf(hFile, "\n"); fprintf(hFile, " IV hash GUID : "); GUIDToWCHAR(&(LUKSHeader.IVHashGUID), &tmpStringGUID); SDUwcstoupper(tmpStringGUID, tmpStringGUID); driver_DumpWCHAR(hFile, tmpStringGUID); SecZeroAndFreeWCHARMemory(tmpStringGUID); fprintf(hFile, "\n"); if (baseIVCypherOnHashLength) { fprintf(hFile, " IV cypher : <based on IV hash length>\n"); } else { fprintf(hFile, " IV cypher : <same as main cypher>\n"); } fprintf(hFile, " IV cypher pretty title : %s\n", IVCypherTitle); fprintf(hFile, " IV cypher driver KM name: "); driver_DumpWCHAR(hFile, LUKSHeader.IVCypherKernelModeDeviceName); fprintf(hFile, "\n"); fprintf(hFile, " IV cypher GUID : "); GUIDToWCHAR(&(LUKSHeader.IVCypherGUID), &tmpStringGUID); SDUwcstoupper(tmpStringGUID, tmpStringGUID); driver_DumpWCHAR(hFile, tmpStringGUID); SecZeroAndFreeWCHARMemory(tmpStringGUID); fprintf(hFile, "\n"); } } fprintf(hFile, "\n"); fprintf(hFile, "\n"); driver_AddStdDumpSection(hFile, "Master Key"); fprintf(hFile, "User supplied password : %s\n", userKey); keyMaterial = NULL; if (!(LUKS_RecoverMasterKey( mainDriver, filename, userKey, baseIVCypherOnHashLength, &LUKSHeader, &keySlot, &keyMaterial ))) { fprintf(hFile, "No master key could be recovered with the specified password.\n"); } else { prettyPrintDataLength = SDUPrettyPrintHexBufReq( LUKSHeader.rawHeader.key_bytes, 8 ); prettyPrintData = malloc(prettyPrintDataLength); if (prettyPrintData == NULL) { fprintf(hFile, "Unable to allocate memory to store prettyprinted master key\n"); } else { SDUPrettyPrintHex( keyMaterial, 0, LUKSHeader.rawHeader.key_bytes, prettyPrintData, prettyPrintDataLength, 8 ); fprintf(hFile, "Password unlocks key slot: %d\n", keySlot); fprintf(hFile, "Recovered master key :\n"); fprintf(hFile, "%s", prettyPrintData); SecZeroAndFreeMemory(prettyPrintData, prettyPrintDataLength); } } SecZeroAndFreeMemory(keyMaterial, LUKSHeader.rawHeader.key_bytes); } retval = TRUE; fclose(hFile); } return retval; }
/* Encode a wide character string to the locale encoding with the surrogateescape error handler: surrogate characters in the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF. Return a pointer to a newly allocated byte string, use PyMem_Free() to free the memory. Return NULL on encoding or memory allocation error. If error_pos is not NULL, *error_pos is set to the index of the invalid character on encoding error, or set to (size_t)-1 otherwise. Use the Py_DecodeLocale() function to decode the bytes string back to a wide character string. */ char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos) { #if defined(__APPLE__) || defined(__ANDROID__) Py_ssize_t len; PyObject *unicode, *bytes = NULL; char *cpath; unicode = PyUnicode_FromWideChar(text, wcslen(text)); if (unicode == NULL) return NULL; bytes = _PyUnicode_AsUTF8String(unicode, "surrogateescape"); Py_DECREF(unicode); if (bytes == NULL) { PyErr_Clear(); if (error_pos != NULL) *error_pos = (size_t)-1; return NULL; } len = PyBytes_GET_SIZE(bytes); cpath = PyMem_Malloc(len+1); if (cpath == NULL) { PyErr_Clear(); Py_DECREF(bytes); if (error_pos != NULL) *error_pos = (size_t)-1; return NULL; } memcpy(cpath, PyBytes_AsString(bytes), len + 1); Py_DECREF(bytes); return cpath; #else /* __APPLE__ */ const size_t len = wcslen(text); char *result = NULL, *bytes = NULL; size_t i, size, converted; wchar_t c, buf[2]; #ifndef MS_WINDOWS if (force_ascii == -1) force_ascii = check_force_ascii(); if (force_ascii) return encode_ascii_surrogateescape(text, error_pos); #endif /* The function works in two steps: 1. compute the length of the output buffer in bytes (size) 2. outputs the bytes */ size = 0; buf[1] = 0; while (1) { for (i=0; i < len; i++) { c = text[i]; if (c >= 0xdc80 && c <= 0xdcff) { /* UTF-8b surrogate */ if (bytes != NULL) { *bytes++ = c - 0xdc00; size--; } else size++; continue; } else { buf[0] = c; if (bytes != NULL) converted = wcstombs(bytes, buf, size); else converted = wcstombs(NULL, buf, 0); if (converted == (size_t)-1) { if (result != NULL) PyMem_Free(result); if (error_pos != NULL) *error_pos = i; return NULL; } if (bytes != NULL) { bytes += converted; size -= converted; } else size += converted; } } if (result != NULL) { *bytes = '\0'; break; } size += 1; /* nul byte at the end */ result = PyMem_Malloc(size); if (result == NULL) { if (error_pos != NULL) *error_pos = (size_t)-1; return NULL; } bytes = result; } return result; #endif /* __APPLE__ or __ANDROID__ */ }
static int __F_NAME(__sopen,__wsopen)( const CHAR_TYPE *name, int mode, int shflag, va_list args ) { int rwmode; int handle; int attr; int permission; unsigned iomode_flags; tiny_ret_t rc; char dummy; #ifdef __WIDECHAR__ char mbName[MB_CUR_MAX * _MAX_PATH]; /* single-byte char */ #endif handle = -1; rc = 0; while( *name == STRING( ' ' ) ) ++name; #ifdef __WIDECHAR__ /*** If necessary, convert the wide filename to multibyte form ***/ if( wcstombs( mbName, name, sizeof( mbName ) ) == -1 ) { mbName[0] = '\0'; } #endif rwmode = mode & ( O_RDONLY | O_WRONLY | O_RDWR | O_NOINHERIT ); if( _dos_open( __F_NAME(name,mbName), rwmode | shflag, &handle ) == 0 ) { if( handle >= __NFiles ) { TinyClose( handle ); __set_errno( EMFILE ); return( -1 ); } } /* 17-apr-90 05-sep-91 */ if( (mode & (O_RDONLY | O_WRONLY | O_RDWR)) != O_RDONLY ) { if( handle != -1 ) { if( ! isatty( handle ) ) { /* if not a device */ #if 0 rc = TinyAccess( name, 0 ); /* check for existence */ if( TINY_ERROR( rc ) ) { /* file does not exist */ TinyClose( handle ); /* close whatever file we got */ handle = -1; } else if( mode & O_EXCL ) { /* must not exist */ #else /* Don't need to do the access check, since the file was opened and therefore must exist (TinyOpen can't create a file). We don't want to do the check because there are classes of items in the file system namespace that are not devices, but the TinyAccess will fail on (e.g. named pipes). */ /* must not exist if O_CREAT specified */ if( (mode & O_EXCL) && (mode & O_CREAT) ) { #endif TinyClose( handle ); __set_errno( EEXIST ); return( -1 ); } else if( mode & O_TRUNC ) { /* truncate file */ rc = TinyWrite( handle, &dummy, 0 ); if( TINY_ERROR( rc ) ) { TinyClose( handle ); return( __set_errno_dos( TINY_INFO( rc ) ) ); } } } } } if( handle == -1 ) { /* could not open */ if( (mode & O_CREAT) == 0 || _RWD_doserrno != E_nofile ) { return( -1 ); } /* creating the file */ permission = va_arg( args, int ); va_end( args ); if( permission == 0 ) permission = S_IWRITE | S_IREAD; permission &= ~_RWD_umaskval; /* 05-jan-95 */ attr = 0; if(( permission & S_IWRITE) == 0 ) attr = _A_RDONLY; #if 0 /* remove this support because it is not consistently available */ if( _RWD_osmajor >= 5 #ifdef __DOS_EXT__ && !_IsFlashTek() && !_IsRational() #endif ) { /* this function is only available in version DOS 5 and up */ /* this new way was added to handle the case of creating a */ /* new file with read-only access, but with a writeable */ /* file handle */ #ifdef __WIDECHAR__ rc = TinyCreateEx( mbName, rwmode|shflag, attr, TIO_OPEN ); #else rc = TinyCreateEx( name, rwmode|shflag, attr, TIO_OPEN ); #endif if( TINY_ERROR( rc ) ) { return( __set_errno_dos( TINY_INFO( rc ) ) ); } handle = TINY_INFO( rc ); } else #endif { /* do it the old way */ if( _dos_creat( __F_NAME(name,mbName), attr, &handle ) ) { return( -1 ); } if( handle >= __NFiles ) { TinyClose( handle ); __set_errno( EMFILE ); return( -1 ); } /* 21-nov-90 AFS: the file is created so now the file must be */ /* opened with the correct share permissions */ if( shflag != 0 ) { rc = TinyClose( handle ); if( TINY_ERROR( rc ) ) { return( __set_errno_dos( TINY_INFO( rc ) ) ); } if( _dos_open( __F_NAME(name,mbName), rwmode | shflag, &handle ) ) { return( -1 ); } /* handle does not equal -1 now */ } } } iomode_flags = __GetIOMode( handle ); iomode_flags &= ~(_READ|_WRITE|_APPEND|_BINARY); /* 11-aug-88 */ if( isatty( handle ) ) iomode_flags |= _ISTTY; rwmode &= ~O_NOINHERIT; if( rwmode == O_RDWR ) iomode_flags |= _READ | _WRITE; if( rwmode == O_RDONLY) iomode_flags |= _READ; if( rwmode == O_WRONLY) iomode_flags |= _WRITE; if( mode & O_APPEND ) iomode_flags |= _APPEND; if( mode & (O_BINARY|O_TEXT) ) { if( mode & O_BINARY ) iomode_flags |= _BINARY; } else { if( _RWD_fmode == O_BINARY ) iomode_flags |= _BINARY; } __SetIOMode( handle, iomode_flags ); #ifdef DEFAULT_WINDOWING if( _WindowsNewWindow != 0 ) { if( !__F_NAME(stricmp,wcscmp)( name, STRING( "con" ) ) ) { _WindowsNewWindow( NULL, handle, -1 ); } } #endif return( handle ); } #if 0 /* couldn't find any user; please re-enable if it's necessary */ #ifndef __WIDECHAR__ /* compile one version only */ int __set_binary( int handle ) { unsigned iomode_flags; __ChkTTYIOMode( handle ); iomode_flags = __GetIOMode( handle ); iomode_flags |= _BINARY; __SetIOMode( handle, iomode_flags ); if( iomode_flags & _ISTTY ) { tiny_ret_t rc; rc = TinyGetDeviceInfo( handle ); if( TINY_ERROR( rc ) ) { return( __set_errno_dos( TINY_INFO( rc ) ) ); } rc = TinySetDeviceInfo( handle, TINY_INFO(rc) | TIO_CTL_RAW ); if( TINY_ERROR( rc ) ) { return( __set_errno_dos( TINY_INFO( rc ) ) ); } } return( 0 ); }
BOOL WINAPI HookedCreateProcessInternalW( HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation, PHANDLE hNewToken ) { BOOL bReturn; CHAR szDllFullPath[MAX_PATH]; /* apply config rules if shellcode or ROP detected */ if ( DbgGetShellcodeFlag() == MCEDP_STATUS_SHELLCODE_FLAG_SET || DbgGetRopFlag() == MCEDP_STATUS_ROP_FLAG_SET ) { if ( MCEDP_REGCONFIG.SHELLCODE.ANALYSIS_SHELLCODE ) { CHAR *szApplicationNameA = (CHAR *)LocalAlloc(LMEM_ZEROINIT, 1024); CHAR *szCommandLineA = (CHAR *)LocalAlloc(LMEM_ZEROINIT, 1024); PXMLNODE XmlLogNode; PXMLNODE XmlIDLogNode; if ( lpApplicationName != NULL ) wcstombs( szApplicationNameA, lpApplicationName, 1024); if ( lpCommandLine != NULL ) wcstombs( szCommandLineA, lpCommandLine, 1024); XmlIDLogNode = mxmlNewElement( XmlShellcode, "row"); /* type */ XmlLogNode = mxmlNewElement( XmlIDLogNode, "type"); mxmlNewText( XmlLogNode, 0, "1"); /* exec */ XmlLogNode = mxmlNewElement( XmlIDLogNode, "exec_process"); mxmlNewText( XmlLogNode, 0, szApplicationNameA); XmlLogNode = mxmlNewElement( XmlIDLogNode, "exec_cmd"); mxmlNewText( XmlLogNode, 0, szCommandLineA); /* save */ SaveXml( XmlLog ); LocalFree(szApplicationNameA); LocalFree(szCommandLineA); } /* if malware execution is not allowd then terminate the process */ if ( MCEDP_REGCONFIG.GENERAL.ALLOW_MALWARE_EXEC == FALSE ) TerminateProcess(GetCurrentProcess(), STATUS_ACCESS_VIOLATION); /* let the malware execute */ return (CreateProcessInternalW_( hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, hNewToken)); } /* if the process is creating with CREATE_SUSPENDED flag, let it do its job */ if ( IsBitSet(dwCreationFlags, 2) ) { bReturn = CreateProcessInternalW_( hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, hNewToken); if ( bReturn != FALSE ) { strncpy( szDllFullPath, MCEDP_REGCONFIG.MCEDP_MODULE_PATH, MAX_PATH ); if ( InjectDLLIntoProcess( szDllFullPath, lpProcessInformation->hProcess ) != MCEDP_STATUS_SUCCESS ) { DEBUG_PRINTF(LDBG, NULL, "Module failed to inject itself into newly created process , PID : %d\n", lpProcessInformation->dwProcessId); return bReturn; } DEBUG_PRINTF(LDBG, NULL, "Module injected itself into newly created process , PID : %d\n", lpProcessInformation->dwProcessId); /* Sleep for INIT_WAIT_TIME sec and let MCEDP init itself in newly created process TODO : use a messaging mechanism and resume process after init finished instead of sleeping! */ Sleep(INIT_WAIT_TIME); return bReturn; } } else { /* if the process is not creating with CREATE_SUSPENDED flag, force it do it */ bReturn = CreateProcessInternalW_( hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags | CREATE_SUSPENDED , lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, hNewToken); if ( bReturn != FALSE ) { /* TODO : We dont need this if ther process is already added into Protection List in registry, so we should remove this lines */ strncpy( szDllFullPath, MCEDP_REGCONFIG.MCEDP_MODULE_PATH, MAX_PATH ); if ( InjectDLLIntoProcess( szDllFullPath, lpProcessInformation->hProcess ) != MCEDP_STATUS_SUCCESS ) { DEBUG_PRINTF(LDBG, NULL, "Module failed to inject itself into newly created process , PID : %d\n", lpProcessInformation->dwProcessId); ResumeThread(lpProcessInformation->hThread); return bReturn; } DEBUG_PRINTF(LDBG, NULL, "Module injected itself into newly created process , PID : %d\n", lpProcessInformation->dwProcessId); /* Sleep for INIT_WAIT_TIME sec and let MCEDP init itself in newly created process TODO : use a messaging mechanism and resume process after init finished instead of sleeping! */ Sleep(INIT_WAIT_TIME); ResumeThread(lpProcessInformation->hThread); return bReturn; } } return bReturn; }
WORKGRPDOMNT4_API BOOL CUGP(char * userin,char *password,char *machine, char *groupin, int locdom) { // FILE *file; bool isNT = true; bool isXP =false; bool access_vnc=FALSE; bool laccess_vnc=FALSE; bool localdatabase=false; ad_access=false; OSVERSIONINFO ovi = { sizeof ovi }; // determine OS and load appropriate library GetVersionEx( &ovi ); if ( ovi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) isNT = false; if (ovi.dwPlatformId == VER_PLATFORM_WIN32_NT && ovi.dwMajorVersion == 5 && ovi.dwMinorVersion >= 1) isXP=true; HINSTANCE hNet = 0, hLoc = 0; if ( isNT ) { hNet = LoadLibrary( "netapi32.dll" ); } else { hLoc = LoadLibrary( "rlocal32.dll" ); hNet = LoadLibrary( "radmin32.dll" ); } if ( hNet == 0 ) { printf( "LoadLibrary( %s ) failed, gle = %lu\n", isNT? "netapi32.dll": "radmin32.dll", GetLastError() ); return false; } // locate needed functions NetApiBufferFree_t NetApiBufferFree = 0; NetGetDCNameNT_t NetGetDCNameNT = 0; NetGetDCName95_t NetGetDCName95 = 0; NetUserGetGroupsNT_t NetUserGetGroupsNT = 0; NetUserGetGroupsNT_t2 NetUserGetGroupsNT2 = 0; NetUserGetGroups95_t NetUserGetGroups95 = 0; NetWkstaGetInfoNT_t NetWkstaGetInfoNT = 0; NetWkstaGetInfo95_t NetWkstaGetInfo95 = 0; NetApiBufferFree = (NetApiBufferFree_t) GetProcAddress( hNet, "NetApiBufferFree" ); if ( NetApiBufferFree == 0 ) { printf( "Oops! GetProcAddress() failed\n" ); return false; } if ( isNT ) { NetGetDCNameNT = (NetGetDCNameNT_t) GetProcAddress( hNet, "NetGetDCName" ); NetUserGetGroupsNT = (NetUserGetGroupsNT_t) GetProcAddress( hNet, "NetUserGetLocalGroups" ); NetUserGetGroupsNT2 = (NetUserGetGroupsNT_t2) GetProcAddress( hNet, "NetUserGetGroups" ); NetWkstaGetInfoNT = (NetWkstaGetInfoNT_t)GetProcAddress( hNet,"NetWkstaGetInfo" ); if ( NetGetDCNameNT == 0 || NetUserGetGroupsNT == 0 || NetWkstaGetInfoNT==0 ||NetUserGetGroupsNT2 == 0) { printf( "Oops! Some functions not found ...\n" ); return false; } } else { NetGetDCName95 = (NetGetDCName95_t) GetProcAddress( hLoc, "LocalNetGetDCName" ); NetUserGetGroups95 = (NetUserGetGroups95_t) GetProcAddress( hNet, "NetUserGetGroupsA" ); NetWkstaGetInfo95 = (NetWkstaGetInfo95_t)GetProcAddress( hNet,"NetWkstaGetInfoA" ); if ( NetGetDCName95 == 0 || NetUserGetGroups95 == 0 ||NetWkstaGetInfo95 == 0) { printf( "Oops! Some functions not found ...\n" ); return false; } } // find PDC if necessary; else set up server name for call byte *buf = 0; DWORD rc,rc2,read, total,i,rcdomain; char server[MAXLEN * sizeof(wchar_t)]; char user[MAXLEN * sizeof(wchar_t)]; char group[MAXLEN * sizeof(wchar_t)]; char groupname[MAXLEN]; char domain[MAXLEN * sizeof(wchar_t)]; if ( isNT ) mbstowcs( (wchar_t *) user, userin, MAXLEN ); else strcpy( user, userin ); if ( isNT ) mbstowcs( (wchar_t *) group, groupin, MAXLEN ); else strcpy( group, groupin ); //////////////////////////////////////////////////////////////////////////////////////////// ////NT //////////////////////////////////////////////////////////////////////////////////////////// if ( isNT ) { printf("Client NT4 or later \n"); ///////////////// search DC /////////////////////////////////// rcdomain = NetGetDCNameNT( 0, 0, &buf ); if (rcdomain==2453) printf( "No domain controler found\n"); if (!rcdomain) { printf("Domain controler found"); wcscpy( (wchar_t *) server, (wchar_t *) buf ); wprintf((wchar_t *)server); printf("\n------------------------------\n"); } printf("Checking Local groups for "); printf("user: %S\n", _wcsupr((wchar_t *)user)); printf("group: %S\n", _wcsupr((wchar_t *)group)); ////////////////////////////////////////////////////////////////// ///////////////// Local groups /////////////////////////////////// ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// if (locdom==1 || locdom==3){ LOCALGROUP_MEMBERS_INFO_2 *bufLMI, *cur; DWORD read, total, resumeh, rc, i; wchar_t tempbuf[MAXLEN]; wchar_t seperator[MAXLEN]; netlocalgroupgetmembers_t netlocalgroupgetmembers; HINSTANCE h = LoadLibrary ("netapi32.dll"); netlocalgroupgetmembers = (netlocalgroupgetmembers_t) GetProcAddress (h, "NetLocalGroupGetMembers"); ////////////////////// GROUPS/////////////////////////////////////// mbstowcs( seperator, "\\", 5 ); ///////////////////////GROUP1///////////////////////////////////// resumeh = 0; do { bufLMI = NULL; rc = netlocalgroupgetmembers( NULL, (wchar_t *)group, 2, (BYTE **) &bufLMI,BUFSIZE, &read, &total, &resumeh ); if ( rc == ERROR_MORE_DATA || rc == ERROR_SUCCESS ) { for ( i = 0, cur = bufLMI; i < read; ++ i, ++ cur ) { // Note: the capital S in the format string will expect Unicode // strings, as this is a program written/compiled for ANSI. _wcsupr(cur->lgrmi2_domainandname); wcscpy(tempbuf,cur->lgrmi2_domainandname); wchar_t *t=wcsstr(tempbuf,seperator); t++; printf( "%S\n", t ); if (wcscmp(_wcsupr(t), _wcsupr((wchar_t *)user))==0) { laccess_vnc=TRUE; printf( "Local: User found in group \n" ); } } if ( bufLMI != NULL ) NetApiBufferFree( bufLMI ); } } while ( rc == ERROR_MORE_DATA ); /////////////////////////////////////////////////////////////////////// if ( h != 0 )FreeLibrary( h); } if ( !rcdomain){ DWORD rc; printf( "New added ---- just for testing \n"); wcscpy( (wchar_t *) server, (wchar_t *) buf ); byte *buf2 = 0; rc2 = NetWkstaGetInfoNT( 0 , 100 , &buf2 ) ; if( rc2 ) printf( "NetWkstaGetInfoA() returned %lu \n", rc2); else wcstombs( domain, ((WKSTA_INFO_100_NT *) buf2)->wki100_langroup, MAXLEN ); NetApiBufferFree( buf2 ); domain[MAXLEN - 1] = '\0'; printf("Detected domain = %s\n",domain); buf2 = 0; char userdomain[MAXLEN * sizeof(wchar_t)]; char userdom[MAXLEN]; strcpy(userdom,domain); strcat(userdom,"\\"); strcat(userdom,userin); mbstowcs( (wchar_t *) userdomain, userdom, MAXLEN ); printf( "%S\n", userdomain); rc = NetUserGetGroupsNT( NULL ,(wchar_t *) userdomain, 0, 1,&buf2, MAX_PREFERRED_LENGTH, &read, &total); if ( rc == NERR_Success) { for ( i = 0; i < read; ++ i ) { wcstombs( groupname, ((LPLOCALGROUP_USERS_INFO_0_NT *) buf2)[i].grui0_name, MAXLEN ); groupname[MAXLEN - 1] = '\0'; // because strncpy won't do this if overflow #ifdef _MSC_VER _strupr(groupname); _strupr(groupin); #else _strupr(groupname); _strupr(groupin); #endif printf( "compare %s %s\n", groupname, group); if (strcmp(groupname, groupin)==0) { printf( "match ...\n" ); laccess_vnc=TRUE; } else printf( "no match ...\n" ); } if (laccess_vnc==TRUE) printf( "group found ...\n" ); else printf( "No group found \n" ); } NetApiBufferFree( buf2 ); } if (locdom==2 || locdom==3) if ( !rcdomain){ DWORD rc; printf( "New added ---- just for testing \n"); wcscpy( (wchar_t *) server, (wchar_t *) buf ); byte *buf2 = 0; rc2 = NetWkstaGetInfoNT( 0 , 100 , &buf2 ) ; if( rc2 ) printf( "NetWkstaGetInfoA() returned %lu \n", rc2); else wcstombs( domain, ((WKSTA_INFO_100_NT *) buf2)->wki100_langroup, MAXLEN ); NetApiBufferFree( buf2 ); domain[MAXLEN - 1] = '\0'; printf("Detected domain = %s\n",domain); buf2 = 0; char userdomain[MAXLEN * sizeof(wchar_t)]; char userdom[MAXLEN]; //strcpy(userdom,domain); //strcat(userdom,"\\"); strcpy(userdom,userin); mbstowcs( (wchar_t *) userdomain, userdom, MAXLEN ); printf( "%S\n", userdomain); rc = NetUserGetGroupsNT2( (wchar_t *)server,(wchar_t *) userdomain, 0,&buf2, MAX_PREFERRED_LENGTH, &read, &total); if ( rc == NERR_Success) { for ( i = 0; i < read; ++ i ) { wcstombs( groupname, ((LPLOCALGROUP_USERS_INFO_0_NT *) buf2)[i].grui0_name, MAXLEN ); groupname[MAXLEN - 1] = '\0'; // because strncpy won't do this if overflow #ifdef _MSC_VER _strupr(groupname); _strupr(groupin); #else _strupr(groupname); _strupr(groupin); #endif printf( "compare %s %s\n", groupname, group); if (strcmp(groupname, groupin)==0) { printf( "match ...\n" ); laccess_vnc=TRUE; } else printf( "no match ...\n" ); } if (laccess_vnc==TRUE) printf( "group found ...\n" ); else printf( "No group found \n" ); } NetApiBufferFree( buf2 ); } } //////////////////////////////////////////////////////////////////////////////////////////// ////9.X //////////////////////////////////////////////////////////////////////////////////////////// if (locdom==2 || locdom==3) if ( !isNT ) { rc = NetGetDCName95( 0, &buf ); if ( rc ) printf( "NetGetDCName95() returned %lu\n", rc ); if (rc==2453) { printf( "No domain controler found\n"); return false; } if ( !rc ) { strcpy( server, (char *) buf ); byte *buf2 = 0; rc = NetWkstaGetInfo95( 0 , 100 , &buf2 ) ; if( rc ) printf( "NetWkstaGetInfoA() returned %lu \n", rc); else strncpy( domain, ((WKSTA_INFO_100_95 *) buf2)->wki100_langroup, MAXLEN ); NetApiBufferFree( buf2 ); domain[MAXLEN - 1] = '\0'; NetApiBufferFree( buf ); buf = 0; buf2 = 0; //////////////////////////////////////////// rc = NetUserGetGroups95( server,user, 0, &buf2, 2024, &read, &total); if ( rc == NERR_Success) { for ( i = 0; i < read; ++ i ) { strncpy( groupname, ((LPLOCALGROUP_USERS_INFO_0_95 *) buf2)[i].grui0_name, MAXLEN ); groupname[MAXLEN - 1] = '\0'; // because strncpy won't do this if overflow #ifdef _MSC_VER _strupr(groupname); #else _strupr(groupname); #endif printf( "%s\n", groupname); if (strcmp(groupname, group)==0) laccess_vnc=TRUE; } if (access_vnc==TRUE) printf( "NT: Domain group found ...\n" ); else printf( "No Domain group found \n" ); } NetApiBufferFree( buf2 ); buf2=0; } } if (buf)NetApiBufferFree( buf ); if ( hNet != 0 ) FreeLibrary( hNet ); if ( hLoc != 0 ) FreeLibrary( hLoc ); //check user if (isNT) { #if _MSC_VER < 1400 wcstombs( user, (unsigned short *)user, MAXLEN); #else wcstombs( user, (const wchar_t *)user, MAXLEN); #endif } BOOL logon_OK=false; BOOL passwd_OK=false; #ifdef _MSC_VER _strupr(user); #else _strupr(user); #endif passwd_OK=false; if (isXP) { LOGONUSER LU=NULL; HMODULE shell1 = LoadLibrary("advapi32.dll"); if(shell1!=NULL) LU = (LOGONUSER)GetProcAddress((HINSTANCE)shell1,"LogonUserA"); if (LU!=NULL) { HANDLE token; if (locdom==2 || locdom==3 ||locdom==1) if (LU(user,domain,password,LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,&token)) { passwd_OK=true; if (passwd_OK==TRUE) printf( "Domain password check OK \n" ); else printf( "Domain password check Failed \n" ); } if (locdom==1 || locdom==3) if (LU(user,".",password,LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,&token)) { passwd_OK=true; if (passwd_OK==TRUE) printf( "Local password check OK \n" ); } } FreeLibrary(shell1); } else { if (locdom==2 || locdom==3 || locdom==1) if (SSPLogonUser(domain,user, password)) { passwd_OK=true; if (passwd_OK==TRUE) printf( "Domain password check OK \n" ); } else printf( "Domain password check Failed \n" ); if (locdom==1 || locdom==3) if (SSPLogonUser(".",user, password)) { passwd_OK=true; if (passwd_OK==TRUE) printf( "Local password check OK \n" ); } else printf( "Local password check Failed \n" ); if (locdom==2 || locdom==3)if (SSPLogonUser(domain,"isdiua", "hegbfsa")) {passwd_OK=false;printf( "Guest account block \n" );} if (locdom==1 || locdom==3)if (SSPLogonUser(".","isdiua", "hegbfsa")) {passwd_OK=false;printf( "Guest account block \n" );} } if (access_vnc==TRUE || laccess_vnc==TRUE || ad_access==TRUE) { if (passwd_OK) { logon_OK=true; printf( "Acces to vnc OK \n" ); } } return logon_OK; }
void load_libs(void) { struct dirent *entry; DIR *extdir; void *lib; initfun initializer; const char *ext; wchar_t path[512] = { 0 }; char *asciipath; _api *a = malloc(sizeof(_api)); chatenv *c = malloc(sizeof(chatenv)); c->get_users = rget_users; if (a == NULL) HANDLE_ERR("Unable to allocate memory for _api"); a->hook_msg = hook_msg; a->hook_join = hook_join; a->hook_part = hook_part; a->unhook = ev_unhook; a->events = ev_get_global(); a->setting_store = setting_store; a->setting_get = setting_get; a->chatenv = c; wchar_t *exts = setting_get(BKEY_EXTENSIONS_DIR); if (exts == NULL) { free(a); return; } char *asciidir = calloc(1, wcslen(exts) * 4); wcstombs(asciidir, exts, wcslen(exts) * 4); extdir = opendir(asciidir); if (extdir == NULL) { perror("Couldn't open extension directory"); exit(EXIT_FAILURE); return; } while ((entry = readdir(extdir))) { ext = get_extension(entry->d_name); if (strcmp(ext, "so") == 0) { wmemset(path, 0, 512); swprintf(path, 511, L"%s/%s", asciidir, entry->d_name); asciipath = calloc(1, 1022); wcstombs(asciipath, path, 1022); lib = dlopen(asciipath, RTLD_NOW); free(asciipath); if (lib == NULL) { wprintf(L"Unable to read %ls, invalid library\n", path); continue; } initializer = (initfun)dlsym(lib, BINIT_FUNCTION); if (initializer == NULL) { wprintf(L"Symbol %s not found in %ls, might want to fix that.\n", BINIT_FUNCTION, path); continue; } initializer(a); } } free(asciidir); closedir(extdir); }
std::vector<ip_route> enum_routes(io_service& ios, error_code& ec) { std::vector<ip_route> ret; TORRENT_UNUSED(ios); #ifdef TORRENT_BUILD_SIMULATOR TORRENT_UNUSED(ec); ip_route r; r.destination = address_v4(); r.netmask = address_v4::from_string("255.255.255.0"); address_v4::bytes_type b = ios.get_ip().to_v4().to_bytes(); b[3] = 1; r.gateway = address_v4(b); strcpy(r.name, "eth0"); r.mtu = ios.sim().config().path_mtu(ios.get_ip(), ios.get_ip()); ret.push_back(r); #elif TORRENT_USE_SYSCTL /* struct rt_msg { rt_msghdr m_rtm; char buf[512]; }; rt_msg m; int len = sizeof(rt_msg); bzero(&m, len); m.m_rtm.rtm_type = RTM_GET; m.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY; m.m_rtm.rtm_version = RTM_VERSION; m.m_rtm.rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK; m.m_rtm.rtm_seq = 0; m.m_rtm.rtm_msglen = len; int s = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC); if (s == -1) { ec = error_code(errno, boost::asio::error::system_category); return std::vector<ip_route>(); } int n = write(s, &m, len); if (n == -1) { ec = error_code(errno, boost::asio::error::system_category); close(s); return std::vector<ip_route>(); } else if (n != len) { ec = boost::asio::error::operation_not_supported; close(s); return std::vector<ip_route>(); } bzero(&m, len); n = read(s, &m, len); if (n == -1) { ec = error_code(errno, boost::asio::error::system_category); close(s); return std::vector<ip_route>(); } for (rt_msghdr* ptr = &m.m_rtm; (char*)ptr < ((char*)&m.m_rtm) + n; ptr = (rt_msghdr*)(((char*)ptr) + ptr->rtm_msglen)) { std::cout << " rtm_msglen: " << ptr->rtm_msglen << std::endl; std::cout << " rtm_type: " << ptr->rtm_type << std::endl; if (ptr->rtm_errno) { ec = error_code(ptr->rtm_errno, boost::asio::error::system_category); return std::vector<ip_route>(); } if (m.m_rtm.rtm_flags & RTF_UP == 0 || m.m_rtm.rtm_flags & RTF_GATEWAY == 0) { ec = boost::asio::error::operation_not_supported; return address_v4::any(); } if (ptr->rtm_addrs & RTA_DST == 0 || ptr->rtm_addrs & RTA_GATEWAY == 0 || ptr->rtm_addrs & RTA_NETMASK == 0) { ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } if (ptr->rtm_msglen > len - ((char*)ptr - ((char*)&m.m_rtm))) { ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } int min_len = sizeof(rt_msghdr) + 2 * sizeof(sockaddr_in); if (m.m_rtm.rtm_msglen < min_len) { ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } ip_route r; // destination char* p = m.buf; sockaddr_in* sin = (sockaddr_in*)p; r.destination = sockaddr_to_address((sockaddr*)p); // gateway p += sin->sin_len; sin = (sockaddr_in*)p; r.gateway = sockaddr_to_address((sockaddr*)p); // netmask p += sin->sin_len; sin = (sockaddr_in*)p; r.netmask = sockaddr_to_address((sockaddr*)p); ret.push_back(r); } close(s); */ int mib[6] = { CTL_NET, PF_ROUTE, 0, AF_UNSPEC, NET_RT_DUMP, 0}; size_t needed = 0; #ifdef TORRENT_OS2 if (__libsocket_sysctl(mib, 6, 0, &needed, 0, 0) < 0) #else if (sysctl(mib, 6, 0, &needed, 0, 0) < 0) #endif { ec = error_code(errno, boost::asio::error::system_category); return std::vector<ip_route>(); } if (needed <= 0) { return std::vector<ip_route>(); } boost::scoped_array<char> buf(new (std::nothrow) char[needed]); if (buf.get() == 0) { ec = boost::asio::error::no_memory; return std::vector<ip_route>(); } #ifdef TORRENT_OS2 if (__libsocket_sysctl(mib, 6, buf.get(), &needed, 0, 0) < 0) #else if (sysctl(mib, 6, buf.get(), &needed, 0, 0) < 0) #endif { ec = error_code(errno, boost::asio::error::system_category); return std::vector<ip_route>(); } char* end = buf.get() + needed; int s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { ec = error_code(errno, boost::asio::error::system_category); return std::vector<ip_route>(); } rt_msghdr* rtm; for (char* next = buf.get(); next < end; next += rtm->rtm_msglen) { rtm = reinterpret_cast<rt_msghdr*>(next); if (rtm->rtm_version != RTM_VERSION) continue; ip_route r; if (parse_route(s, rtm, &r)) ret.push_back(r); } close(s); #elif TORRENT_USE_GETIPFORWARDTABLE /* move this to enum_net_interfaces // Load Iphlpapi library HMODULE iphlp = LoadLibraryA("Iphlpapi.dll"); if (!iphlp) { ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } // Get GetAdaptersInfo() pointer typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG); GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo"); if (!GetAdaptersInfo) { FreeLibrary(iphlp); ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } PIP_ADAPTER_INFO adapter_info = 0; ULONG out_buf_size = 0; if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW) { FreeLibrary(iphlp); ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size); if (!adapter_info) { FreeLibrary(iphlp); ec = boost::asio::error::no_memory; return std::vector<ip_route>(); } if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR) { for (PIP_ADAPTER_INFO adapter = adapter_info; adapter != 0; adapter = adapter->Next) { ip_route r; r.destination = address::from_string(adapter->IpAddressList.IpAddress.String, ec); r.gateway = address::from_string(adapter->GatewayList.IpAddress.String, ec); r.netmask = address::from_string(adapter->IpAddressList.IpMask.String, ec); strncpy(r.name, adapter->AdapterName, sizeof(r.name)); if (ec) { ec = error_code(); continue; } ret.push_back(r); } } // Free memory free(adapter_info); FreeLibrary(iphlp); */ // Load Iphlpapi library HMODULE iphlp = LoadLibraryA("Iphlpapi.dll"); if (!iphlp) { ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } typedef DWORD (WINAPI *GetIfEntry_t)(PMIB_IFROW pIfRow); GetIfEntry_t GetIfEntry = (GetIfEntry_t)GetProcAddress(iphlp, "GetIfEntry"); if (!GetIfEntry) { ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } #if _WIN32_WINNT >= 0x0600 typedef DWORD (WINAPI *GetIpForwardTable2_t)( ADDRESS_FAMILY, PMIB_IPFORWARD_TABLE2*); typedef void (WINAPI *FreeMibTable_t)(PVOID Memory); GetIpForwardTable2_t GetIpForwardTable2 = (GetIpForwardTable2_t)GetProcAddress( iphlp, "GetIpForwardTable2"); FreeMibTable_t FreeMibTable = (FreeMibTable_t)GetProcAddress( iphlp, "FreeMibTable"); if (GetIpForwardTable2 && FreeMibTable) { MIB_IPFORWARD_TABLE2* routes = NULL; int res = GetIpForwardTable2(AF_UNSPEC, &routes); if (res == NO_ERROR) { for (int i = 0; i < routes->NumEntries; ++i) { ip_route r; r.gateway = sockaddr_to_address((const sockaddr*)&routes->Table[i].NextHop); r.destination = sockaddr_to_address( (const sockaddr*)&routes->Table[i].DestinationPrefix.Prefix); r.netmask = build_netmask(routes->Table[i].SitePrefixLength , routes->Table[i].DestinationPrefix.Prefix.si_family); MIB_IFROW ifentry; ifentry.dwIndex = routes->Table[i].InterfaceIndex; if (GetIfEntry(&ifentry) == NO_ERROR) { wcstombs(r.name, ifentry.wszName, sizeof(r.name)); r.mtu = ifentry.dwMtu; ret.push_back(r); } } } if (routes) FreeMibTable(routes); FreeLibrary(iphlp); return ret; } #endif // Get GetIpForwardTable() pointer typedef DWORD (WINAPI *GetIpForwardTable_t)(PMIB_IPFORWARDTABLE pIpForwardTable,PULONG pdwSize,BOOL bOrder); GetIpForwardTable_t GetIpForwardTable = (GetIpForwardTable_t)GetProcAddress( iphlp, "GetIpForwardTable"); if (!GetIpForwardTable) { FreeLibrary(iphlp); ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } MIB_IPFORWARDTABLE* routes = NULL; ULONG out_buf_size = 0; if (GetIpForwardTable(routes, &out_buf_size, FALSE) != ERROR_INSUFFICIENT_BUFFER) { FreeLibrary(iphlp); ec = boost::asio::error::operation_not_supported; return std::vector<ip_route>(); } routes = (MIB_IPFORWARDTABLE*)malloc(out_buf_size); if (!routes) { FreeLibrary(iphlp); ec = boost::asio::error::no_memory; return std::vector<ip_route>(); } if (GetIpForwardTable(routes, &out_buf_size, FALSE) == NO_ERROR) { for (int i = 0; i < routes->dwNumEntries; ++i) { ip_route r; r.destination = inaddr_to_address((in_addr const*)&routes->table[i].dwForwardDest); r.netmask = inaddr_to_address((in_addr const*)&routes->table[i].dwForwardMask); r.gateway = inaddr_to_address((in_addr const*)&routes->table[i].dwForwardNextHop); MIB_IFROW ifentry; ifentry.dwIndex = routes->table[i].dwForwardIfIndex; if (GetIfEntry(&ifentry) == NO_ERROR) { wcstombs(r.name, ifentry.wszName, sizeof(r.name)); r.name[sizeof(r.name)-1] = 0; r.mtu = ifentry.dwMtu; ret.push_back(r); } } } // Free memory free(routes); FreeLibrary(iphlp); #elif TORRENT_USE_NETLINK enum { BUFSIZE = 8192 }; int sock = socket(PF_ROUTE, SOCK_DGRAM, NETLINK_ROUTE); if (sock < 0) { ec = error_code(errno, boost::asio::error::system_category); return std::vector<ip_route>(); } int seq = 0; char msg[BUFSIZE]; memset(msg, 0, BUFSIZE); nlmsghdr* nl_msg = (nlmsghdr*)msg; nl_msg->nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg)); nl_msg->nlmsg_type = RTM_GETROUTE; nl_msg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST; nl_msg->nlmsg_seq = seq++; nl_msg->nlmsg_pid = getpid(); if (send(sock, nl_msg, nl_msg->nlmsg_len, 0) < 0) { ec = error_code(errno, boost::asio::error::system_category); close(sock); return std::vector<ip_route>(); } int len = read_nl_sock(sock, msg, BUFSIZE, seq, getpid()); if (len < 0) { ec = error_code(errno, boost::asio::error::system_category); close(sock); return std::vector<ip_route>(); } int s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { ec = error_code(errno, boost::asio::error::system_category); return std::vector<ip_route>(); } for (; NLMSG_OK(nl_msg, len); nl_msg = NLMSG_NEXT(nl_msg, len)) { ip_route r; if (parse_route(s, nl_msg, &r)) ret.push_back(r); } close(s); close(sock); #endif return ret; }
/* PSYCHHIDCheckInit() Check to see if we need to create the USB-HID device list. If it has not been created then create it. */ void PsychHIDVerifyInit(void) { int busId, devId; pRecDevice currentDevice = NULL; struct hid_device_info* hid_dev = NULL; // If hid_devices list of all HID devices not yet initialized, // perform device enumeration: if (!hidlib_devices) { // Low-Level enumeration by HIDLIB: hidlib_devices = hid_enumerate(0x0, 0x0); // Build our own higher-level device list filled with info // from the low-level list: for (hid_dev = hidlib_devices; hid_dev != NULL; hid_dev = hid_dev->next) { // Allocate and zero-init high level struct currentDevice: currentDevice = calloc(1, sizeof(recDevice)); // Copy low-level props to corresponding high-level props: currentDevice->usagePage = hid_dev->usage_page; currentDevice->usage = hid_dev->usage; // Abuse the "transport" string for the device path. On OS/X this just contains "USB": sprintf(¤tDevice->transport[0], "%s", hid_dev->path); currentDevice->vendorID = hid_dev->vendor_id; currentDevice->productID = hid_dev->product_id; currentDevice->version = hid_dev->release_number; if (hid_dev->manufacturer_string) wcstombs(¤tDevice->manufacturer[0], hid_dev->manufacturer_string, 256); if (hid_dev->product_string) wcstombs(¤tDevice->product[0], hid_dev->product_string, 256); if (hid_dev->serial_number) wcstombs(¤tDevice->serial[0], hid_dev->serial_number, 256); // Convert unique device path into unique numeric location id: if (PSYCH_SYSTEM == PSYCH_LINUX) { // Use USB bus-id and device-id as unique location identifier: sscanf(hid_dev->path, "%x:%x", &busId, &devId); currentDevice->locID = (double) ((busId << 16) + (devId << 0)); } if (PSYCH_SYSTEM == PSYCH_WINDOWS) { // Use device container id as unique location identifier. // This may only work on Windows-7+ and is a bit of a hack here, // the id is a GUID, nothing related to busId or devId. We init // devId with the hid_dev pointer value, to get a devId and thereby // location id in case proper parsing of a container id doesn't work: busId = 0; devId = (int) hid_dev; if (strstr(hid_dev->path, "{")) sscanf(strstr(hid_dev->path, "{"), "{%x-%x", &busId, &devId); currentDevice->locID = (double) (((psych_uint64) busId << 32) + devId); } // Interface number is great for identifying DAQ devices, but not available // on OS/X, so this will be a Linux/Windows only thing. currentDevice->interfaceId = hid_dev->interface_number; // Enqueue record into linked list: currentDevice->pNext = hid_devices; hid_devices = currentDevice; } } return; }
static int do_test (void) { struct sigaction sa; sa.sa_handler = handler; sa.sa_flags = 0; sigemptyset (&sa.sa_mask); sigaction (SIGABRT, &sa, NULL); /* Avoid all the buffer overflow messages on stderr. */ int fd = open (_PATH_DEVNULL, O_WRONLY); if (fd == -1) close (STDERR_FILENO); else { dup2 (fd, STDERR_FILENO); close (fd); } setenv ("LIBC_FATAL_STDERR_", "1", 1); struct A { char buf1[9]; char buf2[1]; } a; struct wA { wchar_t buf1[9]; wchar_t buf2[1]; } wa; printf ("Test checking routines at fortify level %d\n", #ifdef __USE_FORTIFY_LEVEL (int) __USE_FORTIFY_LEVEL #else 0 #endif ); /* These ops can be done without runtime checking of object size. */ memcpy (buf, "abcdefghij", 10); memmove (buf + 1, buf, 9); if (memcmp (buf, "aabcdefghi", 10)) FAIL (); if (mempcpy (buf + 5, "abcde", 5) != buf + 10 || memcmp (buf, "aabcdabcde", 10)) FAIL (); memset (buf + 8, 'j', 2); if (memcmp (buf, "aabcdabcjj", 10)) FAIL (); strcpy (buf + 4, "EDCBA"); if (memcmp (buf, "aabcEDCBA", 10)) FAIL (); if (stpcpy (buf + 8, "F") != buf + 9 || memcmp (buf, "aabcEDCBF", 10)) FAIL (); strncpy (buf + 6, "X", 4); if (memcmp (buf, "aabcEDX\0\0", 10)) FAIL (); if (sprintf (buf + 7, "%s", "67") != 2 || memcmp (buf, "aabcEDX67", 10)) FAIL (); if (snprintf (buf + 7, 3, "%s", "987654") != 6 || memcmp (buf, "aabcEDX98", 10)) FAIL (); /* These ops need runtime checking, but shouldn't __chk_fail. */ memcpy (buf, "abcdefghij", l0 + 10); memmove (buf + 1, buf, l0 + 9); if (memcmp (buf, "aabcdefghi", 10)) FAIL (); if (mempcpy (buf + 5, "abcde", l0 + 5) != buf + 10 || memcmp (buf, "aabcdabcde", 10)) FAIL (); memset (buf + 8, 'j', l0 + 2); if (memcmp (buf, "aabcdabcjj", 10)) FAIL (); strcpy (buf + 4, str1 + 5); if (memcmp (buf, "aabcEDCBA", 10)) FAIL (); if (stpcpy (buf + 8, str2) != buf + 9 || memcmp (buf, "aabcEDCBF", 10)) FAIL (); strncpy (buf + 6, "X", l0 + 4); if (memcmp (buf, "aabcEDX\0\0", 10)) FAIL (); if (stpncpy (buf + 5, "cd", l0 + 5) != buf + 7 || memcmp (buf, "aabcEcd\0\0", 10)) FAIL (); if (sprintf (buf + 7, "%d", num1) != 2 || memcmp (buf, "aabcEcd67", 10)) FAIL (); if (snprintf (buf + 7, 3, "%d", num2) != 6 || memcmp (buf, "aabcEcd98", 10)) FAIL (); buf[l0 + 8] = '\0'; strcat (buf, "A"); if (memcmp (buf, "aabcEcd9A", 10)) FAIL (); buf[l0 + 7] = '\0'; strncat (buf, "ZYXWV", l0 + 2); if (memcmp (buf, "aabcEcdZY", 10)) FAIL (); memcpy (a.buf1, "abcdefghij", l0 + 10); memmove (a.buf1 + 1, a.buf1, l0 + 9); if (memcmp (a.buf1, "aabcdefghi", 10)) FAIL (); if (mempcpy (a.buf1 + 5, "abcde", l0 + 5) != a.buf1 + 10 || memcmp (a.buf1, "aabcdabcde", 10)) FAIL (); memset (a.buf1 + 8, 'j', l0 + 2); if (memcmp (a.buf1, "aabcdabcjj", 10)) FAIL (); #if __USE_FORTIFY_LEVEL < 2 /* The following tests are supposed to crash with -D_FORTIFY_SOURCE=2 and sufficient GCC support, as the string operations overflow from a.buf1 into a.buf2. */ strcpy (a.buf1 + 4, str1 + 5); if (memcmp (a.buf1, "aabcEDCBA", 10)) FAIL (); if (stpcpy (a.buf1 + 8, str2) != a.buf1 + 9 || memcmp (a.buf1, "aabcEDCBF", 10)) FAIL (); strncpy (a.buf1 + 6, "X", l0 + 4); if (memcmp (a.buf1, "aabcEDX\0\0", 10)) FAIL (); if (sprintf (a.buf1 + 7, "%d", num1) != 2 || memcmp (a.buf1, "aabcEDX67", 10)) FAIL (); if (snprintf (a.buf1 + 7, 3, "%d", num2) != 6 || memcmp (a.buf1, "aabcEDX98", 10)) FAIL (); a.buf1[l0 + 8] = '\0'; strcat (a.buf1, "A"); if (memcmp (a.buf1, "aabcEDX9A", 10)) FAIL (); a.buf1[l0 + 7] = '\0'; strncat (a.buf1, "ZYXWV", l0 + 2); if (memcmp (a.buf1, "aabcEDXZY", 10)) FAIL (); #endif #if __USE_FORTIFY_LEVEL >= 1 /* Now check if all buffer overflows are caught at runtime. */ CHK_FAIL_START memcpy (buf + 1, "abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START memmove (buf + 2, buf + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START p = mempcpy (buf + 6, "abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START memset (buf + 9, 'j', l0 + 2); CHK_FAIL_END CHK_FAIL_START strcpy (buf + 5, str1 + 5); CHK_FAIL_END CHK_FAIL_START p = stpcpy (buf + 9, str2); CHK_FAIL_END CHK_FAIL_START strncpy (buf + 7, "X", l0 + 4); CHK_FAIL_END CHK_FAIL_START stpncpy (buf + 6, "cd", l0 + 5); CHK_FAIL_END CHK_FAIL_START sprintf (buf + 8, "%d", num1); CHK_FAIL_END CHK_FAIL_START snprintf (buf + 8, l0 + 3, "%d", num2); CHK_FAIL_END memcpy (buf, str1 + 2, l0 + 9); CHK_FAIL_START strcat (buf, "AB"); CHK_FAIL_END memcpy (buf, str1 + 3, l0 + 8); CHK_FAIL_START strncat (buf, "ZYXWV", l0 + 3); CHK_FAIL_END CHK_FAIL_START memcpy (a.buf1 + 1, "abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START memmove (a.buf1 + 2, a.buf1 + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START p = mempcpy (a.buf1 + 6, "abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START memset (a.buf1 + 9, 'j', l0 + 2); CHK_FAIL_END #if __USE_FORTIFY_LEVEL >= 2 # define O 0 #else # define O 1 #endif CHK_FAIL_START strcpy (a.buf1 + (O + 4), str1 + 5); CHK_FAIL_END CHK_FAIL_START p = stpcpy (a.buf1 + (O + 8), str2); CHK_FAIL_END CHK_FAIL_START strncpy (a.buf1 + (O + 6), "X", l0 + 4); CHK_FAIL_END CHK_FAIL_START sprintf (a.buf1 + (O + 7), "%d", num1); CHK_FAIL_END CHK_FAIL_START snprintf (a.buf1 + (O + 7), l0 + 3, "%d", num2); CHK_FAIL_END memcpy (a.buf1, str1 + (3 - O), l0 + 8 + O); CHK_FAIL_START strcat (a.buf1, "AB"); CHK_FAIL_END memcpy (a.buf1, str1 + (4 - O), l0 + 7 + O); CHK_FAIL_START strncat (a.buf1, "ZYXWV", l0 + 3); CHK_FAIL_END #endif /* These ops can be done without runtime checking of object size. */ wmemcpy (wbuf, L"abcdefghij", 10); wmemmove (wbuf + 1, wbuf, 9); if (wmemcmp (wbuf, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wbuf + 5, L"abcde", 5) != wbuf + 10 || wmemcmp (wbuf, L"aabcdabcde", 10)) FAIL (); wmemset (wbuf + 8, L'j', 2); if (wmemcmp (wbuf, L"aabcdabcjj", 10)) FAIL (); wcscpy (wbuf + 4, L"EDCBA"); if (wmemcmp (wbuf, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wbuf + 8, L"F") != wbuf + 9 || wmemcmp (wbuf, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wbuf + 6, L"X", 4); if (wmemcmp (wbuf, L"aabcEDX\0\0", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"%ls", L"987654") >= 0 || wmemcmp (wbuf, L"aabcEDX98", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"64") != 2 || wmemcmp (wbuf, L"aabcEDX64", 10)) FAIL (); /* These ops need runtime checking, but shouldn't __chk_fail. */ wmemcpy (wbuf, L"abcdefghij", l0 + 10); wmemmove (wbuf + 1, wbuf, l0 + 9); if (wmemcmp (wbuf, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wbuf + 5, L"abcde", l0 + 5) != wbuf + 10 || wmemcmp (wbuf, L"aabcdabcde", 10)) FAIL (); wmemset (wbuf + 8, L'j', l0 + 2); if (wmemcmp (wbuf, L"aabcdabcjj", 10)) FAIL (); wcscpy (wbuf + 4, wstr1 + 5); if (wmemcmp (wbuf, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wbuf + 8, wstr2) != wbuf + 9 || wmemcmp (wbuf, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wbuf + 6, L"X", l0 + 4); if (wmemcmp (wbuf, L"aabcEDX\0\0", 10)) FAIL (); if (wcpncpy (wbuf + 5, L"cd", l0 + 5) != wbuf + 7 || wmemcmp (wbuf, L"aabcEcd\0\0", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"%d", num2) >= 0 || wmemcmp (wbuf, L"aabcEcd98", 10)) FAIL (); wbuf[l0 + 8] = L'\0'; wcscat (wbuf, L"A"); if (wmemcmp (wbuf, L"aabcEcd9A", 10)) FAIL (); wbuf[l0 + 7] = L'\0'; wcsncat (wbuf, L"ZYXWV", l0 + 2); if (wmemcmp (wbuf, L"aabcEcdZY", 10)) FAIL (); wmemcpy (wa.buf1, L"abcdefghij", l0 + 10); wmemmove (wa.buf1 + 1, wa.buf1, l0 + 9); if (wmemcmp (wa.buf1, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wa.buf1 + 5, L"abcde", l0 + 5) != wa.buf1 + 10 || wmemcmp (wa.buf1, L"aabcdabcde", 10)) FAIL (); wmemset (wa.buf1 + 8, L'j', l0 + 2); if (wmemcmp (wa.buf1, L"aabcdabcjj", 10)) FAIL (); #if __USE_FORTIFY_LEVEL < 2 /* The following tests are supposed to crash with -D_FORTIFY_SOURCE=2 and sufficient GCC support, as the string operations overflow from a.buf1 into a.buf2. */ wcscpy (wa.buf1 + 4, wstr1 + 5); if (wmemcmp (wa.buf1, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wa.buf1 + 8, wstr2) != wa.buf1 + 9 || wmemcmp (wa.buf1, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wa.buf1 + 6, L"X", l0 + 4); if (wmemcmp (wa.buf1, L"aabcEDX\0\0", 10)) FAIL (); if (swprintf (wa.buf1 + 7, 3, L"%d", num2) >= 0 || wmemcmp (wa.buf1, L"aabcEDX98", 10)) FAIL (); wa.buf1[l0 + 8] = L'\0'; wcscat (wa.buf1, L"A"); if (wmemcmp (wa.buf1, L"aabcEDX9A", 10)) FAIL (); wa.buf1[l0 + 7] = L'\0'; wcsncat (wa.buf1, L"ZYXWV", l0 + 2); if (wmemcmp (wa.buf1, L"aabcEDXZY", 10)) FAIL (); #endif #if __USE_FORTIFY_LEVEL >= 1 /* Now check if all buffer overflows are caught at runtime. */ CHK_FAIL_START wmemcpy (wbuf + 1, L"abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START wmemmove (wbuf + 2, wbuf + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START wp = wmempcpy (wbuf + 6, L"abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START wmemset (wbuf + 9, L'j', l0 + 2); CHK_FAIL_END CHK_FAIL_START wcscpy (wbuf + 5, wstr1 + 5); CHK_FAIL_END CHK_FAIL_START wp = wcpcpy (wbuf + 9, wstr2); CHK_FAIL_END CHK_FAIL_START wcsncpy (wbuf + 7, L"X", l0 + 4); CHK_FAIL_END CHK_FAIL_START wcpncpy (wbuf + 6, L"cd", l0 + 5); CHK_FAIL_END wmemcpy (wbuf, wstr1 + 2, l0 + 9); CHK_FAIL_START wcscat (wbuf, L"AB"); CHK_FAIL_END wmemcpy (wbuf, wstr1 + 3, l0 + 8); CHK_FAIL_START wcsncat (wbuf, L"ZYXWV", l0 + 3); CHK_FAIL_END CHK_FAIL_START wmemcpy (wa.buf1 + 1, L"abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START wmemmove (wa.buf1 + 2, wa.buf1 + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START wp = wmempcpy (wa.buf1 + 6, L"abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START wmemset (wa.buf1 + 9, L'j', l0 + 2); CHK_FAIL_END #if __USE_FORTIFY_LEVEL >= 2 # define O 0 #else # define O 1 #endif CHK_FAIL_START wcscpy (wa.buf1 + (O + 4), wstr1 + 5); CHK_FAIL_END CHK_FAIL_START wp = wcpcpy (wa.buf1 + (O + 8), wstr2); CHK_FAIL_END CHK_FAIL_START wcsncpy (wa.buf1 + (O + 6), L"X", l0 + 4); CHK_FAIL_END wmemcpy (wa.buf1, wstr1 + (3 - O), l0 + 8 + O); CHK_FAIL_START wcscat (wa.buf1, L"AB"); CHK_FAIL_END wmemcpy (wa.buf1, wstr1 + (4 - O), l0 + 7 + O); CHK_FAIL_START wcsncat (wa.buf1, L"ZYXWV", l0 + 3); CHK_FAIL_END #endif /* Now checks for %n protection. */ /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ int n1, n2; if (sprintf (buf, "%s%n%s%n", str2, &n1, str2, &n2) != 2 || n1 != 1 || n2 != 2) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (snprintf (buf, 4, str3, str2, &n1, str2, &n2) != 2 || n1 != 1 || n2 != 2) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (sprintf (buf, buf2, str2, &n1, str2, &n1) != 2) FAIL (); CHK_FAIL2_END CHK_FAIL2_START if (snprintf (buf, 3, buf2, str2, &n1, str2, &n1) != 2) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (sprintf (buf, buf2 + 4, str2) != 1) FAIL (); /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ if (printf ("%s%n%s%n", str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (printf (str3, str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (printf (buf2, str4, &n1, str5, &n1) != 14) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (printf (buf2 + 4, str5) != 7) FAIL (); FILE *fp = stdout; /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ if (fprintf (fp, "%s%n%s%n", str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (fprintf (fp, str3, str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (fprintf (fp, buf2, str4, &n1, str5, &n1) != 14) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (fprintf (fp, buf2 + 4, str5) != 7) FAIL (); if (freopen (temp_filename, "r", stdin) == NULL) { puts ("could not open temporary file"); exit (1); } if (gets (buf) != buf || memcmp (buf, "abcdefgh", 9)) FAIL (); if (gets (buf) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (gets (buf) != buf) FAIL (); CHK_FAIL_END #endif rewind (stdin); if (fgets (buf, sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); if (fgets (buf, sizeof (buf), stdin) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); rewind (stdin); if (fgets (buf, l0 + sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (fgets (buf, sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (fgets (buf, l0 + sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END #endif rewind (stdin); if (fgets_unlocked (buf, sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); if (fgets_unlocked (buf, sizeof (buf), stdin) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); rewind (stdin); if (fgets_unlocked (buf, l0 + sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (fgets_unlocked (buf, sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (fgets_unlocked (buf, l0 + sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END #endif lseek (fileno (stdin), 0, SEEK_SET); if (read (fileno (stdin), buf, sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (read (fileno (stdin), buf, sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "ABCDEFGHI", 9)) FAIL (); lseek (fileno (stdin), 0, SEEK_SET); if (read (fileno (stdin), buf, l0 + sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (read (fileno (stdin), buf, sizeof (buf) + 1) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (pread (fileno (stdin), buf, sizeof (buf) - 1, sizeof (buf) - 2) != sizeof (buf) - 1 || memcmp (buf, "\nABCDEFGH", 9)) FAIL (); if (pread (fileno (stdin), buf, sizeof (buf) - 1, 0) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (pread (fileno (stdin), buf, l0 + sizeof (buf) - 1, sizeof (buf) - 3) != sizeof (buf) - 1 || memcmp (buf, "h\nABCDEFG", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (pread (fileno (stdin), buf, sizeof (buf) + 1, 2 * sizeof (buf)) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (pread64 (fileno (stdin), buf, sizeof (buf) - 1, sizeof (buf) - 2) != sizeof (buf) - 1 || memcmp (buf, "\nABCDEFGH", 9)) FAIL (); if (pread64 (fileno (stdin), buf, sizeof (buf) - 1, 0) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (pread64 (fileno (stdin), buf, l0 + sizeof (buf) - 1, sizeof (buf) - 3) != sizeof (buf) - 1 || memcmp (buf, "h\nABCDEFG", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (pread64 (fileno (stdin), buf, sizeof (buf) + 1, 2 * sizeof (buf)) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (freopen (temp_filename, "r", stdin) == NULL) { puts ("could not open temporary file"); exit (1); } if (fseek (stdin, 9 + 10 + 11, SEEK_SET)) { puts ("could not seek in test file"); exit (1); } #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (gets (buf) != buf) FAIL (); CHK_FAIL_END #endif /* Check whether missing N$ formats are detected. */ CHK_FAIL2_START printf ("%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START fprintf (stdout, "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START sprintf (buf, "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START snprintf (buf, sizeof (buf), "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END int sp[2]; if (socketpair (PF_UNIX, SOCK_STREAM, 0, sp)) FAIL (); else { const char *sendstr = "abcdefgh\nABCDEFGH\n0123456789\n"; if (send (sp[0], sendstr, strlen (sendstr), 0) != strlen (sendstr)) FAIL (); char recvbuf[12]; if (recv (sp[1], recvbuf, sizeof recvbuf, MSG_PEEK) != sizeof recvbuf || memcmp (recvbuf, sendstr, sizeof recvbuf) != 0) FAIL (); if (recv (sp[1], recvbuf + 6, l0 + sizeof recvbuf - 7, MSG_PEEK) != sizeof recvbuf - 7 || memcmp (recvbuf + 6, sendstr, sizeof recvbuf - 7) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (recv (sp[1], recvbuf + 1, sizeof recvbuf, MSG_PEEK) != sizeof recvbuf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (recv (sp[1], recvbuf + 4, l0 + sizeof recvbuf - 3, MSG_PEEK) != sizeof recvbuf - 3) FAIL (); CHK_FAIL_END #endif socklen_t sl; struct sockaddr_un sa_un; sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf, sizeof recvbuf, MSG_PEEK, &sa_un, &sl) != sizeof recvbuf || memcmp (recvbuf, sendstr, sizeof recvbuf) != 0) FAIL (); sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 6, l0 + sizeof recvbuf - 7, MSG_PEEK, &sa_un, &sl) != sizeof recvbuf - 7 || memcmp (recvbuf + 6, sendstr, sizeof recvbuf - 7) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 1, sizeof recvbuf, MSG_PEEK, &sa_un, &sl) != sizeof recvbuf) FAIL (); CHK_FAIL_END CHK_FAIL_START sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 4, l0 + sizeof recvbuf - 3, MSG_PEEK, &sa_un, &sl) != sizeof recvbuf - 3) FAIL (); CHK_FAIL_END #endif close (sp[0]); close (sp[1]); } char fname[] = "/tmp/tst-chk1-dir-XXXXXX\0foo"; char *enddir = strchr (fname, '\0'); if (mkdtemp (fname) == NULL) { printf ("mkdtemp failed: %m\n"); return 1; } *enddir = '/'; if (symlink ("bar", fname) != 0) FAIL (); char readlinkbuf[4]; if (readlink (fname, readlinkbuf, 4) != 3 || memcmp (readlinkbuf, "bar", 3) != 0) FAIL (); if (readlink (fname, readlinkbuf + 1, l0 + 3) != 3 || memcmp (readlinkbuf, "bbar", 4) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (readlink (fname, readlinkbuf + 2, l0 + 3) != 3) FAIL (); CHK_FAIL_END CHK_FAIL_START if (readlink (fname, readlinkbuf + 3, 4) != 3) FAIL (); CHK_FAIL_END #endif char *cwd1 = getcwd (NULL, 0); if (cwd1 == NULL) FAIL (); char *cwd2 = getcwd (NULL, 250); if (cwd2 == NULL) FAIL (); if (cwd1 && cwd2) { if (strcmp (cwd1, cwd2) != 0) FAIL (); *enddir = '\0'; if (chdir (fname)) FAIL (); char *cwd3 = getcwd (NULL, 0); if (cwd3 == NULL) FAIL (); if (strcmp (fname, cwd3) != 0) printf ("getcwd after chdir is '%s' != '%s'," "get{c,}wd tests skipped\n", cwd3, fname); else { char getcwdbuf[sizeof fname - 3]; char *cwd4 = getcwd (getcwdbuf, sizeof getcwdbuf); if (cwd4 != getcwdbuf || strcmp (getcwdbuf, fname) != 0) FAIL (); cwd4 = getcwd (getcwdbuf + 1, l0 + sizeof getcwdbuf - 1); if (cwd4 != getcwdbuf + 1 || getcwdbuf[0] != fname[0] || strcmp (getcwdbuf + 1, fname) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (getcwd (getcwdbuf + 2, l0 + sizeof getcwdbuf) != getcwdbuf + 2) FAIL (); CHK_FAIL_END CHK_FAIL_START if (getcwd (getcwdbuf + 2, sizeof getcwdbuf) != getcwdbuf + 2) FAIL (); CHK_FAIL_END #endif if (getwd (getcwdbuf) != getcwdbuf || strcmp (getcwdbuf, fname) != 0) FAIL (); if (getwd (getcwdbuf + 1) != getcwdbuf + 1 || strcmp (getcwdbuf + 1, fname) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (getwd (getcwdbuf + 2) != getcwdbuf + 2) FAIL (); CHK_FAIL_END #endif } if (chdir (cwd1) != 0) FAIL (); free (cwd3); } free (cwd1); free (cwd2); *enddir = '/'; if (unlink (fname) != 0) FAIL (); *enddir = '\0'; if (rmdir (fname) != 0) FAIL (); #if PATH_MAX > 0 char largebuf[PATH_MAX]; char *realres = realpath (".", largebuf); if (realres != largebuf) FAIL (); # if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char realbuf[1]; realres = realpath (".", realbuf); if (realres != realbuf) FAIL (); CHK_FAIL_END # endif #endif if (setlocale (LC_ALL, "de_DE.UTF-8") != NULL) { assert (MB_CUR_MAX <= 10); /* First a simple test. */ char enough[10]; if (wctomb (enough, L'A') != 1) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 /* We know the wchar_t encoding is ISO 10646. So pick a character which has a multibyte representation which does not fit. */ CHK_FAIL_START char smallbuf[2]; if (wctomb (smallbuf, L'\x100') != 2) FAIL (); CHK_FAIL_END #endif mbstate_t s; memset (&s, '\0', sizeof (s)); if (wcrtomb (enough, L'D', &s) != 1 || enough[0] != 'D') FAIL (); #if __USE_FORTIFY_LEVEL >= 1 /* We know the wchar_t encoding is ISO 10646. So pick a character which has a multibyte representation which does not fit. */ CHK_FAIL_START char smallbuf[2]; if (wcrtomb (smallbuf, L'\x100', &s) != 2) FAIL (); CHK_FAIL_END #endif wchar_t wenough[10]; memset (&s, '\0', sizeof (s)); const char *cp = "A"; if (mbsrtowcs (wenough, &cp, 10, &s) != 1 || wcscmp (wenough, L"A") != 0) FAIL (); cp = "BC"; if (mbsrtowcs (wenough, &cp, l0 + 10, &s) != 2 || wcscmp (wenough, L"BC") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbsrtowcs (wsmallbuf, &cp, 10, &s); CHK_FAIL_END #endif cp = "A"; if (mbstowcs (wenough, cp, 10) != 1 || wcscmp (wenough, L"A") != 0) FAIL (); cp = "DEF"; if (mbstowcs (wenough, cp, l0 + 10) != 3 || wcscmp (wenough, L"DEF") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbstowcs (wsmallbuf, cp, 10); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); cp = "ABC"; wcscpy (wenough, L"DEF"); if (mbsnrtowcs (wenough, &cp, 1, 10, &s) != 1 || wcscmp (wenough, L"AEF") != 0) FAIL (); cp = "IJ"; if (mbsnrtowcs (wenough, &cp, 1, l0 + 10, &s) != 1 || wcscmp (wenough, L"IEF") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbsnrtowcs (wsmallbuf, &cp, 3, 10, &s); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); const wchar_t *wcp = L"A"; if (wcsrtombs (enough, &wcp, 10, &s) != 1 || strcmp (enough, "A") != 0) FAIL (); wcp = L"BC"; if (wcsrtombs (enough, &wcp, l0 + 10, &s) != 2 || strcmp (enough, "BC") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcsrtombs (smallbuf, &wcp, 10, &s); CHK_FAIL_END #endif memset (enough, 'Z', sizeof (enough)); wcp = L"EF"; if (wcstombs (enough, wcp, 10) != 2 || strcmp (enough, "EF") != 0) FAIL (); wcp = L"G"; if (wcstombs (enough, wcp, l0 + 10) != 1 || strcmp (enough, "G") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcstombs (smallbuf, wcp, 10); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); wcp = L"AB"; if (wcsnrtombs (enough, &wcp, 1, 10, &s) != 1 || strcmp (enough, "A") != 0) FAIL (); wcp = L"BCD"; if (wcsnrtombs (enough, &wcp, 1, l0 + 10, &s) != 1 || strcmp (enough, "B") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcsnrtombs (smallbuf, &wcp, 3, 10, &s); CHK_FAIL_END #endif }
int main(int argc, char *argv[]) { wchar_t srcbuf[128]; char dstbuf[128]; /* * C/POSIX locale. */ printf("1..1\n"); /* Simple null terminated string. */ wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf)); wcscpy(srcbuf, L"hello"); memset(dstbuf, 0xcc, sizeof(dstbuf)); assert(wcstombs(dstbuf, srcbuf, sizeof(dstbuf)) == 5); assert(strcmp(dstbuf, "hello") == 0); assert((unsigned char)dstbuf[6] == 0xcc); /* Not enough space in destination buffer. */ wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf)); wcscpy(srcbuf, L"hello"); memset(dstbuf, 0xcc, sizeof(dstbuf)); assert(wcstombs(dstbuf, srcbuf, 4) == 4); assert(memcmp(dstbuf, "hell", 4) == 0); assert((unsigned char)dstbuf[5] == 0xcc); /* Null terminated string, internal dest. buffer */ wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf)); wcscpy(srcbuf, L"hello"); assert(wcstombs(NULL, srcbuf, sizeof(dstbuf)) == 5); /* Null terminated string, internal state. */ wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf)); wcscpy(srcbuf, L"hello"); memset(dstbuf, 0xcc, sizeof(dstbuf)); assert(wcstombs(dstbuf, srcbuf, sizeof(dstbuf)) == 5); assert(strcmp(dstbuf, "hello") == 0); assert((unsigned char)dstbuf[6] == 0xcc); /* Null terminated string, internal state, internal dest. buffer. */ wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf)); wcscpy(srcbuf, L"hello"); assert(wcstombs(NULL, srcbuf, 0) == 5); /* Empty source buffer. */ wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf)); srcbuf[0] = L'\0'; memset(dstbuf, 0xcc, sizeof(dstbuf)); assert(wcstombs(dstbuf, srcbuf, sizeof(dstbuf)) == 0); assert(dstbuf[0] == L'\0'); /* Zero length destination buffer. */ wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf)); wcscpy(srcbuf, L"hello"); memset(dstbuf, 0xcc, sizeof(dstbuf)); assert(wcstombs(dstbuf, srcbuf, 0) == 0); assert((unsigned char)dstbuf[0] == 0xcc); /* * Japanese (EUC) locale. */ assert(strcmp(setlocale(LC_CTYPE, "ja_JP.eucJP"), "ja_JP.eucJP") == 0); assert(MB_CUR_MAX > 1); wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf)); srcbuf[0] = 0xA3C1; srcbuf[1] = 0x0020; srcbuf[2] = 0x0042; srcbuf[3] = 0x0020; srcbuf[4] = 0xA3C3; srcbuf[5] = 0x0000; memset(dstbuf, 0xcc, sizeof(dstbuf)); assert(wcstombs(dstbuf, srcbuf, sizeof(dstbuf)) == 7); assert(strcmp(dstbuf, "\xA3\xC1 B \xA3\xC3") == 0); assert((unsigned char)dstbuf[8] == 0xcc); printf("ok 1 - wcstombs()\n"); return (0); }
/* * Our thread-safe and smart strerror() replacement. * * The 'err' argument passed in to this function MUST be a true errno number * as reported on this system. We do no range checking on the number before * we pass it to the "number-to-message" convertion function and there might * be systems that don't do proper range checking in there themselves. * * We don't do range checking (on systems other than Windows) since there is * no good reliable and portable way to do it. */ const char *Curl_strerror(struct connectdata *conn, int err) { char *buf, *p; size_t max; curlassert(conn); curlassert(err >= 0); buf = conn->syserr_buf; max = sizeof(conn->syserr_buf)-1; *buf = '\0'; #if defined(WIN32) && !defined(__CYGWIN__) #ifdef _WIN32_WCE buf[0]=0; { wchar_t wbuf[256]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, LANG_NEUTRAL, wbuf, sizeof(wbuf)/sizeof(wchar_t), NULL); wcstombs(buf,wbuf,max); } #else /* 'sys_nerr' is the maximum errno number, it is not widely portable */ if (err >= 0 && err < sys_nerr) strncpy(buf, strerror(err), max); else { if (!get_winsock_error(err, buf, max) && !FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, LANG_NEUTRAL, buf, (DWORD)max, NULL)) snprintf(buf, max, "Unknown error %d (%#x)", err, err); } #endif #else /* not native Windows coming up */ /* These should be atomic and hopefully thread-safe */ #ifdef HAVE_STRERROR_R /* There are two different APIs for strerror_r(). The POSIX and the GLIBC versions. */ #ifdef HAVE_POSIX_STRERROR_R strerror_r(err, buf, max); /* this may set errno to ERANGE if insufficient storage was supplied via 'strerrbuf' and 'buflen' to contain the generated message string, or EINVAL if the value of 'errnum' is not a valid error number.*/ #else { /* HAVE_GLIBC_STRERROR_R */ char buffer[256]; char *msg = strerror_r(err, buffer, sizeof(buffer)); /* this version of strerror_r() only *might* use the buffer we pass to the function, but it always returns the error message as a pointer, so we must copy that string unconditionally */ strncpy(buf, msg, max); } #endif /* end of HAVE_GLIBC_STRERROR_R */ #else /* HAVE_STRERROR_R */ strncpy(buf, strerror(err), max); #endif /* end of HAVE_STRERROR_R */ #endif /* end of ! Windows */ buf[max] = '\0'; /* make sure the string is zero terminated */ /* strip trailing '\r\n' or '\n'. */ if ((p = strrchr(buf,'\n')) != NULL && (p - buf) >= 2) *p = '\0'; if ((p = strrchr(buf,'\r')) != NULL && (p - buf) >= 1) *p = '\0'; return buf; }
self->capacity = newCapacity; stringSelf->text = newText; return 0; } inline static int __ensureCapacity(struct WMutableString *const self, UInteger minCapacity) { if ( minCapacity > self->capacity ) return __grow(self, minCapacity); return 0; } inline static char *__wideToCharConverter(const wchar_t *restrict wideContent) { if ( wideContent == NULL ) return errno = EINVAL, (char *)NULL; size_t charContentSize = wcstombs(NULL, wideContent, 0); if ( charContentSize == (size_t)-1 ) return errno = 0, NULL; char *restrict charContent = calloc(charContentSize+1, sizeof(char)); if ( charContent == NULL ) return errno = ENOMEM, (char *)NULL; charContentSize = wcstombs(charContent, wideContent, charContentSize); if ( charContentSize == (size_t)-1 ) return free(charContent), errno = 0, (char *)NULL; return charContent; } inline static wchar_t *__charToWideConverter(const char *restrict charContent) { if ( charContent == NULL ) return errno = EINVAL, (wchar_t *)NULL; size_t wideContentSize = mbstowcs(NULL, charContent, 0);
BOOLEAN NTAPI PasswordFilter( PUNICODE_STRING UserName, PUNICODE_STRING FullName, PUNICODE_STRING Password, BOOLEAN SetOperation ) /*++ Routine Description: This (optional) routine is notified of a password change. Arguments: UserName - Name of user whose password changed FullName - Full name of the user whose password changed NewPassword - Cleartext new password for the user SetOperation - TRUE if the password was SET rather than CHANGED Return Value: TRUE if the specified Password is suitable (complex, long, etc). The system will continue to evaluate the password update request through any other installed password change packages. FALSE if the specified Password is unsuitable. The password change on the specified account will fail. --*/ { BOOLEAN bComplex = FALSE; // assume the password in not complex enough DWORD cchPassword; DWORD i; DWORD j; DWORD count; DWORD dwNum = 0; DWORD dwUpper = 0; DWORD dwLower = 0; DWORD dwSpecialChar = 0 ; PCHAR token ; CHAR _password[PWLEN+1]; CHAR _username[UNLEN+1]; PCHAR _fullname = NULL; WORD CharType[PWLEN+1]; PCHAR TempString; // // If the password was explicitly set, allow it through. // if (SetOperation) { bComplex = TRUE; goto end; } // // Make sure the password and username will fit in our local buffers // if (Password->Length > PWLEN * sizeof(WCHAR)) { goto end; } if (UserName->Length > UNLEN * sizeof(WCHAR)) { goto end; } _fullname = HeapAlloc(GetProcessHeap(), 0, FullName->Length + sizeof(WCHAR)); if (_fullname == NULL) { goto end; } // // check if the password is complex enough for our liking by // checking that at least two of the four character types are // present. // cchPassword = Password->Length / sizeof(WCHAR); if(GetStringTypeW( CT_CTYPE1, Password->Buffer, cchPassword, CharType )) { for(i = 0 ; i < cchPassword ; i++) { // // keep track of what type of characters we have encountered // if(CharType[i] & C1_DIGIT) { dwNum = 1; continue; } if(CharType[i] & C1_UPPER) { dwUpper = 1; continue; } if(CharType[i] & C1_LOWER) { dwLower = 1; continue; } } // for // // Indicate whether we encountered enough password complexity // if( (dwNum + dwLower + dwUpper) < 2) { bComplex = FALSE ; goto end ; } else { // // now we resort to more complex checking // wcstombs(_password, Password->Buffer, PWLEN+1) ; wcstombs(_username, UserName->Buffer, UNLEN+1) ; wcstombs(_fullname, FullName->Buffer, 1+FullName->Length/sizeof(WCHAR)) ; _strupr(_password) ; _password[Password->Length/sizeof(WCHAR)] = '\0' ; _strupr(_username) ; _username[UserName->Length/sizeof(WCHAR)] = '\0' ; _strupr(_fullname) ; _fullname[FullName->Length/sizeof(WCHAR)] = '\0' ; if (strpbrk (_password, "(`~!@#$%^&*_-+=|\\{}[]:;\"'<>,.?)") != NULL) { dwSpecialChar = 1 ; } if ((dwNum + dwLower + dwUpper + dwSpecialChar) < 3) { bComplex = FALSE ; goto end ; } if ((UserName->Length >= 3 * sizeof(WCHAR)) && strstr (_password, _username)) { bComplex = FALSE ; goto end ; } // // Tokenize the full name and check if the password is derived from it // token = LocalStrTok(_fullname, " ,.\t-_#",&TempString); while( token != NULL ) { if (lstrlenA(token) > 3 && strstr(_password, token)) { bComplex = FALSE ; goto end ; } token = LocalStrTok(NULL, " ,.\t-_#",&TempString); } bComplex = TRUE ; } } // if end: ZeroMemory( CharType, Password->Length ); ZeroMemory( _password, Password->Length ); HeapFree(GetProcessHeap(), 0, _fullname); return bComplex; }
void WCharToChar( const wchar_t* pwstrSrc, char pstrDest[] ) { int nLen = ( int )wcslen( pwstrSrc ); wcstombs( pstrDest, pwstrSrc, nLen + 1 ); }
ITypeLib* tCOMUtil::LoadTypeLibFromCLSID(CLSID clsid, unsigned short major_version) { wchar_t* wcClsid = NULL; HRESULT hr = StringFromCLSID(clsid, &wcClsid); if (FAILED(hr)) return NULL; /* converte CLSID para string normal */ char* pcClsid = (char*) malloc( (wcslen(wcClsid) + 1) * sizeof(char)); wcstombs(pcClsid, wcClsid,wcslen(wcClsid)+1); CoTaskMemFree(wcClsid); DWORD size = 38*3; /*{F37C8063-4AD5-101B-B826-00DD01103DE1}*/ BYTE *bLibID = (BYTE *) malloc(size); BYTE bVersion[100]; // This must hold something like "5.2" HKEY iid_key, obj_key, typelib_key, version_key; /* extrai do registry type library (GUID e versao) */ LONG res = 0; bool version_info_found = true; try { res = RegOpenKeyEx(HKEY_CLASSES_ROOT,"CLSID", 0, KEY_READ, &iid_key); WINCHECK(res == ERROR_SUCCESS); res = RegOpenKeyEx(iid_key, pcClsid, 0, KEY_READ, &obj_key); RegCloseKey(iid_key); free(pcClsid); pcClsid = NULL; WINCHECK(res == ERROR_SUCCESS); res = RegOpenKeyEx(obj_key, "TypeLib",0, KEY_READ, &typelib_key); if(res != ERROR_SUCCESS) { RegCloseKey(obj_key); LUACOM_EXCEPTION(WINDOWS_ERROR); } res = RegOpenKeyEx(obj_key, "version",0, KEY_READ, &version_key); RegCloseKey(obj_key); if(res != ERROR_SUCCESS) version_info_found = false; RegQueryValueEx(typelib_key, NULL, NULL, NULL, bLibID, &size); RegCloseKey(typelib_key); RegQueryValueEx(version_key, NULL, NULL, NULL, bVersion, &size); RegCloseKey(version_key); } catch(class tLuaCOMException& e) { UNUSED(e); if(pcClsid) free(pcClsid); return NULL; } // converts libID to multibyte string wchar_t* wcTypelib= (wchar_t*) malloc( (strlen((char *) bLibID) + 1) * sizeof(wchar_t)); mbstowcs(wcTypelib, (char *) bLibID, strlen((char *) bLibID)+1); // extracts version information int version_major = 0, version_minor = 0; int found = 0; if(version_info_found) { found = sscanf( (const char *) bVersion, "%d.%d", &version_major, &version_minor); } if(major_version > 0 && ( (!version_info_found) || (version_info_found && found == 0) ) ) { version_major = major_version; version_minor = 0; } else if(!version_info_found) { // tries to load the first type library found in // the registry bool result = tCOMUtil::GetDefaultTypeLibVersion( (const char*) bLibID, &version_major, &version_minor); if(!result) return NULL; } free(bLibID); GUID libid = IID_NULL; CLSIDFromString(wcTypelib, &libid); free(wcTypelib); ITypeLib* typelib = NULL; hr = LoadRegTypeLib(libid, version_major, version_minor, 0, &typelib); if(FAILED(hr)) return NULL; return typelib; }
ILboolean ILAPIENTRY ilLoad(ILenum Type, const ILstring FileName) { #ifndef _UNICODE if (FileName == NULL || strlen(FileName) < 1) { #else char AnsiName[512]; if (FileName == NULL || wcslen(FileName) < 1) { #endif//_UNICODE ilSetError(IL_INVALID_PARAM); return IL_FALSE; } switch (Type) { case IL_TYPE_UNKNOWN: return ilLoadImage(FileName); #ifndef IL_NO_TGA case IL_TGA: return ilLoadTarga(FileName); #endif #ifndef IL_NO_JPG case IL_JPG: return ilLoadJpeg(FileName); #endif #ifndef IL_NO_DDS case IL_DDS: return ilLoadDds(FileName); #endif #ifndef IL_NO_PNG case IL_PNG: return ilLoadPng(FileName); #endif #ifndef IL_NO_BMP case IL_BMP: return ilLoadBmp(FileName); #endif #ifndef IL_NO_GIF case IL_GIF: return ilLoadGif(FileName); #endif #ifndef IL_NO_HDR case IL_HDR: return ilLoadHdr(FileName); #endif #ifndef IL_NO_CUT case IL_CUT: return ilLoadCut(FileName); #endif #ifndef IL_NO_DOOM case IL_DOOM: return ilLoadDoom(FileName); case IL_DOOM_FLAT: return ilLoadDoomFlat(FileName); #endif #ifndef IL_NO_ICO case IL_ICO: return ilLoadIcon(FileName); #endif #ifndef IL_NO_LIF case IL_LIF: return ilLoadLif(FileName); #endif #ifndef IL_NO_MDL case IL_MDL: return ilLoadMdl(FileName); #endif #ifndef IL_NO_MNG case IL_MNG: return ilLoadMng(FileName); #endif #ifndef IL_NO_PCD case IL_PCD: return IL_FALSE;//ilLoadPcd(FileName); #endif #ifndef IL_NO_PCX case IL_PCX: return ilLoadPcx(FileName); #endif #ifndef IL_NO_PIC case IL_PIC: return ilLoadPic(FileName); #endif #ifndef IL_NO_PIX case IL_PIX: return ilLoadPix(FileName); #endif #ifndef IL_NO_PNM case IL_PNM: return ilLoadPnm(FileName); #endif #ifndef IL_NO_PSD case IL_PSD: return ilLoadPsd(FileName); #endif #ifndef IL_NO_PSP case IL_PSP: return ilLoadPsp(FileName); #endif #ifndef IL_NO_PXR case IL_PXR: return ilLoadPxr(FileName); #endif #ifndef IL_NO_RAW case IL_RAW: return ilLoadRaw(FileName); #endif #ifndef IL_NO_SGI case IL_SGI: return ilLoadSgi(FileName); #endif #ifndef IL_NO_TIF case IL_TIF: #ifndef _UNICODE return ilLoadTiff(FileName); #else wcstombs(AnsiName, FileName, 512); //WideCharToMultiByte(CP_ACP, 0, FileName, -1, AnsiName, 512, NULL, NULL); return ilLoadTiff(AnsiName); #endif//_UNICODE #endif #ifndef IL_NO_WAL case IL_WAL: return ilLoadWal(FileName); #endif #ifndef IL_NO_XPM case IL_XPM: return ilLoadXpm(FileName); #endif } ilSetError(IL_INVALID_ENUM); return IL_FALSE; } ILboolean ILAPIENTRY ilLoadF(ILenum Type, ILHANDLE File) { if (File == NULL) { ilSetError(IL_INVALID_PARAM); return IL_FALSE; } if (Type == IL_TYPE_UNKNOWN) Type = ilDetermineTypeF(File); switch (Type) { case IL_TYPE_UNKNOWN: return IL_FALSE; #ifndef IL_NO_TGA case IL_TGA: return ilLoadTargaF(File); #endif #ifndef IL_NO_JPG #ifndef IL_USE_IJL case IL_JPG: return ilLoadJpegF(File); #endif #endif #ifndef IL_NO_DDS case IL_DDS: return ilLoadDdsF(File); #endif #ifndef IL_NO_PNG case IL_PNG: return ilLoadPngF(File); #endif #ifndef IL_NO_BMP case IL_BMP: return ilLoadBmpF(File); #endif #ifndef IL_NO_GIF case IL_GIF: return ilLoadGifF(File); #endif #ifndef IL_NO_HDR case IL_HDR: return ilLoadHdrF(File); #endif #ifndef IL_NO_CUT case IL_CUT: return ilLoadCutF(File); #endif #ifndef IL_NO_DOOM case IL_DOOM: return ilLoadDoomF(File); case IL_DOOM_FLAT: return ilLoadDoomFlatF(File); #endif #ifndef IL_NO_ICO case IL_ICO: return ilLoadIconF(File); #endif #ifndef IL_NO_LIF case IL_LIF: return ilLoadLifF(File); #endif #ifndef IL_NO_MDL case IL_MDL: return ilLoadMdlF(File); #endif #ifndef IL_NO_MNG case IL_MNG: return ilLoadMngF(File); #endif #ifndef IL_NO_PCD case IL_PCD: return IL_FALSE;//return ilLoadPcdF(File); #endif #ifndef IL_NO_PCX case IL_PCX: return ilLoadPcxF(File); #endif #ifndef IL_NO_PIC case IL_PIC: return ilLoadPicF(File); #endif #ifndef IL_NO_PIX case IL_PIX: return ilLoadPixF(File); #endif #ifndef IL_NO_PNM case IL_PNM: return ilLoadPnmF(File); #endif #ifndef IL_NO_PSD case IL_PSD: return ilLoadPsdF(File); #endif #ifndef IL_NO_PSP case IL_PSP: return ilLoadPspF(File); #endif #ifndef IL_NO_PXR case IL_PXR: return ilLoadPxrF(File); #endif #ifndef IL_NO_RAW case IL_RAW: return ilLoadRawF(File); #endif #ifndef IL_NO_SGI case IL_SGI: return ilLoadSgiF(File); #endif #ifndef IL_NO_TIF case IL_TIF: return ilLoadTiffF(File); #endif #ifndef IL_NO_WAL case IL_WAL: return ilLoadWalF(File); #endif #ifndef IL_NO_XPM case IL_XPM: return ilLoadXpmF(File); #endif } ilSetError(IL_INVALID_ENUM); return IL_FALSE; } ILboolean ILAPIENTRY ilLoadL(ILenum Type, const ILvoid *Lump, ILuint Size) { if (Lump == NULL || Size == 0) { ilSetError(IL_INVALID_PARAM); return IL_FALSE; } if (Type == IL_TYPE_UNKNOWN) Type = ilDetermineTypeL(Lump, Size); switch (Type) { case IL_TYPE_UNKNOWN: return IL_FALSE; #ifndef IL_NO_TGA case IL_TGA: return ilLoadTargaL(Lump, Size); #endif #ifndef IL_NO_JPG case IL_JPG: return ilLoadJpegL(Lump, Size); #endif #ifndef IL_NO_DDS case IL_DDS: return ilLoadDdsL(Lump, Size); #endif #ifndef IL_NO_PNG case IL_PNG: return ilLoadPngL(Lump, Size); #endif #ifndef IL_NO_BMP case IL_BMP: return ilLoadBmpL(Lump, Size); #endif #ifndef IL_NO_GIF case IL_GIF: return ilLoadGifL(Lump, Size); #endif #ifndef IL_NO_HDR case IL_HDR: return ilLoadHdrL(Lump, Size); #endif #ifndef IL_NO_CUT case IL_CUT: return ilLoadCutL(Lump, Size); #endif #ifndef IL_NO_DOOM case IL_DOOM: return ilLoadDoomL(Lump, Size); case IL_DOOM_FLAT: return ilLoadDoomFlatL(Lump, Size); #endif #ifndef IL_NO_ICO case IL_ICO: return ilLoadIconL(Lump, Size); #endif #ifndef IL_NO_LIF case IL_LIF: return ilLoadLifL(Lump, Size); #endif #ifndef IL_NO_MDL case IL_MDL: return ilLoadMdlL(Lump, Size); #endif #ifndef IL_NO_MNG case IL_MNG: return ilLoadMngL(Lump, Size); #endif #ifndef IL_NO_PCD case IL_PCD: return IL_FALSE;//return ilLoadPcdL(Lump, Size); #endif #ifndef IL_NO_PCX case IL_PCX: return ilLoadPcxL(Lump, Size); #endif #ifndef IL_NO_PIC case IL_PIC: return ilLoadPicL(Lump, Size); #endif #ifndef IL_NO_PIX case IL_PIX: return ilLoadPixL(Lump, Size); #endif #ifndef IL_NO_PNM case IL_PNM: return ilLoadPnmL(Lump, Size); #endif #ifndef IL_NO_PSD case IL_PSD: return ilLoadPsdL(Lump, Size); #endif #ifndef IL_NO_PSP case IL_PSP: return ilLoadPspL(Lump, Size); #endif #ifndef IL_NO_PXR case IL_PXR: return ilLoadPxrL(Lump, Size); #endif #ifndef IL_NO_RAW case IL_RAW: return ilLoadRawL(Lump, Size); #endif #ifndef IL_NO_SGI case IL_SGI: return ilLoadSgiL(Lump, Size); #endif #ifndef IL_NO_TIF case IL_TIF: return ilLoadTiffL(Lump, Size); #endif #ifndef IL_NO_WAL case IL_WAL: return ilLoadWalL(Lump, Size); #endif #ifndef IL_NO_XPM case IL_XPM: return ilLoadXpmL(Lump, Size); #endif } ilSetError(IL_INVALID_ENUM); return IL_FALSE; } //! Attempts to load an image with various different methods before failing - very generic. ILboolean ILAPIENTRY ilLoadImage(const ILstring FileName) { ILstring Ext = iGetExtension(FileName); ILenum Type; if (iCurImage == NULL) { ilSetError(IL_ILLEGAL_OPERATION); return IL_FALSE; } #ifndef _UNICODE if (FileName == NULL || strlen(FileName) < 1) { #else if (FileName == NULL || wcslen(FileName) < 1) { #endif//_UNICODE ilSetError(IL_INVALID_PARAM); return IL_FALSE; } // Try registered procedures first (so users can override default lib functions). if (Ext) { if (iRegisterLoad(FileName)) return IL_TRUE; #ifndef IL_NO_TGA if (!iStrCmp(Ext, IL_TEXT("tga")) || !iStrCmp(Ext, IL_TEXT("vda")) || !iStrCmp(Ext, IL_TEXT("icb")) || !iStrCmp(Ext, IL_TEXT("vst"))) { return ilLoadTarga(FileName); } #endif #ifndef IL_NO_JPG if (!iStrCmp(Ext, IL_TEXT("jpg")) || !iStrCmp(Ext, IL_TEXT("jpe")) || !iStrCmp(Ext, IL_TEXT("jpeg"))) { return ilLoadJpeg(FileName); } #endif #ifndef IL_NO_DDS if (!iStrCmp(Ext, IL_TEXT("dds"))) { return ilLoadDds(FileName); } #endif #ifndef IL_NO_PNG if (!iStrCmp(Ext, IL_TEXT("png"))) { return ilLoadPng(FileName); } #endif #ifndef IL_NO_BMP if (!iStrCmp(Ext, IL_TEXT("bmp")) || !iStrCmp(Ext, IL_TEXT("dib"))) { return ilLoadBmp(FileName); } #endif #ifndef IL_NO_GIF if (!iStrCmp(Ext, IL_TEXT("gif"))) { return ilLoadGif(FileName); } #endif #ifndef IL_NO_HDR if (!iStrCmp(Ext, IL_TEXT("hdr"))) { return ilLoadHdr(FileName); } #endif #ifndef IL_NO_CUT if (!iStrCmp(Ext, IL_TEXT("cut"))) { return ilLoadCut(FileName); } #endif #ifndef IL_NO_DCX if (!iStrCmp(Ext, IL_TEXT("dcx"))) { return ilLoadDcx(FileName); } #endif #ifndef IL_NO_ICO if (!iStrCmp(Ext, IL_TEXT("ico")) || !iStrCmp(Ext, IL_TEXT("cur"))) { return ilLoadIcon(FileName); } #endif #ifndef IL_NO_LIF if (!iStrCmp(Ext, IL_TEXT("lif"))) { return ilLoadLif(FileName); } #endif #ifndef IL_NO_MDL if (!iStrCmp(Ext, IL_TEXT("mdl"))) { return ilLoadMdl(FileName); } #endif #ifndef IL_NO_MNG if (!iStrCmp(Ext, IL_TEXT("mng")) || !iStrCmp(Ext, IL_TEXT("jng"))) { return ilLoadMng(FileName); } #endif #ifndef IL_NO_PCD if (!iStrCmp(Ext, IL_TEXT("pcd"))) { return IL_FALSE;//return ilLoadPcd(FileName); } #endif #ifndef IL_NO_PCX if (!iStrCmp(Ext, IL_TEXT("pcx"))) { return ilLoadPcx(FileName); } #endif #ifndef IL_NO_PIC if (!iStrCmp(Ext, IL_TEXT("pic"))) { return ilLoadPic(FileName); } #endif #ifndef IL_NO_PIX if (!iStrCmp(Ext, IL_TEXT("pix"))) { return ilLoadPix(FileName); } #endif #ifndef IL_NO_PNM if (!iStrCmp(Ext, IL_TEXT("pbm"))) { return ilLoadPnm(FileName); } if (!iStrCmp(Ext, IL_TEXT("pgm"))) { return ilLoadPnm(FileName); } if (!iStrCmp(Ext, IL_TEXT("pnm"))) { return ilLoadPnm(FileName); } if (!iStrCmp(Ext, IL_TEXT("ppm"))) { return ilLoadPnm(FileName); } #endif #ifndef IL_NO_PSD if (!iStrCmp(Ext, IL_TEXT("psd")) || !iStrCmp(Ext, IL_TEXT("pdd"))) { return ilLoadPsd(FileName); } #endif #ifndef IL_NO_PSP if (!iStrCmp(Ext, IL_TEXT("psp"))) { return ilLoadPsp(FileName); } #endif #ifndef IL_NO_PXR if (!iStrCmp(Ext, IL_TEXT("pxr"))) { return ilLoadPxr(FileName); } #endif #ifndef IL_NO_SGI if (!iStrCmp(Ext, IL_TEXT("sgi")) || !iStrCmp(Ext, IL_TEXT("bw")) || !iStrCmp(Ext, IL_TEXT("rgb")) || !iStrCmp(Ext, IL_TEXT("rgba"))) { return ilLoadSgi(FileName); } #endif #ifndef IL_NO_TIF if (!iStrCmp(Ext, IL_TEXT("tif")) || !iStrCmp(Ext, IL_TEXT("tiff"))) { return ilLoadTiff(FileName); } #endif #ifndef IL_NO_WAL if (!iStrCmp(Ext, IL_TEXT("wal"))) { return ilLoadWal(FileName); } #endif #ifndef IL_NO_XPM if (!iStrCmp(Ext, IL_TEXT("xpm"))) { return ilLoadXpm(FileName); } #endif } // As a last-ditch effort, try to identify the image Type = ilDetermineType(FileName); if (Type == IL_TYPE_UNKNOWN) return IL_FALSE; return ilLoad(Type, FileName); } ILboolean ILAPIENTRY ilSave(ILenum Type, ILstring FileName) { switch (Type) { case IL_TYPE_UNKNOWN: return ilSaveImage(FileName); #ifndef IL_NO_BMP case IL_BMP: return ilSaveBmp(FileName); #endif #ifndef IL_NO_CHEAD case IL_CHEAD: return ilSaveCHeader(FileName, "IL_IMAGE"); #endif #ifndef IL_NO_JPG case IL_JPG: return ilSaveJpeg(FileName); #endif #ifndef IL_NO_PCX case IL_PCX: return ilSavePcx(FileName); #endif #ifndef IL_NO_PNG case IL_PNG: return ilSavePng(FileName); #endif #ifndef IL_NO_PNM case IL_PNM: return ilSavePnm(FileName); #endif #ifndef IL_NO_PSD case IL_PSD: return ilSavePsd(FileName); #endif #ifndef IL_NO_RAW case IL_RAW: return ilSaveRaw(FileName); #endif #ifndef IL_NO_SGI case IL_SGI: return ilSaveSgi(FileName); #endif #ifndef IL_NO_TGA case IL_TGA: return ilSaveTarga(FileName); #endif #ifndef IL_NO_TIF case IL_TIF: return ilSaveTiff(FileName); #endif case IL_JASC_PAL: return ilSaveJascPal(FileName); } ilSetError(IL_INVALID_ENUM); return IL_FALSE; } ILuint ILAPIENTRY ilSaveF(ILenum Type, ILHANDLE File) { ILboolean Ret; if (File == NULL) { ilSetError(IL_INVALID_PARAM); return 0; } switch (Type) { #ifndef IL_NO_BMP case IL_BMP: Ret = ilSaveBmpF(File); break; #endif #ifndef IL_NO_JPG #ifndef IL_USE_IJL case IL_JPG: Ret = ilSaveJpegF(File); break; #endif #endif #ifndef IL_NO_PNM case IL_PNM: Ret = ilSavePnmF(File); break; #endif #ifndef IL_NO_PNG case IL_PNG: Ret = ilSavePngF(File); break; #endif #ifndef IL_NO_PSD case IL_PSD: Ret = ilSavePsdF(File); break; #endif #ifndef IL_NO_RAW case IL_RAW: Ret = ilSaveRawF(File); break; #endif #ifndef IL_NO_SGI case IL_SGI: Ret = ilSaveSgiF(File); break; #endif #ifndef IL_NO_TGA case IL_TGA: Ret = ilSaveTargaF(File); break; #endif /*#ifndef IL_NO_TIF case IL_TIF: Ret = ilSaveTiffF(File); break; #endif*/ default: ilSetError(IL_INVALID_ENUM); return 0; } if (Ret == IL_FALSE) return 0; return itell(); }
void OpenPort(String portname) { // String portname //имя порта (например, "COM1", "COM2" и т.д.) DCB dcb; //структура для общей инициализации порта DCB COMMTIMEOUTS timeouts; //структура для установки таймаутов // portname = ; //получить имя выбранного порта //открыть порт, для асинхронных операций обязательно нужно указать флаг FILE_FLAG_OVERLAPPED char* port; port = new char[15]; wcstombs(port, portname.c_str(), 15); COMport = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); //здесь: // - port - имя порта в качестве имени файла, // - GENERIC_READ | GENERIC_WRITE - доступ к порту на чтение/записть // - 0 - порт не может быть общедоступным (shared) // - NULL - дескриптор порта не наследуется, используется дескриптор безопасности по умолчанию // - OPEN_EXISTING - порт должен открываться как уже существующий файл // - FILE_FLAG_OVERLAPPED - этот флаг указывает на использование асинхронных операций // - NULL - указатель на файл шаблона не используется при работе с портами if(COMport == INVALID_HANDLE_VALUE) //если ошибка открытия порта { // Form1->Info->Lines->Add(GetLastError()); return; } //инициализация порта dcb.DCBlength = sizeof(DCB); //в первое поле структуры DCB необходимо занести её длину, //она будет использоваться функциями настройки порта //для контроля корректности структуры //считать структуру DCB из порта if(!GetCommState(COMport, &dcb)) { //если не удалось - закрыть порт и вывести сообщение об ошибке в строке состояния ClosePort(); ShowMessage("Ошибка соединения: не удалось считать DCB!"); return; } //инициализация структуры DCB dcb.BaudRate = 9600; //задаём скорость передачи dcb.fBinary = TRUE; //включаем двоичный режим обмена dcb.fOutxCtsFlow = FALSE; //выключаем режим слежения за сигналом CTS dcb.fOutxDsrFlow = FALSE; //выключаем режим слежения за сигналом DSR dcb.fDtrControl = DTR_CONTROL_DISABLE; //отключаем использование линии DTR dcb.fDsrSensitivity = FALSE; //отключаем восприимчивость драйвера к состоянию линии DSR dcb.fNull = FALSE; //разрешить приём нулевых байтов dcb.fRtsControl = RTS_CONTROL_DISABLE; //отключаем использование линии RTS dcb.fAbortOnError = FALSE; //отключаем остановку всех операций чтения/записи при ошибке dcb.ByteSize = 8; //задаём 8 бит в байте dcb.Parity = 0; //отключаем проверку чётности dcb.StopBits = 0; //задаём один стоп-бит //загрузить структуру DCB в порт if(!SetCommState(COMport, &dcb)) { //если не удалось - закрыть порт и вывести сообщение об ошибке в строке состояния ClosePort(); ShowMessage("Ошибка соединения: не удалось установить DCB!"); return; } //установить таймауты timeouts.ReadIntervalTimeout = 1; //таймаут между двумя символами timeouts.ReadTotalTimeoutMultiplier = 1; //общий таймаут операции чтения timeouts.ReadTotalTimeoutConstant = 1; //константа для общего таймаута операции чтения timeouts.WriteTotalTimeoutMultiplier = 1; //общий таймаут операции записи timeouts.WriteTotalTimeoutConstant = 1; //константа для общего таймаута операции записи //записать структуру таймаутов в порт //если не удалось - закрыть порт и вывести сообщение об ошибке в строке состояния if(!SetCommTimeouts(COMport, &timeouts)) { ClosePort(); ShowMessage("Ошибка соединения: не удалось установить тайм-ауты!"); return; } //установить размеры очередей приёма и передачи SetupComm(COMport,2000,2000); //создать или открыть существующий файл для записи принимаемых данных handle = open("test.txt", O_CREAT | O_APPEND | O_BINARY | O_WRONLY, S_IREAD | S_IWRITE); if(handle==-1) //если произошла ошибка открытия файла { //вывести сообщение об этом в командной строке Form1->Info->Lines->Add("Ошибка открытия файла"); } //иначе вывести в строке состояния сообщение об успешном открытии файла else { // Form1->Info->Lines->Add("КСЭ-01В ПОДКЛЮЧЕН"); } PurgeComm(COMport, PURGE_RXCLEAR); //очистить принимающий буфер порта // EscapeCommFunction(COMport, SETDTR); // EscapeCommFunction(COMport, SETRTS); reader = CreateThread(NULL, 0, ReceiveFromDeviceThread, NULL, 0, NULL); //создать и запустить поток чтения байтов writer = CreateThread(NULL, 0, SendToDeviceThread, NULL, CREATE_SUSPENDED, NULL); //создаём поток записи в остановленном состоянии (предпоследний параметр = CREATE_SUSPENDED) }
NTSTATUS NTAPI LsaApLogonUserEx (PLSA_CLIENT_REQUEST request, SECURITY_LOGON_TYPE logon_type, PVOID auth, PVOID client_auth_base, ULONG auth_len, PVOID *pbuf, PULONG pbuf_len, PLUID logon_id, PNTSTATUS sub_stat, PLSA_TOKEN_INFORMATION_TYPE tok_type, PVOID *tok, PUNICODE_STRING *account, PUNICODE_STRING *authority, PUNICODE_STRING *machine) { DWORD checksum, i; PDWORD csp, csp_end; NTSTATUS stat; SECPKG_CLIENT_INFO clinf; PLSA_TOKEN_INFORMATION_V2 tokinf; cyglsa_t *authinf = (cyglsa_t *) auth; /* Check if the caller has the SeTcbPrivilege, otherwise refuse service. */ stat = funcs->GetClientInfo (&clinf); if (stat != STATUS_SUCCESS) { cyglsa_printf ("GetClientInfo failed: 0x%08lx\n", stat); return stat; } if (!clinf.HasTcbPrivilege) { cyglsa_printf ("Client has no TCB privilege. Access denied.\n"); return STATUS_ACCESS_DENIED; } /* Make a couple of validity checks. */ if (auth_len < sizeof *authinf || authinf->magic != CYG_LSA_MAGIC || !authinf->username[0] || !authinf->domain[0]) { cyglsa_printf ("Invalid authentication parameter.\n"); return STATUS_INVALID_PARAMETER; } checksum = CYG_LSA_MAGIC; csp = (PDWORD) &authinf->username; csp_end = (PDWORD) ((PBYTE) authinf + auth_len); while (csp < csp_end) checksum += *csp++; if (authinf->checksum != checksum) { cyglsa_printf ("Invalid checksum.\n"); return STATUS_INVALID_PARAMETER_3; } /* Set account to username and authority to domain resp. machine name. The name of the logon account name as returned by LookupAccountSid is created from here as "authority\account". */ authinf->username[UNLEN] = '\0'; authinf->domain[MAX_DOMAIN_NAME_LEN] = '\0'; if (account && !(*account = uni_alloc (authinf->username, wcslen (authinf->username)))) { cyglsa_printf ("No memory trying to create account.\n"); return STATUS_NO_MEMORY; } if (authority && !(*authority = uni_alloc (authinf->domain, wcslen (authinf->domain)))) { cyglsa_printf ("No memory trying to create authority.\n"); return STATUS_NO_MEMORY; } if (machine) { WCHAR mach[MAX_COMPUTERNAME_LENGTH + 1]; DWORD msize = MAX_COMPUTERNAME_LENGTH + 1; if (!GetComputerNameW (mach, &msize)) wcscpy (mach, L"UNKNOWN"); if (!(*machine = uni_alloc (mach, wcslen (mach)))) { cyglsa_printf ("No memory trying to create machine.\n"); return STATUS_NO_MEMORY; } } /* Create a fake buffer in pbuf which is free'd again in the client. Windows 2000 tends to crash when setting this pointer to NULL. */ if (pbuf) { #ifdef JUST_ANOTHER_NONWORKING_SOLUTION cygprf_t prf; WCHAR sam_username[MAX_DOMAIN_NAME_LEN + UNLEN + 2]; SECURITY_STRING sam_user, prefix; PUCHAR user_auth; ULONG user_auth_size; WCHAR flatname[UNLEN + 1]; UNICODE_STRING flatnm; TOKEN_SOURCE ts; HANDLE token; #endif /* JUST_ANOTHER_NONWORKING_SOLUTION */ stat = funcs->AllocateClientBuffer (request, 64UL, pbuf); if (!LSA_SUCCESS (stat)) { cyglsa_printf ("AllocateClientBuffer failed: 0x%08lx\n", stat); return stat; } #ifdef JUST_ANOTHER_NONWORKING_SOLUTION prf.magic_pre = MAGIC_PRE; prf.token = NULL; prf.magic_post = MAGIC_POST; #if 0 /* That's how it was supposed to work according to MSDN... */ wcscpy (sam_username, authinf->domain); wcscat (sam_username, L"\\"); wcscat (sam_username, authinf->username); #else /* That's the only solution which worked, and then it only worked for machine local accounts. No domain authentication possible. STATUS_NO_SUCH_USER galore! */ wcscpy (sam_username, authinf->username); #endif RtlInitUnicodeString (&sam_user, sam_username); RtlInitUnicodeString (&prefix, L""); RtlInitEmptyUnicodeString (&flatnm, flatname, (UNLEN + 1) * sizeof (WCHAR)); stat = funcs->GetAuthDataForUser (&sam_user, SecNameSamCompatible, NULL, &user_auth, &user_auth_size, &flatnm); if (!NT_SUCCESS (stat)) { char sam_u[MAX_DOMAIN_NAME_LEN + UNLEN + 2]; wcstombs (sam_u, sam_user.Buffer, sizeof (sam_u)); cyglsa_printf ("GetAuthDataForUser (%u,%u,%s) failed: 0x%08lx\n", sam_user.Length, sam_user.MaximumLength, sam_u, stat); return stat; } memcpy (ts.SourceName, "Cygwin.1", 8); ts.SourceIdentifier.HighPart = 0; ts.SourceIdentifier.LowPart = 0x0104; RtlInitEmptyUnicodeString (&flatnm, flatname, (UNLEN + 1) * sizeof (WCHAR)); stat = funcs->ConvertAuthDataToToken (user_auth, user_auth_size, SecurityDelegation, &ts, Interactive, *authority, &token, logon_id, &flatnm, sub_stat); if (!NT_SUCCESS (stat)) { cyglsa_printf ("ConvertAuthDataToToken failed: 0x%08lx\n", stat); return stat; } stat = funcs->DuplicateHandle (token, &prf.token); if (!NT_SUCCESS (stat)) { cyglsa_printf ("DuplicateHandle failed: 0x%08lx\n", stat); return stat; } stat = funcs->CopyToClientBuffer (request, sizeof prf, *pbuf, &prf); if (!NT_SUCCESS (stat)) { cyglsa_printf ("CopyToClientBuffer failed: 0x%08lx\n", stat); return stat; } funcs->FreeLsaHeap (user_auth); #endif /* JUST_ANOTHER_NONWORKING_SOLUTION */ } if (pbuf_len) *pbuf_len = 64UL; /* A PLSA_TOKEN_INFORMATION_V2 is allocated in one piece, so... */ #if defined (__x86_64__) || defined (_M_AMD64) { /* ...on 64 bit systems we have to convert the incoming 32 bit offsets into 64 bit pointers. That requires to re-evaluate the size of the outgoing tokinf structure and a somewhat awkward procedure to copy the information over. */ LONG_PTR base; PBYTE tptr; DWORD size, newsize; PSID src_sid; PCYG_TOKEN_GROUPS src_grps; PTOKEN_GROUPS grps; PTOKEN_PRIVILEGES src_privs; PACL src_acl; base = (LONG_PTR) &authinf->inf; newsize = authinf->inf_size; newsize += sizeof (TOKEN_USER) - sizeof (CYG_TOKEN_USER); /* User SID */ newsize += sizeof (PTOKEN_GROUPS) - sizeof (OFFSET); /* Groups */ src_grps = (PCYG_TOKEN_GROUPS) (base + authinf->inf.Groups); newsize += src_grps->GroupCount /* Group SIDs */ * (sizeof (SID_AND_ATTRIBUTES) - sizeof (CYG_SID_AND_ATTRIBUTES)); newsize += sizeof (PSID) - sizeof (OFFSET); /* Primary Group SID */ newsize += sizeof (PTOKEN_PRIVILEGES) - sizeof (OFFSET); /* Privileges */ newsize += 0; /* Owner SID */ newsize += sizeof (PACL) - sizeof (OFFSET); /* Default DACL */ if (!(tokinf = funcs->AllocateLsaHeap (newsize))) return STATUS_NO_MEMORY; tptr = (PBYTE)(tokinf + 1); tokinf->ExpirationTime = authinf->inf.ExpirationTime; /* User SID */ src_sid = (PSID) (base + authinf->inf.User.User.Sid); size = RtlLengthSid (src_sid); RtlCopySid (size, (PSID) tptr, src_sid); tokinf->User.User.Sid = (PSID) tptr; tptr += size; tokinf->User.User.Attributes = authinf->inf.User.User.Attributes; /* Groups */ grps = (PTOKEN_GROUPS) tptr; tokinf->Groups = grps; grps->GroupCount = src_grps->GroupCount; tptr += sizeof grps->GroupCount + grps->GroupCount * sizeof (SID_AND_ATTRIBUTES); /* Group SIDs */ for (i = 0; i < src_grps->GroupCount; ++i) { src_sid = (PSID) (base + src_grps->Groups[i].Sid); size = RtlLengthSid (src_sid); RtlCopySid (size, (PSID) tptr, src_sid); tokinf->Groups->Groups[i].Sid = (PSID) tptr; tptr += size; tokinf->Groups->Groups[i].Attributes = src_grps->Groups[i].Attributes; } /* Primary Group SID */ src_sid = (PSID) (base + authinf->inf.PrimaryGroup.PrimaryGroup); size = RtlLengthSid (src_sid); RtlCopySid (size, (PSID) tptr, src_sid); tokinf->PrimaryGroup.PrimaryGroup = (PSID) tptr; tptr += size; /* Privileges */ src_privs = (PTOKEN_PRIVILEGES) (base + authinf->inf.Privileges); size = sizeof src_privs->PrivilegeCount + src_privs->PrivilegeCount * sizeof (LUID_AND_ATTRIBUTES); memcpy (tptr, src_privs, size); tokinf->Privileges = (PTOKEN_PRIVILEGES) tptr; tptr += size; /* Owner */ tokinf->Owner.Owner = NULL; /* Default DACL */ src_acl = (PACL) (base + authinf->inf.DefaultDacl.DefaultDacl); size = src_acl->AclSize; memcpy (tptr, src_acl, size); tokinf->DefaultDacl.DefaultDacl = (PACL) tptr; } #else { /* ...on 32 bit systems we just allocate tokinf with the same size as we get, copy the whole structure and convert offsets into pointers. */ /* Allocate LUID for usage in the logon SID on Windows 2000. This is not done in the 64 bit code above for hopefully obvious reasons... */ LUID logon_sid_id; if (must_create_logon_sid && !NT_SUCCESS (NtAllocateLocallyUniqueId (&logon_sid_id))) return STATUS_INSUFFICIENT_RESOURCES; if (!(tokinf = funcs->AllocateLsaHeap (authinf->inf_size))) return STATUS_NO_MEMORY; memcpy (tokinf, &authinf->inf, authinf->inf_size); /* User SID */ tokinf->User.User.Sid = (PSID) ((PBYTE) tokinf + (LONG_PTR) tokinf->User.User.Sid); /* Groups */ tokinf->Groups = (PTOKEN_GROUPS) ((PBYTE) tokinf + (LONG_PTR) tokinf->Groups); /* Group SIDs */ for (i = 0; i < tokinf->Groups->GroupCount; ++i) { tokinf->Groups->Groups[i].Sid = (PSID) ((PBYTE) tokinf + (LONG_PTR) tokinf->Groups->Groups[i].Sid); if (must_create_logon_sid && tokinf->Groups->Groups[i].Attributes & SE_GROUP_LOGON_ID && *RtlSubAuthorityCountSid (tokinf->Groups->Groups[i].Sid) == 3 && *RtlSubAuthoritySid (tokinf->Groups->Groups[i].Sid, 0) == SECURITY_LOGON_IDS_RID) { *RtlSubAuthoritySid (tokinf->Groups->Groups[i].Sid, 1) = logon_sid_id.HighPart; *RtlSubAuthoritySid (tokinf->Groups->Groups[i].Sid, 2) = logon_sid_id.LowPart; } } /* Primary Group SID */ tokinf->PrimaryGroup.PrimaryGroup = (PSID) ((PBYTE) tokinf + (LONG_PTR) tokinf->PrimaryGroup.PrimaryGroup); /* Privileges */ tokinf->Privileges = (PTOKEN_PRIVILEGES) ((PBYTE) tokinf + (LONG_PTR) tokinf->Privileges); /* Owner SID */ tokinf->Owner.Owner = NULL; /* Default DACL */ tokinf->DefaultDacl.DefaultDacl = (PACL) ((PBYTE) tokinf + (LONG_PTR) tokinf->DefaultDacl.DefaultDacl); } #endif *tok = (PVOID) tokinf; *tok_type = LsaTokenInformationV2; print_tokinf (tokinf, authinf->inf_size, authinf, &authinf->inf, (PVOID)((LONG_PTR) &authinf->inf + authinf->inf_size)); /* Create logon session. */ stat = NtAllocateLocallyUniqueId (logon_id); if (!NT_SUCCESS (stat)) { funcs->FreeLsaHeap (*tok); *tok = NULL; cyglsa_printf ("NtAllocateLocallyUniqueId status 0x%08lx\n", stat); return STATUS_INSUFFICIENT_RESOURCES; } stat = funcs->CreateLogonSession (logon_id); if (stat != STATUS_SUCCESS) { funcs->FreeLsaHeap (*tok); *tok = NULL; cyglsa_printf ("CreateLogonSession failed: 0x%08lx\n", stat); return stat; } cyglsa_printf ("BINGO!!!\n", stat); return STATUS_SUCCESS; }
// read font linking information from registry, and store in std::map //------------------------------------------------------------------ void initWindows(){ LONG l_ret; const wchar_t *Fonts = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"; HKEY key_ft; l_ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, Fonts, 0, KEY_QUERY_VALUE, &key_ft); if (l_ret != ERROR_SUCCESS){ ofLogError("ofTrueTypeFont") << "initWindows(): couldn't find fonts registery key"; return; } DWORD value_count; DWORD max_data_len; wchar_t value_name[2048]; BYTE *value_data; // get font_file_name -> font_face mapping from the "Fonts" registry key l_ret = RegQueryInfoKeyW(key_ft, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &value_count, nullptr, &max_data_len, nullptr, nullptr); if(l_ret != ERROR_SUCCESS){ ofLogError("ofTrueTypeFont") << "initWindows(): couldn't query registery for fonts"; return; } // no font installed if (value_count == 0){ ofLogError("ofTrueTypeFont") << "initWindows(): couldn't find any fonts in registery"; return; } // max_data_len is in BYTE value_data = static_cast<BYTE *>(HeapAlloc(GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS, max_data_len)); if(value_data == nullptr) return; char value_name_char[2048]; char value_data_char[2048]; /*char ppidl[2048]; char fontsPath[2048]; SHGetKnownFolderIDList(FOLDERID_Fonts, 0, nullptr, &ppidl); SHGetPathFromIDList(ppidl,&fontsPath);*/ std::string fontsDir = getenv ("windir"); fontsDir += "\\Fonts\\"; for (DWORD i = 0; i < value_count; ++i) { DWORD name_len = 2048; DWORD data_len = max_data_len; l_ret = RegEnumValueW(key_ft, i, value_name, &name_len, nullptr, nullptr, value_data, &data_len); if(l_ret != ERROR_SUCCESS){ ofLogError("ofTrueTypeFont") << "initWindows(): couldn't read registry key for font type"; continue; } wcstombs(value_name_char,value_name,2048); wcstombs(value_data_char,reinterpret_cast<wchar_t *>(value_data),2048); std::string curr_face = value_name_char; std::string font_file = value_data_char; curr_face = curr_face.substr(0, curr_face.find('(') - 1); fonts_table[curr_face] = fontsDir + font_file; } HeapFree(GetProcessHeap(), 0, value_data); l_ret = RegCloseKey(key_ft); }
/* Encode a (wide) character string to the locale encoding with the surrogateescape error handler (characters in range U+DC80..U+DCFF are converted to bytes 0x80..0xFF). This function is the reverse of _Py_char2wchar(). Return a pointer to a newly allocated byte string (use PyMem_Free() to free the memory), or NULL on conversion or memory allocation error. If error_pos is not NULL: *error_pos is the index of the invalid character on conversion error, or (size_t)-1 otherwise. */ char* _Py_wchar2char(const wchar_t *text, size_t *error_pos) { const size_t len = wcslen(text); char *result = NULL, *bytes = NULL; size_t i, size, converted; wchar_t c, buf[2]; if (error_pos != NULL) *error_pos = (size_t)-1; /* The function works in two steps: 1. compute the length of the output buffer in bytes (size) 2. outputs the bytes */ size = 0; buf[1] = 0; while (1) { for (i=0; i < len; i++) { c = text[i]; if (c >= 0xdc80 && c <= 0xdcff) { /* UTF-8b surrogate */ if (bytes != NULL) { *bytes++ = c - 0xdc00; size--; } else size++; continue; } else { buf[0] = c; #ifdef ANDROID converted =1; if (bytes != NULL) *bytes = c; #else if (bytes != NULL) converted = wcstombs(bytes, buf, size); else converted = wcstombs(NULL, buf, 0); #endif if (converted == (size_t)-1) { if (result != NULL) PyMem_Free(result); if (error_pos != NULL) *error_pos = i; return NULL; } if (bytes != NULL) { bytes += converted; size -= converted; } else size += converted; } } if (result != NULL) { *bytes = 0; break; } size += 1; /* nul byte at the end */ result = PyMem_Malloc(size); if (result == NULL) return NULL; bytes = result; } return result; }
static int xic_draw_callback(XIC, XPointer client_data, XPointer call_data) { QXIMInputContext *qic = (QXIMInputContext *) client_data; if (!qic) { XIM_DEBUG("xic_draw_callback: no qic"); return 0; } QXIMInputContext::ICData *data = qic->icData(); if (!data) { XIM_DEBUG("xic_draw_callback: no ic data"); return 0; } XIM_DEBUG("xic_draw_callback"); if(!data->composing) { data->clear(); data->composing = true; } XIMPreeditDrawCallbackStruct *drawstruct = (XIMPreeditDrawCallbackStruct *) call_data; XIMText *text = (XIMText *) drawstruct->text; int cursor = drawstruct->caret, sellen = 0, selstart = 0; if (!drawstruct->caret && !drawstruct->chg_first && !drawstruct->chg_length && !text) { if(data->text.isEmpty()) { XIM_DEBUG("compose emptied"); // if the composition string has been emptied, we need // to send an InputMethodEnd event QInputMethodEvent e; qic->sendEvent(e); data->clear(); // if the commit string has coming after here, InputMethodStart // will be sent dynamically } return 0; } if (text) { char *str = 0; if (text->encoding_is_wchar) { int l = wcstombs(NULL, text->string.wide_char, text->length); if (l != -1) { str = new char[l + 1]; wcstombs(str, text->string.wide_char, l); str[l] = 0; } } else str = text->string.multi_byte; if (!str) return 0; QString s = QString::fromLocal8Bit(str); if (text->encoding_is_wchar) delete [] str; if (drawstruct->chg_length < 0) data->text.replace(drawstruct->chg_first, INT_MAX, s); else data->text.replace(drawstruct->chg_first, drawstruct->chg_length, s); if (data->selectedChars.size() < data->text.length()) { // expand the selectedChars array if the compose string is longer int from = data->selectedChars.size(); data->selectedChars.resize(data->text.length()); for (int x = from; x < data->selectedChars.size(); ++x) data->selectedChars.clearBit(x); } // determine if the changed chars are selected based on text->feedback for (int x = 0; x < text->length; ++x) data->selectedChars.setBit(x + drawstruct->chg_first, (text->feedback ? (text->feedback[x] & XIMReverse) : 0)); // figure out where the selection starts, and how long it is bool started = false; for (int x = 0; x < qMin(data->selectedChars.size(), data->text.length()); ++x) { if (started) { if (data->selectedChars.testBit(x)) ++sellen; else break; } else { if (data->selectedChars.testBit(x)) { selstart = x; started = true; sellen = 1; } } } } else { if (drawstruct->chg_length == 0) drawstruct->chg_length = -1; data->text.remove(drawstruct->chg_first, drawstruct->chg_length); bool qt_compose_emptied = data->text.isEmpty(); if (qt_compose_emptied) { XIM_DEBUG("compose emptied 2 text=%s", data->text.toUtf8().constData()); // if the composition string has been emptied, we need // to send an InputMethodEnd event QInputMethodEvent e; qic->sendEvent(e); data->clear(); // if the commit string has coming after here, InputMethodStart // will be sent dynamically return 0; } } XIM_DEBUG("sending compose: '%s', cursor=%d, sellen=%d", data->text.toUtf8().constData(), cursor, sellen); QList<QInputMethodEvent::Attribute> attrs; if (selstart > 0) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, 0, selstart, qic->standardFormat(QInputContext::PreeditFormat)); if (sellen) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selstart, sellen, qic->standardFormat(QInputContext::SelectionFormat)); if (selstart + sellen < data->text.length()) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selstart + sellen, data->text.length() - selstart - sellen, qic->standardFormat(QInputContext::PreeditFormat)); attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, cursor, sellen ? 0 : 1, QVariant()); QInputMethodEvent e(data->text, attrs); data->preeditEmpty = data->text.isEmpty(); qic->sendEvent(e); return 0; }
/* Open a gzip file either by name or file descriptor. */ local gzFile gz_open( const void *path, int fd, const char *mode) { gz_statep state; size_t len; int oflag; #ifdef O_CLOEXEC int cloexec = 0; #endif #ifdef O_EXCL int exclusive = 0; #endif /* check input */ if (path == NULL) return NULL; /* allocate gzFile structure to return */ state = (gz_statep)malloc(sizeof(gz_state)); if (state == NULL) return NULL; state->size = 0; /* no buffers allocated yet */ state->want = GZBUFSIZE; /* requested buffer size */ state->msg = NULL; /* no error message yet */ /* interpret mode */ state->mode = GZ_NONE; state->level = Z_DEFAULT_COMPRESSION; state->strategy = Z_DEFAULT_STRATEGY; state->direct = 0; while (*mode) { if (*mode >= '0' && *mode <= '9') state->level = *mode - '0'; else switch (*mode) { case 'r': state->mode = GZ_READ; break; #ifndef NO_GZCOMPRESS case 'w': state->mode = GZ_WRITE; break; case 'a': state->mode = GZ_APPEND; break; #endif case '+': /* can't read and write at the same time */ free(state); return NULL; case 'b': /* ignore -- will request binary anyway */ break; #ifdef O_CLOEXEC case 'e': cloexec = 1; break; #endif #ifdef O_EXCL case 'x': exclusive = 1; break; #endif case 'f': state->strategy = Z_FILTERED; break; case 'h': state->strategy = Z_HUFFMAN_ONLY; break; case 'R': state->strategy = Z_RLE; break; case 'F': state->strategy = Z_FIXED; break; case 'T': state->direct = 1; break; default: /* could consider as an error, but just ignore */ ; } mode++; } /* must provide an "r", "w", or "a" */ if (state->mode == GZ_NONE) { free(state); return NULL; } /* can't force transparent read */ if (state->mode == GZ_READ) { if (state->direct) { free(state); return NULL; } state->direct = 1; /* for empty file */ } /* save the path name for error messages */ #ifdef _WIN32 if (fd == -2) { len = wcstombs(NULL, path, 0); if (len == (size_t)-1) len = 0; } else #endif len = strlen((const char *)path); state->path = (char *)malloc(len + 1); if (state->path == NULL) { free(state); return NULL; } #ifdef _WIN32 if (fd == -2) if (len) wcstombs(state->path, path, len + 1); else *(state->path) = 0; else #endif #if !defined(NO_snprintf) && !defined(NO_vsnprintf) snprintf(state->path, len + 1, "%s", (const char *)path); #else strcpy(state->path, path); #endif /* compute the flags for open() */ oflag = #ifdef O_LARGEFILE O_LARGEFILE | #endif #ifdef O_BINARY O_BINARY | #endif #ifdef O_CLOEXEC (cloexec ? O_CLOEXEC : 0) | #endif (state->mode == GZ_READ ? O_RDONLY : (O_WRONLY | O_CREAT | #ifdef O_EXCL (exclusive ? O_EXCL : 0) | #endif (state->mode == GZ_WRITE ? O_TRUNC : O_APPEND))); /* open the file with the appropriate flags (or just use fd) */ state->fd = fd > -1 ? fd : ( #ifdef _WIN32 fd == -2 ? _wopen(path, oflag, 0666) : #endif open((const char *)path, oflag, 0666)); if (state->fd == -1) { free(state->path); free(state); return NULL; } if (state->mode == GZ_APPEND) state->mode = GZ_WRITE; /* simplify later checks */ /* save the current position for rewinding (only if reading) */ if (state->mode == GZ_READ) { state->start = LSEEK(state->fd, 0, SEEK_CUR); if (state->start == -1) state->start = 0; } /* initialize stream */ gz_reset(state); /* return stream */ return (gzFile)state; }
len=wcstombs(buff,pwstr,SIZE_CHAR_BUFFER); if(len==-1) return false; if(len<SIZE_CHAR_BUFFER) { buff[len]=0; ret.assign(buff,len); return true; } len=wcstombs(0,pwstr,0); if(len==-1) return false; wyc_error("to_astring: size overflow [%d]",len); } else len<<=1; char *pdst=new char[len+1]; len=wcstombs(pdst,pwstr,len); assert(len>=0); pdst[len]=0; ret.assign(pdst,len); delete [] pdst; return true; } bool str2wstr_utf8(std::wstring &ret, const char *pstr, size_t len) { string_codec codec; if(!codec.decode_utf8(pstr,len)) return false; unsigned n=codec.chars(); ret.assign(codec.buffer(),n); return true;
/* Converts Python simple objects (String, Long, Float, Boolean, Bytes, and None) to C string. If the `obj` is none of these types, then call PyObject_Str, and recall this function with the result. */ char * PyObject2char(PyObject *obj) { char *str = NULL; char *tmp = NULL; const wchar_t *wstr; Py_ssize_t length = 0; const unsigned int len = 24; /* The max length that a number's char* representation can be. */ if (obj == NULL) return NULL; /* If Python objects is a None return an empty("") char*. */ if (obj == Py_None) { str = (char *)malloc(sizeof(char)); str[0] = '\0'; return str; } if (PyUnicode_Check(obj)) { /* Python string converting. From Python 3.3 could be use PyUnicode_AsUTF8AndSize(). */ wstr = PyUnicode_AsWideCharString(obj, &length); str = (char *)malloc(sizeof(char) * (length + 1)); if (str == NULL) return (char *)PyErr_NoMemory(); wcstombs(str, wstr, length); /* Put the delimiter at the end. */ str[length] = '\0'; } else if (PyLong_Check(obj)) { /* Python integer converting. Could be longer, literally. */ long int inum = PyLong_AsLong(obj); tmp = malloc(sizeof(char) * len); if (tmp == NULL) return (char *)PyErr_NoMemory(); sprintf(tmp, "%ld", inum); } else if (PyFloat_Check(obj)) { /* Python floating point number converting. */ double dnum = PyFloat_AsDouble(obj); tmp = malloc(sizeof(char) * len); if (tmp == NULL) return (char *)PyErr_NoMemory(); sprintf(tmp, "%lf", dnum); } else if (PyBool_Check(obj)) { /* Python boolean converting to number representation (0 or 1). */ if (obj == Py_True) { str = "1"; } else { str = "0"; } } else if (PyBytes_Check(obj)) { /* Python bytes converting. */ tmp = PyBytes_AsString(obj); if (tmp == NULL) return NULL; str = (char *)malloc(sizeof(char) * (strlen(tmp) + 1)); strcpy(str, tmp); return str; } else { PyObject *tmpobj = PyObject_Str(obj); if (tmpobj == NULL) { PyErr_BadInternalCall(); return NULL; } str = PyObject2char(tmpobj); Py_DECREF(tmpobj); return str; } /* In case of converting numbers, optimizing the memory allocation. */ if (tmp != NULL) { str = strdup(tmp); free(tmp); } return str; }
// ---------------------------------------------------------------------------- BOOL LUKS_IdentifyCypher( char* cypherName, int keySizeBits, char* cypherMode, BOOL baseIVCypherOnHashLength, WCHAR *cypherKernelModeDeviceName, GUID* cypherGUID, SECTOR_IV_GEN_METHOD* sectorIVGenMethod, WCHAR *IVHashKernelModeDeviceName, GUID* IVHashGUID, WCHAR *IVCypherKernelModeDeviceName, GUID* IVCypherGUID ) { BOOL allOK; CYPHER_MODE currCypherMode; CYPHER_MODE useCypherMode; char* IVGenMethod; HASH IVHashDetails; char ucCypherMode[LUKS_CIPHERMODE_L]; char ucCypherName[LUKS_CIPHERNAME_L]; char tmpUCtestMode[LUKS_CIPHERMODE_L]; char* tmpPtr; WCHAR strMode_WCHAR[10]; // Enough to hold any cypher mode as a string char strMode_char[10]; // Enough to hold any cypher mode as a string BOOL gotImplDetails; int countImplCypher = 0; DRIVER_AND_ALG* implCypher = NULL; // Array of options int countImplHash = 0; DRIVER_AND_ALG* implHash = NULL; // Array of options allOK = TRUE; gotImplDetails = FALSE; // Standardise to uppercase; removes any potential problems with case // sensitivity SDUstrtoupper(ucCypherMode, cypherMode); SDUstrtoupper(ucCypherName, cypherName); // Detect IV generation method // Examples: ecb // cbc-plain // lrw-plain // cbc-essiv:sha256 // The stuff before the "-" is the cypher mode; the stuff after is the IV // generation // Note: ESSIV is NOT specified in the LUKS specification, but LUKS implements // this anyway as "-essiv:<hash>" if (allOK) { // Fallback to none... (e.g. ECB) *sectorIVGenMethod = SCTRIVGEN_NONE; wcscpy(IVHashKernelModeDeviceName, TEXT("")); *IVHashGUID = FREEOTFE_NULL_GUID; tmpPtr = strstr(ucCypherMode, "-"); if (tmpPtr != NULL) { tmpPtr[0] = 0; // Replace "-" with terminating NULL for ucCypherMode // tick on a char to point to IV generation method IVGenMethod = &(tmpPtr[1]); // Search for "-plain64" and strip off cypher mode SDUstrtoupper(tmpUCtestMode, PLAIN64_IV); tmpPtr = strstr(IVGenMethod, tmpUCtestMode); if (tmpPtr != NULL) { *sectorIVGenMethod = SCTRIVGEN_64BIT_SECTOR_ID; } else { // Search for "-plain" and strip off cypher mode SDUstrtoupper(tmpUCtestMode, PLAIN_IV); tmpPtr = strstr(IVGenMethod, tmpUCtestMode); if (tmpPtr != NULL) { *sectorIVGenMethod = SCTRIVGEN_32BIT_SECTOR_ID; } } // Search for "-essiv" and strip off cypher mode SDUstrtoupper(tmpUCtestMode, ESSIV_IV); tmpPtr = strstr(IVGenMethod, tmpUCtestMode); if (tmpPtr != NULL) { *sectorIVGenMethod = SCTRIVGEN_ESSIV; // Get the hash tmpPtr = strstr(IVGenMethod, ":"); allOK = (tmpPtr != NULL); if (allOK) { tmpPtr = &(tmpPtr[1]); // Move on 1 char allOK = LUKS_IdentifyHash( tmpPtr, IVHashKernelModeDeviceName, IVHashGUID ); } } // Search for "-benbi" and strip off cypher mode SDUstrtoupper(tmpUCtestMode, BENBI_IV); tmpPtr = strstr(IVGenMethod, tmpUCtestMode); if (tmpPtr != NULL) { *sectorIVGenMethod = SCTRIVGEN_NONE; // Get the hash tmpPtr = strstr(IVGenMethod, ":"); // Optional/not needed for "benbi"? if (tmpPtr != NULL) { tmpPtr = &(tmpPtr[1]); // Move on 1 char allOK = LUKS_IdentifyHash( tmpPtr, IVHashKernelModeDeviceName, IVHashGUID ); } } } } // Determine cypher mode useCypherMode = CYPHER_MODE_UNKNOWN; if (allOK) { for ( currCypherMode = _CYPHER_MODE_FIRST; currCypherMode <= _CYPHER_MODE_LAST; currCypherMode++ ) { // Convert cypher mode to simple char text representation, in uppercase driver_CypherPrettyprintAlgMode(currCypherMode, strMode_WCHAR); memset(strMode_char, 0, sizeof(strMode_char)); wcstombs(strMode_char, strMode_WCHAR, wcslen(strMode_WCHAR)); SDUstrtoupper(strMode_char, strMode_char); if (strcmp(strMode_char, ucCypherMode) == 0) { useCypherMode = currCypherMode; break; } } allOK = (useCypherMode != CYPHER_MODE_UNKNOWN); } // Obtain details of all cyphers... if (allOK) { gotImplDetails = driver_GetAllAlgorithmDriverOptions( &countImplHash, &implHash, &countImplCypher, &implCypher, TRUE ); } // Given the information we've determined, identify the FreeOTFE driver to // map the details to if (allOK) { allOK = LUKS_IdentifyCypher_SearchCyphers( countImplCypher, implCypher, cypherName, keySizeBits, useCypherMode, cypherKernelModeDeviceName, cypherGUID ); } // Sort out the IV cypher driver if (allOK) { wcscpy(IVCypherKernelModeDeviceName, cypherKernelModeDeviceName); *IVCypherGUID = *cypherGUID; // Because of a bug in dm-crypt, the cypher used to generate ESSIV IVs may // ***NOT*** be the same cypher as used for the bulk encryption of data // This is because it passes the IV hash's length to the cypher when it // creates the ESSIV cypher - as a result, the ESSIV cypher may have a // different keylength to the bulk encryption cypher if ( (baseIVCypherOnHashLength) && (*sectorIVGenMethod == SCTRIVGEN_ESSIV) ) { allOK = driver_HashGetImplDetails( IVHashKernelModeDeviceName, IVHashGUID, &IVHashDetails ); if (allOK) { allOK = LUKS_IdentifyCypher_SearchCyphers( countImplCypher, implCypher, cypherName, IVHashDetails.Length, useCypherMode, IVCypherKernelModeDeviceName, IVCypherGUID ); } } } if (gotImplDetails) { driver_FreeAllAlgorithmDriverOptions( &countImplHash, &implHash, &countImplCypher, &implCypher ); } return allOK; }
static bool Config_SetDefault() { if (ConfigOpenSection("Video-General", &g_configVideoGeneral) != M64ERR_SUCCESS) { LOG(LOG_ERROR, "Unable to open Video-General configuration section"); return false; } if (ConfigOpenSection("Video-GLideN64", &g_configVideoGliden64) != M64ERR_SUCCESS) { LOG(LOG_ERROR, "Unable to open GLideN64 configuration section"); return false; } config.resetToDefaults(); // Set default values for "Video-General" section, if they are not set yet. Taken from RiceVideo m64p_error res = ConfigSetDefaultBool(g_configVideoGeneral, "Fullscreen", config.video.fullscreen, "Use fullscreen mode if True, or windowed mode if False "); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGeneral, "ScreenWidth", config.video.windowedWidth, "Width of output window or fullscreen width"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGeneral, "ScreenHeight", config.video.windowedHeight, "Height of output window or fullscreen height"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGeneral, "VerticalSync", config.video.verticalSync, "If true, activate the SDL_GL_SWAP_CONTROL attribute"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "configVersion", CONFIG_VERSION_CURRENT, "Settings version. Don't touch it."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "MultiSampling", config.video.multisampling, "Enable/Disable MultiSampling (0=off, 2,4,8,16=quality)"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "AspectRatio", config.frameBufferEmulation.aspect, "Screen aspect ratio (0=stretch, 1=force 4:3, 2=force 16:9, 3=adjust)"); assert(res == M64ERR_SUCCESS); //#Texture Settings res = ConfigSetDefaultBool(g_configVideoGliden64, "bilinearMode", config.texture.bilinearMode, "Bilinear filtering mode (0=N64 3point, 1=standard)"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "MaxAnisotropy", config.texture.maxAnisotropy, "Max level of Anisotropic Filtering, 0 for off"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "CacheSize", config.texture.maxBytes / uMegabyte, "Size of texture cache in megabytes. Good value is VRAM*3/4"); assert(res == M64ERR_SUCCESS); //#Emulation Settings res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableFog", config.generalEmulation.enableFog, "Enable fog emulation."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableNoise", config.generalEmulation.enableNoise, "Enable color noise emulation."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableLOD", config.generalEmulation.enableLOD, "Enable LOD emulation."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableHWLighting", config.generalEmulation.enableHWLighting, "Enable hardware per-pixel lighting."); assert(res == M64ERR_SUCCESS); #ifdef ANDROID res = ConfigSetDefaultBool(g_configVideoGliden64, "ForcePolygonOffset", config.generalEmulation.forcePolygonOffset, "If true, use polygon offset values specified below"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultFloat(g_configVideoGliden64, "PolygonOffsetFactor", config.generalEmulation.polygonOffsetFactor, "Specifies a scale factor that is used to create a variable depth offset for each polygon"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultFloat(g_configVideoGliden64, "PolygonOffsetUnits", config.generalEmulation.polygonOffsetUnits, "Is multiplied by an implementation-specific value to create a constant depth offset"); assert(res == M64ERR_SUCCESS); #endif //#Frame Buffer Settings:" res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableFBEmulation", config.frameBufferEmulation.enable, "Enable frame and|or depth buffer emulation."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableCopyColorToRDRAM", config.frameBufferEmulation.copyToRDRAM, "Enable color buffer copy to RDRAM."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableCopyDepthToRDRAM", config.frameBufferEmulation.copyDepthToRDRAM, "Enable depth buffer copy to RDRAM."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableCopyColorFromRDRAM", config.frameBufferEmulation.copyFromRDRAM, "Enable color buffer copy from RDRAM."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableDetectCFB", config.frameBufferEmulation.detectCFB, "Detect CPU writes to frame buffer."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "EnableN64DepthCompare", config.frameBufferEmulation.N64DepthCompare, "Enable N64 depth compare instead of OpenGL standard one. Experimental."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "ValidityCheckMethod", config.frameBufferEmulation.validityCheckMethod, "Method to check validity of auxiliary texture frame buffer (0=write fingerprint to the buffer, 1=fill whole buffer in RDRAM with test value)"); assert(res == M64ERR_SUCCESS); //#Texture filter settings res = ConfigSetDefaultInt(g_configVideoGliden64, "txFilterMode", config.textureFilter.txFilterMode, "Texture filter (0=none, 1=Smooth filtering 1, 2=Smooth filtering 2, 3=Smooth filtering 3, 4=Smooth filtering 4, 5=Sharp filtering 1, 6=Sharp filtering 2)"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "txEnhancementMode", config.textureFilter.txEnhancementMode, "Texture Enhancement (0=none, 1=store as is, 2=X2, 3=X2SAI, 4=HQ2X, 5=HQ2XS, 6=LQ2X, 7=LQ2XS, 8=HQ4X, 9=2xBRZ, 10=3xBRZ, 11=4xBRZ, 12=5xBRZ), 13=6xBRZ"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "txFilterIgnoreBG", config.textureFilter.txFilterIgnoreBG, "Don't filter background textures."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "txCacheSize", config.textureFilter.txCacheSize/uMegabyte, "Size of filtered textures cache in megabytes."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "txHiresEnable", config.textureFilter.txHiresEnable, "Use high-resolution texture packs if available."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "txHiresFullAlphaChannel", config.textureFilter.txHiresFullAlphaChannel, "Allow to use alpha channel of high-res texture fully."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "txHresAltCRC", config.textureFilter.txHresAltCRC, "Use alternative method of paletted textures CRC calculation."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "txDump", config.textureFilter.txDump, "Enable dump of loaded N64 textures."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "txCacheCompression", config.textureFilter.txCacheCompression, "Zip textures cache."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "txForce16bpp", config.textureFilter.txForce16bpp, "Force use 16bit texture formats for HD textures."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultBool(g_configVideoGliden64, "txSaveCache", config.textureFilter.txSaveCache, "Save texture cache to hard disk."); assert(res == M64ERR_SUCCESS); // Convert to multibyte char txPath[PLUGIN_PATH_SIZE * 2]; wcstombs(txPath, config.textureFilter.txPath, PLUGIN_PATH_SIZE * 2); res = ConfigSetDefaultString(g_configVideoGliden64, "txPath", txPath, "Path to folder with hi-res texture packs."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultString(g_configVideoGliden64, "fontName", config.font.name.c_str(), "File name of True Type Font for text messages."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "fontSize", config.font.size, "Font size."); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultString(g_configVideoGliden64, "fontColor", "B5E61D", "Font color in RGB format."); assert(res == M64ERR_SUCCESS); //#Bloom filter settings res = ConfigSetDefaultInt(g_configVideoGliden64, "EnableBloom", config.bloomFilter.enable, "Enable bloom filter"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "bloomThresholdLevel", config.bloomFilter.thresholdLevel, "Brightness threshold level for bloom. Values [2, 6]"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "bloomBlendMode", config.bloomFilter.blendMode, "Bloom blend mode (0=Strong, 1=Mild, 2=Light)"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "blurAmount", config.bloomFilter.blurAmount, "Blur radius. Values [2, 10]"); assert(res == M64ERR_SUCCESS); res = ConfigSetDefaultInt(g_configVideoGliden64, "blurStrength", config.bloomFilter.blurStrength, "Blur strength. Values [10, 100]"); assert(res == M64ERR_SUCCESS); return ConfigSaveSection("Video-GLideN64") == M64ERR_SUCCESS; }
isc_result_t isc_ntsecurity_getaccountgroups(char *username, char **GroupList, unsigned int maxgroups, unsigned int *totalGroups) { LPGROUP_USERS_INFO_0 pTmpBuf; LPLOCALGROUP_USERS_INFO_0 pTmpLBuf; DWORD i; LPLOCALGROUP_USERS_INFO_0 pBuf = NULL; LPGROUP_USERS_INFO_0 pgrpBuf = NULL; DWORD dwLevel = 0; DWORD dwFlags = LG_INCLUDE_INDIRECT; DWORD dwPrefMaxLen = MAX_PREFERRED_LENGTH; DWORD dwEntriesRead = 0; DWORD dwTotalEntries = 0; NET_API_STATUS nStatus; size_t retlen; wchar_t user[MAX_NAME_LENGTH]; retlen = mbstowcs(user, username, MAX_NAME_LENGTH); *totalGroups = 0; /* * Call the NetUserGetLocalGroups function * specifying information level 0. * * The LG_INCLUDE_INDIRECT flag specifies that the * function should also return the names of the local * groups in which the user is indirectly a member. */ nStatus = NetUserGetLocalGroups(NULL, user, dwLevel, dwFlags, (LPBYTE *) &pBuf, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries); /* * See if the call succeeds, */ if (nStatus != NERR_Success) { if (nStatus == ERROR_ACCESS_DENIED) return (ISC_R_NOPERM); if (nStatus == ERROR_MORE_DATA) return (ISC_R_NOSPACE); if (nStatus == NERR_UserNotFound) dwEntriesRead = 0; } if (pBuf != NULL) { pTmpLBuf = pBuf; /* * Loop through the entries */ for (i = 0; (i < dwEntriesRead && *totalGroups < maxgroups); i++) { assert(pTmpLBuf != NULL); if (pTmpLBuf == NULL) break; retlen = wcslen(pTmpLBuf->lgrui0_name); GroupList[*totalGroups] = (char *) malloc(retlen +1); if (GroupList[*totalGroups] == NULL) return (ISC_R_NOMEMORY); retlen = wcstombs(GroupList[*totalGroups], pTmpLBuf->lgrui0_name, retlen); GroupList[*totalGroups][retlen] = '\0'; if (strcmp(GroupList[*totalGroups], "None") == 0) free(GroupList[*totalGroups]); else (*totalGroups)++; pTmpLBuf++; } } /* Free the allocated memory. */ if (pBuf != NULL) NetApiBufferFree(pBuf); /* * Call the NetUserGetGroups function, specifying level 0. */ nStatus = NetUserGetGroups(NULL, user, dwLevel, (LPBYTE*)&pgrpBuf, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries); /* * See if the call succeeds, */ if (nStatus != NERR_Success) { if (nStatus == ERROR_ACCESS_DENIED) return (ISC_R_NOPERM); if (nStatus == ERROR_MORE_DATA) return (ISC_R_NOSPACE); if (nStatus == NERR_UserNotFound) dwEntriesRead = 0; } if (pgrpBuf != NULL) { pTmpBuf = pgrpBuf; /* * Loop through the entries */ for (i = 0; (i < dwEntriesRead && *totalGroups < maxgroups); i++) { assert(pTmpBuf != NULL); if (pTmpBuf == NULL) break; retlen = wcslen(pTmpBuf->grui0_name); GroupList[*totalGroups] = (char *) malloc(retlen +1); if (GroupList[*totalGroups] == NULL) return (ISC_R_NOMEMORY); retlen = wcstombs(GroupList[*totalGroups], pTmpBuf->grui0_name, retlen); GroupList[*totalGroups][retlen] = '\0'; if (strcmp(GroupList[*totalGroups], "None") == 0) free(GroupList[*totalGroups]); else (*totalGroups)++; pTmpBuf++; } } /* * Free the allocated memory. */ if (pgrpBuf != NULL) NetApiBufferFree(pgrpBuf); return (ISC_R_SUCCESS); }
char *lg_readline(const char *mb_prompt) { static int is_init = FALSE; static HistoryW *hist = NULL; static HistEventW ev; static EditLine *el = NULL; int numc; size_t byte_len; const wchar_t *wc_line; char *mb_line; char *nl; if (!is_init) { size_t sz; #define HFILE ".lg_history" is_init = TRUE; sz = mbstowcs(NULL, mb_prompt, 0) + 4; wc_prompt = malloc (sz*sizeof(wchar_t)); mbstowcs(wc_prompt, mb_prompt, sz); hist = history_winit(); /* Init built-in history */ history_w(hist, &ev, H_SETSIZE, 20); /* Remember 20 events */ history_w(hist, &ev, H_LOAD, HFILE); el = el_init("link-parser", stdin, stdout, stderr); /* By default, it comes up in vi mode, with the editor not in * insert mode; and even when in insert mode, it drops back to * command mode at the drop of a hat. Totally confusing/lame. */ el_wset(el, EL_EDITOR, L"emacs"); el_wset(el, EL_HIST, history_w, hist); el_wset(el, EL_PROMPT_ESC, prompt, '\1'); /* Set the prompt function */ el_source(el, NULL); /* Source the user's defaults file. */ } wc_line = el_wgets(el, &numc); /* Received end-of-file */ if (numc <= 0) { el_end(el); history_wend(hist); free(wc_prompt); wc_prompt = NULL; hist = NULL; el = NULL; is_init = FALSE; return NULL; } if (1 < numc) { history_w(hist, &ev, H_ENTER, wc_line); history_w(hist, &ev, H_SAVE, HFILE); } /* fwprintf(stderr, L"==> got %d %ls", numc, wc_line); */ byte_len = wcstombs(NULL, wc_line, 0) + 4; mb_line = malloc(byte_len); wcstombs(mb_line, wc_line, byte_len); /* In order to be compatible with regular libedit, we have to * strip away the trailing newline, if any. */ nl = strchr(mb_line, '\n'); if (nl) *nl = 0x0; return mb_line; }