bool ofxOscReceiver::getNextMessage( ofxOscMessage* message ) { // grab a lock on the queue grabMutex(); // check if there are any to be got if ( messages.size() == 0 ) { // no: release the mutex releaseMutex(); return false; } // copy the message from the queue to message ofxOscMessage* src_message = messages.front(); message->copy( *src_message ); // now delete the src message delete src_message; // and remove it from the queue messages.pop_front(); // release the lock on the queue releaseMutex(); // return success return true; }
int getNextSub(char ** text, unsigned long long int * pts, long int * milliDuration) { subtitle_printf(50, "index %d\n", readPointer); if (text == NULL) { subtitle_err("null pointer passed\n"); return cERR_SUBTITLE_ERROR; } getMutex(__LINE__); if (subPuffer[readPointer].text == NULL) { /* this is acutally not an error, because it may happen * that there is no subtitle for a while */ subtitle_printf(200, "null in subPuffer\n"); releaseMutex(__LINE__); return cERR_SUBTITLE_ERROR; } *text = strdup(subPuffer[readPointer].text); free(subPuffer[readPointer].text); subPuffer[readPointer].text = NULL; *pts = subPuffer[readPointer].pts; subPuffer[readPointer].pts = 0; *milliDuration = subPuffer[readPointer].milliDuration; subPuffer[readPointer].milliDuration = 0; readPointer++; if (readPointer == PUFFERSIZE) readPointer = 0; if (writePointer == readPointer) { /* this may happen, in normal case the reader is ones ahead the * writer. So this is the normal case that we eat the data * and have the reader reached. */ subtitle_printf(20, "ups something went wrong. no more writers? \n"); } releaseMutex(__LINE__); subtitle_printf(20, "readPointer %d\n",readPointer); subtitle_printf(10, "<\n"); return cERR_SUBTITLE_NO_ERROR; }
void dpy_display_t::printAdcInput(int8_t idxInput) { char lcdString[2+1]; if(idxInput >= 0 && idxInput <= 15) { #ifdef DEBUG int noChars = #endif sprintf(lcdString, "%02u", idxInput); ASSERT(noChars < (int)sizeof(lcdString)); } else lcdString[0] = 'B', lcdString[1] = 'G', lcdString[2] = '\0'; /* Get access to the display, or wait until anybody else has finished respectively. A timeout has been defined which should never elapse, but who knows. In case it should, we simply deny printing. */ if(acquireMutex()) { setCursor(/* col */ 5, /* row */ 0); print(lcdString); /* And release the mutex as soon as possible after writing to the underlaying class has been done. */ releaseMutex(); } } /* End of dpy_display_t::printAdcInput */
bool IsHashSecure(const unsigned char* hash) { KeWaitForSingleObject(&g_secuHashMutex,Executive,KernelMode,FALSE,NULL); UCHAR id = HashFunc(hash); bool bReturn = false; //SECURE_HASH* secuHash = g_secuHash[id]; SECURE_HASH* secuHash = g_queryHash[id]; unsigned __int64 uiStartTimer = __rdtsc(); while(secuHash) { if(RtlCompareMemory(secuHash->Hash, hash, HASH_SIZE) == HASH_SIZE) { bReturn = true; break; } if( ((__rdtsc() - uiStartTimer) / (1000 * 1000 * 1000)) >= MAXELPASETIMERFORCHECK ) { WriteSysLog(LOG_TYPE_INFO,L"elapse the large timer 6 seconds\n "); bReturn = false; break; } secuHash = secuHash->next; } releaseMutex(); return true == bReturn? true:false; }
void DynamixelManager::send(uint8_t *data, size_t len) { while (m_mutex) ; acquireMutex(); m_serial->write(data, len); m_serial->flush(); releaseMutex(); }
uint8_t DynamixelManager::read(uint8_t *data, size_t len) { while (m_mutex) ; acquireMutex(); uint8_t ret = m_serial->readBytes(reinterpret_cast<char*>(data), len); releaseMutex(); return ret; }
void GDNetHost::thread_loop() { while (_running) { acquireMutex(); send_messages(); poll_events(); releaseMutex(); } }
void ofxOscReceiver::ProcessMessage( const osc::ReceivedMessage &m, const IpEndpointName& remoteEndpoint ) { // convert the message to an ofxOscMessage ofxOscMessage* ofMessage = new ofxOscMessage(); // set the address ofMessage->setAddress( m.AddressPattern() ); // set the sender ip/host char endpoint_host[ IpEndpointName::ADDRESS_STRING_LENGTH ]; remoteEndpoint.AddressAsString( endpoint_host ); ofMessage->setRemoteEndpoint( endpoint_host, remoteEndpoint.port ); // transfer the arguments for ( osc::ReceivedMessage::const_iterator arg = m.ArgumentsBegin(); arg != m.ArgumentsEnd(); ++arg ) { if ( arg->IsInt32() ) ofMessage->addIntArg( arg->AsInt32Unchecked() ); else if ( arg->IsFloat() ) ofMessage->addFloatArg( arg->AsFloatUnchecked() ); else if ( arg->IsString() ) ofMessage->addStringArg( arg->AsStringUnchecked() ); else if ( arg->IsBlob() ) { osc::Blob blob; arg->AsBlobUnchecked( blob.data, blob.size ); ofMessage->addBlobArg( blob ); } else { assert( false && "message argument is not int, float, string, or blob" ); } } // now add to the queue // at this point we are running inside the thread created by startThread, // so anyone who calls hasWaitingMessages() or getNextMessage() is coming // from a different thread // so we have to practise shared memory management // grab a lock on the queue grabMutex(); // add incoming message on to the queue messages.push_back( ofMessage ); // release the lock releaseMutex(); }
void getSecuTable() { if(g_bSechHash == false) { g_secuHash = g_secuHashDataF; KeWaitForSingleObject(&g_secuHashMutex,Executive,KernelMode,FALSE,NULL); g_queryHash = g_secuHashDataS; releaseMutex(); //DbgPrint(" change white table: g_secuHashDataF \n"); g_bSechHash = true; } else { g_secuHash = g_secuHashDataS; KeWaitForSingleObject(&g_secuHashMutex,Executive,KernelMode,FALSE,NULL); g_queryHash = g_secuHashDataF; releaseMutex(); //DbgPrint(" change white table: g_secuHashDataS \n"); g_bSechHash = false; } }
bool ofxOscReceiver::hasWaitingMessages() { // grab a lock on the queue grabMutex(); // check the length of the queue int queue_length = (int)messages.size(); // release the lock releaseMutex(); // return whether we have any messages return queue_length > 0; }
bool isRestart() { ULONG num=0; KeWaitForSingleObject(&g_secuHashMutex,Executive,KernelMode,FALSE,NULL); for(int i=0 ; i<SECURE_HASH_BUCKET_SIZE ; i++) { //SECURE_HASH* secuHash = g_secuHash[i]; SECURE_HASH* secuHash = g_queryHash[i]; while(secuHash) { num ++; if(num > 30) { releaseMutex(); return true; } secuHash = secuHash->next; } } releaseMutex(); return false; }
void MessageDigest::digest(const char *key, const int key_len, const char *data, const int data_len, unsigned char *md, unsigned int *mdLen) throw (SecurityException) { if (!key) throw SecurityException(INPUT_PARAMETER_IS_NULL, " - key."); if (!data) throw SecurityException(INPUT_PARAMETER_IS_NULL, " - data."); if (!md) throw SecurityException(INPUT_PARAMETER_IS_NULL, " - md."); getMutex(); const EVP_MD *evp_md = EVP_sha256(); HMAC(evp_md, (const void *) key, key_len, (const unsigned char *) data, data_len, (unsigned char *) &md[0], mdLen); releaseMutex(); }
void dpy_display_t::printCpuLoad(uint8_t cpuLoad) { char lcdString[5+1]; #ifdef DEBUG int noChars = #endif sprintf(lcdString, "%5.1f", (double)cpuLoad/2.0); ASSERT(noChars < (int)sizeof(lcdString)); /* Get access to the display, or wait until anybody else has finished respectively. A timeout has been defined which should never elapse, but who knows. In case it should, we simply deny printing. */ if(acquireMutex()) { setCursor(/* col */ 10, /* row */ 1); print(lcdString); /* And release the mutex as soon as possible after writing to the underlaying class has been done. */ releaseMutex(); } } /* End of dpy_display_t::printCpuLoad */
void dpy_display_t::printTime(uint8_t hour, uint8_t min, uint8_t sec) { char lcdString[8+1]; #ifdef DEBUG int noChars = #endif sprintf(lcdString, "%02u:%02u:%02u", hour, min, sec); ASSERT(noChars < (int)sizeof(lcdString)); /* Get access to the display, or wait until anybody else has finished respectively. A timeout has been defined which should never elapse, but who knows. In case it should, we simply deny printing. */ if(acquireMutex()) { /* "16-sizeof" means to display right aligned. */ setCursor(/* col */ 16-(sizeof(lcdString)-1), /* row */ 0); print(lcdString); /* And release the mutex as soon as possible after writing to the underlaying class has been done. */ releaseMutex(); } } /* End of dpy_display_t::printTime */
static int testTSP( const CRYPT_SESSION cryptSession, const BOOLEAN isServer, const BOOLEAN isRecycledConnection, const BOOLEAN useAltHash, const BOOLEAN localSession ) { int status; /* If we're the client, wait for the server to finish initialising */ if( localSession && !isServer && waitMutex() == CRYPT_ERROR_TIMEOUT ) { printf( "Timed out waiting for server to initialise, line %d.\n", __LINE__ ); return( FALSE ); } /* If we're the client, create a message imprint to timestamp */ if( !isServer ) { CRYPT_CONTEXT hashContext; /* Create the hash value to add to the TSP request */ status = cryptCreateContext( &hashContext, CRYPT_UNUSED, useAltHash ? CRYPT_ALGO_SHA256 : \ CRYPT_ALGO_SHA1 ); if( cryptStatusError( status ) ) return( FALSE ); cryptEncrypt( hashContext, "12345678", 8 ); cryptEncrypt( hashContext, "", 0 ); if( isRecycledConnection ) { /* If we're moving further data over an existing connection, delete the message imprint from the previous run */ status = cryptDeleteAttribute( cryptSession, CRYPT_SESSINFO_TSP_MSGIMPRINT ); if( cryptStatusError( status ) ) { printf( "cryptDeleteAttribute() failed with error code %d, " "line %d.\n", status, __LINE__ ); return( FALSE ); } } status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_TSP_MSGIMPRINT, hashContext ); if( cryptStatusError( status ) ) { printf( "cryptSetAttribute() failed with error code %d, line " "%d.\n", status, __LINE__ ); return( FALSE ); } cryptDestroyContext( hashContext ); /* If it's a local session, wait for the server to finish initialising */ if( localSession && waitMutex() == CRYPT_ERROR_TIMEOUT ) { printf( "Timed out waiting for server to initialise, line %d.\n", __LINE__ ); return( FALSE ); } } else { /* We're the server, if this is the first connect tell the client that we're ready to go */ if( localSession && !isRecycledConnection ) releaseMutex(); } /* Activate the session and timestamp the message */ #if TSP_SERVER_NO == 11 cryptSetAttribute( cryptSession, CRYPT_OPTION_NET_READTIMEOUT, 30 ); #endif /* Very slow TSP */ status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_ACTIVE, TRUE ); if( isServer ) printConnectInfo( cryptSession ); if( cryptStatusError( status ) ) { printExtError( cryptSession, isServer ? \ "SVR: Attempt to activate TSP server session" : \ "Attempt to activate TSP client session", status, __LINE__ ); if( !isServer && isServerDown( cryptSession, status ) ) { puts( " (Server could be down, faking it and continuing...)\n" ); cryptDestroySession( cryptSession ); return( CRYPT_ERROR_FAILED ); } cryptDestroySession( cryptSession ); return( FALSE ); } /* There's not much more we can do in the client at this point since the TSP data is only used internally by cryptlib, OTOH if we get to here then we've received a valid response from the TSA so all is OK */ if( !isServer ) { CRYPT_ENVELOPE cryptEnvelope; BYTE buffer[ BUFFER_SIZE ]; int bytesCopied; status = cryptGetAttribute( cryptSession, CRYPT_SESSINFO_RESPONSE, &cryptEnvelope ); if( cryptStatusError( status ) ) { printExtError( cryptSession, "Attempt to process returned " "timestamp", status, __LINE__ ); return( FALSE ); } status = cryptPopData( cryptEnvelope, buffer, BUFFER_SIZE, &bytesCopied ); if( cryptStatusError( status ) ) { printf( "cryptPopData() failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } printf( "Timestamp data size = %d bytes.\n", bytesCopied ); debugDump( "tstinfo", buffer, bytesCopied ); cryptDestroyEnvelope( cryptEnvelope ); } return( TRUE ); }
void Security::generateSessionKey() throw (SecurityException) { int seedSize; unsigned char seed[SEED_SIZE]; #ifndef _WINDOWS // Reads 256 bytes from file /dev/urandom and adds them to // PRNG to use as seed of the random number generator int fd = open("/dev/urandom", O_RDONLY); if (fd < 0) #ifdef MXHPUXPA // HP-UX PA-RISC // /dev/urandom file does not exist on HP-UX PA-RISK. If customers // do not choose to install the HP-UX Strong Random Number Generator // package which can be obtained from this link, provide the following // weak Random Number Generator { seedSize = WEAK_SEED_SIZE; if (seedGenerator((char*)seed) != seedSize) throw SecurityException(UNABLE_TO_SEED_RNG, NULL); } #else // other UNIX platforms throw SecurityException(UNABLE_TO_SEED_RNG, NULL); seedSize = SEED_SIZE; int num = 0; // This can infinitely loops if /dev/urandom does not return 256 bytes // However, it's very very unlikely to happen. while (num != seedSize) { int count = 0; count = read(fd, &seed[num], seedSize - num); if (count > 0) num += count; else if (count == 0) { close(fd); throw SecurityException(FAILED_GENERATE_RANDOM_NUM, NULL); } else //count < 0 { switch (errno) { #ifdef EINTR case EINTR: // Interrupted system call #endif #ifdef EAGAIN case EAGAIN: // Resource temporarily unavailable #endif /* No error, try again */ break; default: close(fd); throw SecurityException(FAILED_GENERATE_RANDOM_NUM, NULL); } } } close(fd); #endif //MXHPUXPA #else // _WINDOWS seedSize=SEED_SIZE; // Get a handle to the DLL module. HINSTANCE hLib = LoadLibrary(TEXT("advapi32.dll")); // Do the following to avoid the overhead of loading the entire CryptoAPI if (hLib) { BOOLEAN (APIENTRY *pfn)(void*, ULONG) = (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(hLib, "SystemFunction036"); if (pfn) { if(!pfn(seed, seedSize)) { throw SecurityException(UNABLE_TO_SEED_RNG, NULL); } } } else { throw SecurityException(FAILED_LOADING_LIB, NULL); } #endif // _WINDOWS getMutex(); RAND_seed((const void *)seed, seedSize); // Check if the PRNG has been seeded with enough randomness if (!RAND_status ()) { releaseMutex(); throw SecurityException(UNABLE_TO_SEED_RNG, NULL); } // Generate 64 bytes of random number using the seed generated above int errcode = RAND_bytes((unsigned char*) &m_pwdKey.data.session_key[0], SESSION_KEYLEN + NONCE_SIZE); releaseMutex(); if (errcode != 1) throw SecurityException(SESSION_KEY_GENERATION_FAILED, NULL); // Get nonce sequence memcpy((char*) &m_nonceSeq, &m_pwdKey.data.nonce[NONCE_RANDOM], NONCE_SEQNUM); if (!m_littleEndian) { m_nonceSeq = swapByteOrderOfLL(m_nonceSeq); // Store the swap bytes back in nonce //intLLong.llVal = m_nonceSeq; memcpy(&m_pwdKey.data.nonce[NONCE_RANDOM], (char*) &m_nonceSeq, NONCE_SEQNUM); } // Set time when session key is generated m_keyTime = get_msts(); }
static int connectRTCS( const CRYPT_SESSION_TYPE sessionType, const BOOLEAN multipleCerts, const BOOLEAN localSession ) { CRYPT_SESSION cryptSession; CRYPT_CERTIFICATE cryptRTCSRequest; char filenameBuffer[ FILENAME_BUFFER_SIZE ]; #ifdef UNICODE_STRINGS wchar_t wcBuffer[ FILENAME_BUFFER_SIZE ]; #endif /* UNICODE_STRINGS */ void *fileNamePtr = filenameBuffer; const BOOLEAN isServer = ( sessionType == CRYPT_SESSION_RTCS_SERVER ) ? \ TRUE : FALSE; int status; printf( "%sTesting %sRTCS session...\n", isServer ? "SVR: " : "", localSession ? "local " : "" ); /* If we're the client, wait for the server to finish initialising */ if( localSession && !isServer && waitMutex() == CRYPT_ERROR_TIMEOUT ) { printf( "Timed out waiting for server to initialise, line %d.\n", __LINE__ ); return( FALSE ); } /* Create the RTCS session */ status = cryptCreateSession( &cryptSession, CRYPT_UNUSED, sessionType ); if( status == CRYPT_ERROR_PARAM3 ) /* RTCS session access not available */ return( CRYPT_ERROR_NOTAVAIL ); if( cryptStatusError( status ) ) { printf( "cryptCreateSession() failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } if( isServer ) { CRYPT_CONTEXT cryptPrivateKey; CRYPT_KEYSET cryptCertStore; if( !setLocalConnect( cryptSession, 80 ) ) return( FALSE ); /* Add the responder private key */ filenameFromTemplate( filenameBuffer, SERVER_PRIVKEY_FILE_TEMPLATE, 1 ); #ifdef UNICODE_STRINGS mbstowcs( wcBuffer, filenameBuffer, strlen( filenameBuffer ) + 1 ); fileNamePtr = wcBuffer; #endif /* UNICODE_STRINGS */ status = getPrivateKey( &cryptPrivateKey, fileNamePtr, USER_PRIVKEY_LABEL, TEST_PRIVKEY_PASSWORD ); if( cryptStatusOK( status ) ) { status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_PRIVATEKEY, cryptPrivateKey ); cryptDestroyContext( cryptPrivateKey ); } if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "SVR: cryptSetAttribute()", status, __LINE__ ) ); /* Add the certificate store that we'll be using to provide revocation information */ status = cryptKeysetOpen( &cryptCertStore, CRYPT_UNUSED, DATABASE_KEYSET_TYPE, CERTSTORE_KEYSET_NAME, CRYPT_KEYOPT_READONLY ); if( status == CRYPT_ERROR_PARAM3 ) { /* This type of keyset access isn't available, return a special error code to indicate that the test wasn't performed, but that this isn't a reason to abort processing */ puts( "SVR: No certificate store available, aborting RTCS " "responder test.\n" ); cryptDestroySession( cryptSession ); return( CRYPT_ERROR_NOTAVAIL ); } if( status == CRYPT_ERROR_OPEN ) { /* The keyset is available, but it hasn't been created yet by an earlier self-test, this isn't a reason to abort processing */ puts( "SVR: Certificate store hasn't been created yet by " "earlier tests, aborting\n RTCS responder test.\n" ); cryptDestroySession( cryptSession ); return( CRYPT_ERROR_NOTAVAIL ); } if( cryptStatusOK( status ) ) { status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_KEYSET, cryptCertStore ); cryptKeysetClose( cryptCertStore ); } if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "SVR: cryptSetAttribute()", status, __LINE__ ) ); /* Tell the client that we're ready to go */ if( localSession ) releaseMutex(); } else { CRYPT_KEYSET cryptKeyset; CRYPT_CERTIFICATE cryptCert = DUMMY_INIT; /* Get the certificate whose status we're checking */ status = cryptKeysetOpen( &cryptKeyset, CRYPT_UNUSED, DATABASE_KEYSET_TYPE, CERTSTORE_KEYSET_NAME, CRYPT_KEYOPT_READONLY ); if( cryptStatusOK( status ) ) { status = cryptGetPublicKey( cryptKeyset, &cryptCert, CRYPT_KEYID_NAME, TEXT( "Test user 1" ) ); cryptKeysetClose( cryptKeyset ); } if( cryptStatusError( status ) ) { printf( "Couldn't read certificate for RTCS status check, error " "code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } /* Create the RTCS request */ if( !initRTCS( &cryptRTCSRequest, cryptCert, localSession ? \ 1 : RTCS_SERVER_NO, multipleCerts ) ) return( FALSE ); cryptDestroyCert( cryptCert ); /* Set up the server information and activate the session. In theory the RTCS request will contain all the information needed for the session so there'd be nothing else to add before we activate it, however many certs contain incorrect server URLs so we set the server name manually if necessary, overriding the value present in the RTCS request (via the certificate) */ status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_REQUEST, cryptRTCSRequest ); if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "cryptSetAttribute()", status, __LINE__ ) ); cryptDestroyCert( cryptRTCSRequest ); if( localSession && !setLocalConnect( cryptSession, 80 ) ) return( FALSE ); #ifdef RTCS_SERVER_NAME if( !localSession ) { printf( "Setting RTCS server to %s.\n", RTCS_SERVER_NAME ); cryptDeleteAttribute( cryptSession, CRYPT_SESSINFO_SERVER_NAME ); status = cryptSetAttributeString( cryptSession, CRYPT_SESSINFO_SERVER_NAME, RTCS_SERVER_NAME, paramStrlen( RTCS_SERVER_NAME ) ); if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "cryptSetAttributeString()", status, __LINE__ ) ); } #endif /* Kludges for incorrect/missing authorityInfoAccess values */ /* Wait for the server to finish initialising */ if( localSession && waitMutex() == CRYPT_ERROR_TIMEOUT ) { printf( "Timed out waiting for server to initialise, line %d.\n", __LINE__ ); return( FALSE ); } } status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_ACTIVE, TRUE ); if( isServer ) printConnectInfo( cryptSession ); if( cryptStatusError( status ) ) { printExtError( cryptSession, isServer ? \ "SVR: Attempt to activate RTCS server session" : \ "Attempt to activate RTCS client session", status, __LINE__ ); if( !isServer && isServerDown( cryptSession, status ) ) { puts( " (Server could be down, faking it and continuing...)\n" ); cryptDestroySession( cryptSession ); return( CRYPT_ERROR_FAILED ); } cryptDestroySession( cryptSession ); return( FALSE ); } /* Obtain the response information */ if( !isServer ) { CRYPT_CERTIFICATE cryptRTCSResponse; status = cryptGetAttribute( cryptSession, CRYPT_SESSINFO_RESPONSE, &cryptRTCSResponse ); if( cryptStatusError( status ) ) { printf( "cryptGetAttribute() failed with error code %d, line " "%d.\n", status, __LINE__ ); return( FALSE ); } printCertInfo( cryptRTCSResponse ); cryptDestroyCert( cryptRTCSResponse ); } /* Clean up */ status = cryptDestroySession( cryptSession ); if( cryptStatusError( status ) ) { printf( "cryptDestroySession() failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } puts( isServer ? "SVR: RTCS server session succeeded.\n" : \ "RTCS client session succeeded.\n" ); return( TRUE ); }
void addSub(Context_t *context, char * text, unsigned long long int pts, unsigned long int milliDuration) { int count = 20; subtitle_printf(50, "index %d\n", writePointer); if(context && context->playback && !context->playback->isPlaying) { subtitle_err("1. aborting ->no playback\n"); return; } if (text == NULL) { subtitle_err("null pointer passed\n"); return; } if (pts == 0) { subtitle_err("pts 0\n"); return; } if (milliDuration == 0) { subtitle_err("duration 0\n"); return; } while (subPuffer[writePointer].text != NULL) { //List is full, wait till we got some free space if(context && context->playback && !context->playback->isPlaying) { subtitle_err("2. aborting ->no playback\n"); return; } /* konfetti: we dont want to block forever here. if no buffer * is available we start ring from the beginning and loose some stuff * which is acceptable! */ subtitle_printf(10, "waiting on free buffer %d - %d (%d) ...\n", writePointer, readPointer, count); usleep(10000); count--; if (count == 0) { subtitle_err("abort waiting on buffer...\n"); break; } } subtitle_printf(20, "from mkv: %s pts:%lld milliDuration:%lud\n",text,pts,milliDuration); getMutex(__LINE__); if (count == 0) { int i; subtitle_err("freeing not delivered data\n"); //Reset all readPointer = 0; writePointer = 0; for (i = 0; i < PUFFERSIZE; i++) { if (subPuffer[i].text != NULL) free(subPuffer[i].text); subPuffer[i].text = NULL; subPuffer[i].pts = 0; subPuffer[i].milliDuration = 0; } } subPuffer[writePointer].text = strdup(text); subPuffer[writePointer].pts = pts; subPuffer[writePointer].milliDuration = milliDuration; writePointer++; if (writePointer == PUFFERSIZE) writePointer = 0; if (writePointer == readPointer) { /* this should not happen, and means that there is nor reader or * the reader has performance probs ;) * the recovery is done at startup of this function - but next time */ subtitle_err("ups something went wrong. no more readers? \n"); } releaseMutex(__LINE__); subtitle_printf(10, "<\n"); }
static int connectOCSP( const CRYPT_SESSION_TYPE sessionType, const BOOLEAN revokedCert, const BOOLEAN multipleCerts, const BOOLEAN localSession ) { CRYPT_SESSION cryptSession; CRYPT_CERTIFICATE cryptOCSPRequest; char filenameBuffer[ FILENAME_BUFFER_SIZE ]; #ifdef UNICODE_STRINGS wchar_t wcBuffer[ FILENAME_BUFFER_SIZE ]; #endif /* UNICODE_STRINGS */ void *fileNamePtr = filenameBuffer; #if OCSP_SERVER_NO == 7 int complianceValue; #endif /* OCSP servers that return broken resposnes */ const BOOLEAN isServer = ( sessionType == CRYPT_SESSION_OCSP_SERVER ) ? \ TRUE : FALSE; int status; printf( "%sTesting %sOCSP session...\n", isServer ? "SVR: " : "", localSession ? "local " : "" ); /* If we're the client, wait for the server to finish initialising */ if( localSession && !isServer && waitMutex() == CRYPT_ERROR_TIMEOUT ) { printf( "Timed out waiting for server to initialise, line %d.\n", __LINE__ ); return( FALSE ); } /* Create the OCSP session */ status = cryptCreateSession( &cryptSession, CRYPT_UNUSED, sessionType ); if( status == CRYPT_ERROR_PARAM3 ) /* OCSP session access not available */ return( CRYPT_ERROR_NOTAVAIL ); if( cryptStatusError( status ) ) { printf( "cryptCreateSession() failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } if( isServer ) { CRYPT_CONTEXT cryptPrivateKey; CRYPT_KEYSET cryptCertStore; if( !setLocalConnect( cryptSession, 80 ) ) return( FALSE ); /* Add the responder private key */ filenameFromTemplate( filenameBuffer, SERVER_PRIVKEY_FILE_TEMPLATE, 1 ); #ifdef UNICODE_STRINGS mbstowcs( wcBuffer, filenameBuffer, strlen( filenameBuffer ) + 1 ); fileNamePtr = wcBuffer; #endif /* UNICODE_STRINGS */ status = getPrivateKey( &cryptPrivateKey, fileNamePtr, USER_PRIVKEY_LABEL, TEST_PRIVKEY_PASSWORD ); if( cryptStatusOK( status ) ) { status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_PRIVATEKEY, cryptPrivateKey ); cryptDestroyContext( cryptPrivateKey ); } if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "SVR: cryptSetAttribute()", status, __LINE__ ) ); /* Add the certificate store that we'll be using to provide revocation information */ status = cryptKeysetOpen( &cryptCertStore, CRYPT_UNUSED, DATABASE_KEYSET_TYPE, CERTSTORE_KEYSET_NAME, CRYPT_KEYOPT_READONLY ); if( status == CRYPT_ERROR_PARAM3 ) { /* This type of keyset access isn't available, return a special error code to indicate that the test wasn't performed, but that this isn't a reason to abort processing */ puts( "SVR: No certificate store available, aborting OCSP " "responder test.\n" ); cryptDestroySession( cryptSession ); return( CRYPT_ERROR_NOTAVAIL ); } if( cryptStatusOK( status ) ) { status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_KEYSET, cryptCertStore ); cryptKeysetClose( cryptCertStore ); } if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "SVR: cryptSetAttribute()", status, __LINE__ ) ); /* Tell the client that we're ready to go */ if( localSession ) releaseMutex(); } else { /* Create the OCSP request */ if( !initOCSP( &cryptOCSPRequest, localSession ? 1 : OCSP_SERVER_NO, FALSE, revokedCert, multipleCerts, CRYPT_SIGNATURELEVEL_NONE, CRYPT_UNUSED ) ) return( FALSE ); /* Set up the server information and activate the session. In theory the OCSP request will contain all the information needed for the session so there'd be nothing else to add before we activate it, however many certs contain incorrect server URLs so we set the server name manually if necessary, overriding the value present in the OCSP request (via the certificate) */ status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_REQUEST, cryptOCSPRequest ); if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "cryptSetAttribute()", status, __LINE__ ) ); cryptDestroyCert( cryptOCSPRequest ); if( localSession && !setLocalConnect( cryptSession, 80 ) ) return( FALSE ); #ifdef OCSP_SERVER_NAME if( !localSession ) { printf( "Setting OCSP server to %s.\n", OCSP_SERVER_NAME ); cryptDeleteAttribute( cryptSession, CRYPT_SESSINFO_SERVER_NAME ); status = cryptSetAttributeString( cryptSession, CRYPT_SESSINFO_SERVER_NAME, OCSP_SERVER_NAME, paramStrlen( OCSP_SERVER_NAME ) ); if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "cryptSetAttributeString()", status, __LINE__ ) ); } #endif /* Kludges for incorrect/missing authorityInfoAccess values */ if( OCSP_SERVER_NO == 1 || localSession ) { /* The cryptlib server doesn't handle the weird v1 certIDs */ status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_VERSION, 2 ); if( cryptStatusError( status ) ) return( attrErrorExit( cryptSession, "cryptSetAttribute()", status, __LINE__ ) ); } #if OCSP_SERVER_NO == 7 /* Some OCSP server's responses are broken so we have to turn down the compliance level to allow them to be processed */ cryptGetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL, &complianceValue ); cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL, CRYPT_COMPLIANCELEVEL_OBLIVIOUS ); #endif /* OCSP servers that return broken resposnes */ /* Wait for the server to finish initialising */ if( localSession && waitMutex() == CRYPT_ERROR_TIMEOUT ) { printf( "Timed out waiting for server to initialise, line %d.\n", __LINE__ ); return( FALSE ); } } status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_ACTIVE, TRUE ); #if OCSP_SERVER_NO == 7 /* Restore normal certificate processing */ cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL, complianceValue ); #endif /* OCSP servers that return broken resposnes */ if( isServer ) printConnectInfo( cryptSession ); if( cryptStatusError( status ) ) { printExtError( cryptSession, isServer ? \ "SVR: Attempt to activate OCSP server session" : \ "Attempt to activate OCSP client session", status, __LINE__ ); #if OCSP_SERVER_NO == 5 if( status == CRYPT_ERROR_SIGNATURE ) { char errorMessage[ 512 ]; int errorMessageLength; status = cryptGetAttributeString( cryptSession, CRYPT_ATTRIBUTE_ERRORMESSAGE, errorMessage, &errorMessageLength ); if( cryptStatusOK( status ) && errorMessageLength >= 29 && \ !memcmp( errorMessage, "OCSP response doesn't contain", 29 ) ) { cryptDestroySession( cryptSession ); puts( " (Verisign's OCSP responder sends broken responses, " "continuing...)\n" ); return( CRYPT_ERROR_FAILED ); } } #endif /* Verisign's broken OCSP responder */ if( !isServer && isServerDown( cryptSession, status ) ) { puts( " (Server could be down, faking it and continuing...)\n" ); cryptDestroySession( cryptSession ); return( CRYPT_ERROR_FAILED ); } cryptDestroySession( cryptSession ); return( FALSE ); } /* Obtain the response information */ if( !isServer ) { CRYPT_CERTIFICATE cryptOCSPResponse; status = cryptGetAttribute( cryptSession, CRYPT_SESSINFO_RESPONSE, &cryptOCSPResponse ); if( cryptStatusError( status ) ) { printf( "cryptGetAttribute() failed with error code %d, line " "%d.\n", status, __LINE__ ); return( FALSE ); } printCertInfo( cryptOCSPResponse ); cryptDestroyCert( cryptOCSPResponse ); } /* There are so many weird ways to delegate trust and signing authority mentioned in the OCSP RFC without any indication of which one implementors will follow that we can't really perform any sort of automated check since every responder seems to interpret this differently, and many require manual installation of responder certs in order to function */ #if 0 status = cryptCheckCert( cryptOCSPResponse , CRYPT_UNUSED ); if( cryptStatusError( status ) ) return( attrErrorExit( cryptOCSPResponse , "cryptCheckCert()", status, __LINE__ ) ); #endif /* 0 */ /* Clean up */ status = cryptDestroySession( cryptSession ); if( cryptStatusError( status ) ) { printf( "cryptDestroySession() failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } puts( isServer ? "SVR: OCSP server session succeeded.\n" : \ "OCSP client session succeeded.\n" ); return( TRUE ); }
static int suitebServer( const int testNo, const char *hostName, const int port, const int flags, const BOOLEAN isServerTest ) { CRYPT_SESSION cryptSession; CRYPT_CONTEXT privateKey; const SUITEB_TEST_INFO *testInfoPtr = isServerTest ? \ &serverTestInfo[ testNo ] : &clientTestInfo[ testNo ]; const char *testName = testInfoPtr->testName; const BOOLEAN isLoopbackTest = \ ( !strcmp( hostName, "localhost" ) && port == 0 ) ? TRUE : FALSE; const BOOLEAN sendHTTP = \ ( flags & TESTFLAG_SENDHTTPREQ ) ? TRUE : FALSE; char filenameBuffer[ FILENAME_BUFFER_SIZE ]; #ifdef UNICODE_STRINGS wchar_t wcBuffer[ FILENAME_BUFFER_SIZE ]; #endif /* UNICODE_STRINGS */ SPECIAL_HANDLING_TYPE handlingTypeAlt = SPECIAL_NONE; void *fileNamePtr = filenameBuffer; int status; /* Make sure that we've been given a valid test number to run */ if( isServerTest ) { if( testNo < SUITEB_FIRST_SERVER || testNo > SUITEB_LAST_SERVER ) return( FALSE ); } else { if( testNo < SUITEB_FIRST_CLIENT || testNo > SUITEB_LAST_CLIENT ) return( FALSE ); } /* If it's an alias for another test, select the base test */ if( testInfoPtr->aliasTestName != NULL ) { handlingTypeAlt = testInfoPtr->handlingType; testInfoPtr = findAliasTest( isServerTest ? \ &serverTestInfo[ 1 ] : &clientTestInfo[ 1 ], testInfoPtr->aliasTestName ); if( testInfoPtr == NULL ) { assert( 0 ); return( FALSE ); } } /* Acquire the init mutex */ acquireMutex(); cryptSuiteBTestConfig( SUITEB_TEST_NONE ); /* Clear any custom config */ printf( "SVR: Running Suite B server " ); if( flags & TESTFLAG_GENERIC ) printf( "as generic test server.\n" ); else printf( "with test %s.\n", testInfoPtr->testName ); /* Create the SSL/TLS session */ status = cryptCreateSession( &cryptSession, CRYPT_UNUSED, CRYPT_SESSION_SSL_SERVER ); if( status == CRYPT_ERROR_PARAM3 ) /* SSL/TLS session access not available */ return( CRYPT_ERROR_NOTAVAIL ); if( cryptStatusError( status ) ) { printf( "cryptCreateSession() failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_VERSION, 3 ); if( cryptStatusOK( status ) && testInfoPtr->serverOptions != 0 ) { status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_SSL_OPTIONS, testInfoPtr->serverOptions ); } if( testInfoPtr->clientAuthKeySizeBits > 0 ) { /* Tell the test code to expect a client certificate */ cryptSuiteBTestConfig( 1000 ); } if( cryptStatusError( status ) ) { printf( "cryptSetAttribute() failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } /* Set up the server information */ if( isLoopbackTest ) { /* We're running the loopback test, set up a local connect */ if( !setLocalConnect( cryptSession, 443 ) ) return( FALSE ); } else { status = cryptSetAttributeString( cryptSession, CRYPT_SESSINFO_SERVER_NAME, hostName, strlen( hostName ) ); if( cryptStatusOK( status ) && port != 0 && port != 443 ) status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_SERVER_PORT, port ); if( cryptStatusError( status ) ) { printf( "cryptSetAttribute()/cryptSetAttributeString() failed " "with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } } /* Set any custom server configuration that may be required. We have to do this before we set the server key since some of the tests involve invalid server keys */ switch( testInfoPtr->handlingType ) { case SPECIAL_SVR_INVALIDCURVE: /* Server sends non-Suite B curve */ status = cryptSuiteBTestConfig( SUITEB_TEST_SVRINVALIDCURVE ); break; case SPECIAL_BOTH_SUPPCURVES: /* Client must send both P256 and P384 in supported curves extension */ status = cryptSuiteBTestConfig( SUITEB_TEST_BOTHCURVES ); break; case SPECIAL_BOTH_SIGALGO: /* Client must send both SHA256 and SHA384 in signature algos extension */ status = cryptSuiteBTestConfig( SUITEB_TEST_BOTHSIGALGOS ); break; } if( cryptStatusError( status ) ) { printf( "Custom config set failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } /* Add the server key */ filenameFromTemplate( filenameBuffer, SERVER_ECPRIVKEY_FILE_TEMPLATE, testInfoPtr->serverKeySizeBits ); #ifdef UNICODE_STRINGS mbstowcs( wcBuffer, filenameBuffer, strlen( filenameBuffer ) + 1 ); fileNamePtr = wcBuffer; #endif /* UNICODE_STRINGS */ status = getPrivateKey( &privateKey, fileNamePtr, USER_PRIVKEY_LABEL, TEST_PRIVKEY_PASSWORD ); if( cryptStatusOK( status ) ) { status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_PRIVATEKEY, privateKey ); cryptDestroyContext( privateKey ); } if( cryptStatusError( status ) ) { printf( "SVR: cryptSetAttribute/AttributeString() failed with error " "code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } /* For the loopback test we also increase the connection timeout to a higher-than-normal level, since this gives us more time for tracing through the code when debugging */ cryptSetAttribute( cryptSession, CRYPT_OPTION_NET_CONNECTTIMEOUT, 120 ); /* Tell the client that we're ready to go */ releaseMutex(); /* Activate the server session */ status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_ACTIVE, TRUE ); if( ( testInfoPtr->result && !cryptStatusOK( status ) ) || \ ( !testInfoPtr->result && !cryptStatusError( status ) ) ) { if( testInfoPtr->result ) printf( "SVR: Test %s failed, should have succeeded.\n", testName ); else printf( "SVR: Test %s succeeded, should have failed.\n", testName ); if( cryptStatusError( status ) ) { printExtError( cryptSession, "SVR: Failure reason is:", status, __LINE__ ); } cryptDestroySession( cryptSession ); return( FALSE ); } /* Perform any custom post-activation checking that may be required */ if( testInfoPtr->handlingType != 0 || handlingTypeAlt != 0 ) { const SPECIAL_HANDLING_TYPE handlingType = \ ( handlingTypeAlt != 0 ) ? handlingTypeAlt : \ testInfoPtr->handlingType; BYTE buffer[ 1024 ]; int length; switch( handlingType ) { case SPECIAL_CLI_TLSALERT: status = cryptGetAttributeString( cryptSession, CRYPT_ATTRIBUTE_ERRORMESSAGE, buffer, &length ); if( cryptStatusError( status ) || \ memcmp( buffer, "Received TLS alert", 18 ) ) { printf( "SVR: Test %s should have returned a TLS alert " "but didn't.\n", testName ); return( FALSE ); } break; } } /* If we're being asked to send HTTP data, return a basic HTML page */ if( sendHTTP ) { const char serverReply[] = \ "HTTP/1.0 200 OK\n" "Date: Fri, 7 September 2010 20:02:07 GMT\n" "Server: cryptlib Suite B test\n" "Content-Type: text/html\n" "Connection: Close\n" "\n" "<!DOCTYPE HTML SYSTEM \"html.dtd\">\n" "<html>\n" "<head>\n" "<title>cryptlib Suite B test page</title>\n" "<body>\n" "Test message from the cryptlib Suite B server.<p>\n" "</body>\n" "</html>\n"; char buffer[ FILEBUFFER_SIZE ]; int bytesCopied; /* Print the text of the request from the client */ status = cryptPopData( cryptSession, buffer, FILEBUFFER_SIZE, &bytesCopied ); if( cryptStatusError( status ) ) { printExtError( cryptSession, "SVR: Attempt to read data from " "client", status, __LINE__ ); cryptDestroySession( cryptSession ); return( FALSE ); } buffer[ bytesCopied ] = '\0'; printf( "---- Client sent %d bytes ----\n", bytesCopied ); puts( buffer ); puts( "---- End of output ----" ); /* Send a reply */ status = cryptPushData( cryptSession, serverReply, sizeof( serverReply ) - 1, &bytesCopied ); if( cryptStatusOK( status ) ) status = cryptFlushData( cryptSession ); if( cryptStatusError( status ) || \ bytesCopied != sizeof( serverReply ) - 1 ) { printExtError( cryptSession, "Attempt to send data to client", status, __LINE__ ); cryptDestroySession( cryptSession ); return( FALSE ); } } /* Clean up */ status = cryptDestroySession( cryptSession ); if( cryptStatusError( status ) ) { printf( "cryptDestroySession() failed with error code %d, line %d.\n", status, __LINE__ ); return( FALSE ); } printf( "SVR: Suite B server test %s succeeded.\n", testName ); return( TRUE ); }