void NetlibUPnPCleanup(void*) { if (db_get_b(NULL, "Netlib", "NLEnableUPnP", 1) == 0) // upnp is disabled globally, no need for a cleanup return; { int incoming = 0; mir_cslock lck(csNetlibUser); for (int i=0; i < netlibUser.getCount(); i++) if (netlibUser[i]->user.flags & NUF_INCOMING) { incoming = 1; break; } if (!incoming) return; } if (findUPnPGateway()) { char* szData = (char*)alloca(4096); char buf[50], lip[50]; unsigned i, j = 0, k, num = 100; WORD ports[30]; strcpy(lip, inet_ntoa(locIP.sin_addr)); WaitForSingleObject(portListMutex, INFINITE); if (httpTransact(szCtlUrl, szData, 4096, "PortMappingNumberOfEntries", ControlQuery) == 200 && txtParseParam(szData, "QueryStateVariableResponse", "<return>", "<", buf, sizeof(buf))) num = atol(buf); for (i=0; i<num && !Miranda_Terminated(); i++) { mir_snprintf(szData, 4096, get_port_mapping, i); ReleaseMutex(portListMutex); WaitForSingleObject(portListMutex, INFINITE); if (httpTransact(szCtlUrl, szData, 4096, "GetGenericPortMappingEntry", ControlAction) != 200) break; if (!txtParseParam(szData, "<NewPortMappingDescription", ">", "<", buf, sizeof(buf)) || strcmp(buf, "Miranda") != 0) continue; if (!txtParseParam(szData, "<NewInternalClient", ">", "<", buf, sizeof(buf)) || strcmp(buf, lip) != 0) continue; if (txtParseParam(szData, "<NewExternalPort", ">", "<", buf, sizeof(buf))) { WORD mport = (WORD)atol(buf); if (j >= SIZEOF(ports)) break; for (k = 0; k<numports; ++k) if (portList[k] == mport) break; if (k >= numports) ports[j++] = mport; } } ReleaseMutex(portListMutex); for (i=0; i<j && !Miranda_Terminated(); i++) NetlibUPnPDeletePortMapping(ports[i], "TCP"); } }
//=========================================================================== extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd ) { HANDLE hMutex; int iRet; HRESULT hRes; TCHAR szTokens[] = _T("-/"); // Check for another instance hMutex = OpenMutex( SYNCHRONIZE, // requested access (lowest possible) FALSE, // allow inheritance (does not matter) x_szMutexName); // unique name if(hMutex){ MessageBox( NULL, "Cannot start the application because another instance is already running.\n", g_szAppTitile, MB_OK | MB_ICONERROR ); return 1; } hMutex = CreateMutex( NULL, // default security TRUE, // obtain ownership x_szMutexName); // unique name if(!hMutex){ MessageBox( NULL, "Cannot create application mutex.\n", g_szAppTitile, MB_OK | MB_ICONERROR ); return 1; } hRes = CoInitialize(NULL); // single-threaded apartment _ASSERTE(SUCCEEDED(hRes)); _Module.Init(ObjectMap, hInstance, &LIBID_CP_DISPLAYLib); hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE); _ASSERTE(SUCCEEDED(hRes)); lpCmdLine = GetCommandLine(); //this line is necessary for _ATL_MIN_CRT // Parse the command line for options LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens); while (lpszToken != NULL) { if (lstrcmpi(lpszToken, "UnregServer")==0) { _Module.UpdateRegistryFromResource(IDR_CP_Display, FALSE); iRet = _Module.UnregisterServer(TRUE); if( iRet != 0 ) { MessageBox( NULL, "Error: Can't unregister server. UnregisterServer() failed.", g_szAppTitile, MB_OK); } else { MessageBox( NULL, "Success: the server is unregistered.", g_szAppTitile, MB_OK); } _Module.Term(); CoUninitialize(); return iRet; } if (lstrcmpi(lpszToken, "RegServer")==0) { _Module.UpdateRegistryFromResource(IDR_CP_Display, TRUE); iRet = _Module.RegisterServer(TRUE); if( iRet != 0 ) { MessageBox( NULL, "Error: Can't register server. g_RegisterCOM() failed.", g_szAppTitile, MB_OK); } else { MessageBox( NULL, "Success: the server is registered.", g_szAppTitile, MB_OK); } _Module.Term(); CoUninitialize(); return iRet; } lpszToken = FindOneOf(lpszToken, szTokens); } // while there are tokens CP_printfCreate( g_szAppTitile ); // Creates log window (console) CP_printf("%s\n", g_szVersion ); CP_printf("----------------------------------------\n"); CP_printf("Build options:\n\n"); //~~~~~~~~~~~~~~~~~ #ifdef _DEBUG CP_printf("Debug version.\n"); #else CP_printf("Release version. \n\n"); #endif // #ifdef _DEBUG //~~~~~~~~~~~~~~~~~ CP_printf("SET_FULLSCREEN_MODE: %d\n", SET_FULLSCREEN_MODE); CP_printf("DEBUG_THRESHOLD: %d\n", DEBUG_THRESHOLD); CP_printf("----------------------------------------\n"); srand( (unsigned)123 ); try { if ( !g_StartGL_Engine( hInstance, nShowCmd ) ){ g_MainLoop(); } } catch( ... ) { MessageBox( NULL, "Exception!!! SOS!!! The program will shut down!", g_szAppTitile, MB_OK | MB_ICONERROR ); exit(1); } CP_printf("N objects before quitting: %d\n", _Module.GetLockCount() ); _Module.RevokeClassObjects(); Sleep(COM_THREAD_WAIT_MS); //wait for any threads to finish // WrapUp _Module.Term(); CoUninitialize(); // Left-over objects are deleted in CoUninitialize(). Since they call RequestUpdate // in the destuctor, we have to delete GL_Window after CoUninitialize() g_StopGL_Engine( ); InvalidateRect(NULL, NULL, TRUE); // redraw the desktop Sleep(5000); // show log window for 5 sec before quitting CP_printfDestroy( ); // Kills log window (console) ReleaseMutex(hMutex); return 0; }
static int pthread_mutex_unlock(pthread_mutex_t *mutex) { return ReleaseMutex(*mutex) == 0 ? -1 : 0; }
/* * Release a lock previously held. */ VOID lock_release( LOCK * lock ) { if( lock != NULL ) { ReleaseMutex( lock->handle ); } }
int Z_Free(void *pvAddress) #define Z_FREE_RETURN(x) return (x) #endif { #ifdef _WINDOWS if (!s_Initialized) return; #endif assert(s_Initialized); #ifdef _DEBUG // check the header magic ZoneDebugHeader* debug_header = (ZoneDebugHeader*)pvAddress - 1; if (*debug_header != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Free(): Corrupt zone header!"); Z_FREE_RETURN( 0 ); } ZoneHeader* header = (ZoneHeader*)debug_header - 1; // check the footer magic ZoneDebugFooter* debug_footer = (ZoneDebugFooter*)((char*)pvAddress + Z_GetSize(header)); if (*debug_footer != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Free(): Corrupt zone footer!"); Z_FREE_RETURN( 0 ); } #else ZoneHeader* header = (ZoneHeader*)pvAddress - 1; #endif memtag_t tag = Z_GetTag(header); if (tag != TAG_STATIC) { #ifndef _GAMECUBE WaitForSingleObject(s_Mutex, INFINITE); #endif // Determine size of header and footer int header_size = sizeof(ZoneHeader); int align_size = Z_GetAlign(header); int footer_size = 0; int data_size = Z_GetSize(header); if (Z_IsTagLinked(tag)) { header_size += sizeof(ZoneLinkHeader); } if (Z_IsTagTemp(tag)) { footer_size += align_size; } else { header_size += align_size; } #ifdef _DEBUG header_size += sizeof(ZoneDebugHeader); footer_size += sizeof(ZoneDebugFooter); #endif int real_size = data_size + header_size + footer_size; // Update the stats s_Stats.m_SizeAlloc -= data_size; s_Stats.m_OverheadAlloc -= header_size + footer_size; s_Stats.m_SizesPerTag[tag] -= data_size; s_Stats.m_CountAlloc--; s_Stats.m_CountsPerTag[tag]--; // Delink block if (Z_IsTagLinked(tag)) { ZoneLinkHeader* linked = (ZoneLinkHeader*)header - 1; if (linked == s_LinkBase) { s_LinkBase = linked->m_Next; if (s_LinkBase) { s_LinkBase->m_Prev = NULL; } } else { if (linked->m_Next) { linked->m_Next->m_Prev = linked->m_Prev; } linked->m_Prev->m_Next = linked->m_Next; } assert(Z_ValidateLinks()); } // Clear the block header for safety *header = 0; // Add block to free list ZoneFreeBlock* nblock = NULL; if (real_size < sizeof(ZoneFreeBlock)) { // Not enough space in block to put free information -- // use overflow buffer. nblock = Z_GetOverflowBlock(); if (nblock == NULL) { Z_Details_f(); Com_Error(ERR_FATAL, "Zone free overflow buffer overflowed!"); } } else { // Place free information in block nblock = (ZoneFreeBlock*)((char*)pvAddress - header_size); } nblock->m_Address = (unsigned int)pvAddress - header_size; nblock->m_Size = real_size; Z_LinkFreeBlock(nblock); // Coalesce any adjacent free blocks Z_Coalasce(nblock); #ifndef _GAMECUBE ReleaseMutex(s_Mutex); #endif } Z_FREE_RETURN( 0 ); }
int LocalWin32Socket::Read( void* buf, size_t minSize, size_t maxSize, time_t timeout ) { time_t start = 0; char* dst = (char*) buf; size_t size = 0; lastError = EC_OK; if ( timeout != WAIT_FOREVER ) { start = time( NULL ); timeout *= 1000; // convert seconds to miliseconds } while ( size < minSize && state == SS_OPEN ) { recvBuffer->recvWaitFlag = true; size_t begin = recvBuffer->dataBeg; size_t end = recvBuffer->dataEnd; size_t recvSize = (begin <= end) ? end - begin : sizeof(recvBuffer->dataBuf) - begin; if (recvSize > 0) { recvBuffer->recvWaitFlag = false; if ( recvSize >= maxSize ) { memcpy( dst, &recvBuffer->dataBuf[begin], maxSize ); begin += maxSize; size += maxSize; } else { memcpy( dst, &recvBuffer->dataBuf[begin], recvSize ); begin += recvSize; dst += recvSize; size += recvSize; maxSize -= recvSize; } recvBuffer->dataBeg = (begin == sizeof(recvBuffer->dataBuf)) ? 0 : begin; if (recvBuffer->sendWaitFlag) { SetEvent(signalHandle[RTR]); } } else { HANDLE h[2]; h[0] = signalHandle[RD]; h[1] = mutexHandle; int rc = WaitForMultipleObjects( 2, h, false, timeout ); recvBuffer->recvWaitFlag = false; if ( rc != WAIT_OBJECT_0 ) { if ( rc == WAIT_OBJECT_0+1 || rc == WAIT_ABANDONED+1) { SetStreamState( ios::failbit | ios::eofbit ); lastError = EC_BROKEN_PIPE; ReleaseMutex(mutexHandle); } else if ( rc == WAIT_TIMEOUT ) { return (size); } else { SetStreamState( ios::failbit ); lastError = GetLastError(); } return (-1); } if ( timeout != WAIT_FOREVER ) { time_t now = time( NULL ); timeout = timeout >= (now - start)*1000 ? timeout - (now - start)*1000 : 0; } } } return (size < minSize ? -1 : (int) size); }
/*************************************************************** 【函数功能】: 发送Get报文 【输 入】: addr:模块地址;cmd:get命令; 【输 出】: 执行结果:0正确;-1错误;-2发送失败; 【说 明】: 在timer中被调用。直接通过串口发送。 ***************************************************************/ int CSensor::SendGetFrame(char addr, char cmd) { UINT sum = 0; int i; if(!m_bPortOpened) return -1; /**********************************************/ WaitForSingleObject(m_hMutex,1000); // 占用串口发送资源 m_sCmd.send = (BYTE)cmd; m_sCmd.stat = STAT_SENSOR_T2T; m_sCmd.addr = (BYTE)addr; switch ((BYTE)cmd) { case CMD_GET_TDM_INFO: m_sCmd.ack = CMD_RET_TDM_INFO; // 正常应该回复此命令 break; case CMD_GET_TDM_DATA: m_sCmd.ack = CMD_RET_TDM_DATA; // 正常应该回复此命令 break; case CMD_GET_US_DATA: m_sCmd.ack = CMD_RET_US_DATA; // 正常应该回复此命令 break; case CMD_GET_US_ERRCODE: m_sCmd.ack = CMD_RET_US_ERRCODE;// 正常应该回复此命令 break; case CMD_GET_IO_BOMA: m_sCmd.ack = CMD_RET_IO_BOMA; // 正常应该回复此命令 break; case CMD_GET_IO_MODE: m_sCmd.ack = CMD_RET_IO_MODE; // 正常应该回复此命令 break; default: break; } // 准备发送CMD_GET_US_DATA读取超声波测距值 char buf[8] = {0}; buf[0] = 0xAA; buf[1] = 0x55; buf[2] = 4; buf[3] = cmd; buf[4] = addr; buf[5] = ADDR_MASTER_DEFAULT; for(i=0; i<4; i++) { sum += (BYTE)buf[i+2]; } buf[6] = (BYTE)(sum >> 8); buf[7] = (BYTE)sum; // 直接通过串口发送,保证时间精度 i = sio_write(m_iPort, buf, 8); // 持续时间大约10us m_sCmd.stat = STAT_SENSOR_T2R; ReleaseMutex(m_hMutex); /**********************************************/ if(i != 8) return -2; return 0; }
int SelectHostIPsByHostName(char * hostName, list<string> * v){ char query[300]; char * fixedInsertStr; unsigned int len; int holder; MYSQL_RES * results; MYSQL_ROW row; unsigned int numRows = 0, numFields = 0; MYSQL * conn; if(hostName == NULL || strlen(hostName) == 0){ printf("SelectHostIPsByHostName(): hostName passed was null\n"); return GENERIC_ERROR; } fixedInsertStr = "SELECT ip_str FROM Hosts WHERE hostName like '%s'"; len = sprintf_s(query, 300, fixedInsertStr, hostName); if(WaitForSingleObject(mysqlMutex, INFINITE) != WAIT_OBJECT_0){ printf("SelectHostIPsByHostName: Couldn't acquire mutex. Returning\n"); return GENERIC_ERROR; } conn = OpenDatabaseConnection(gffServerDBName); if(conn == NULL){ printf("SelectHostIPsByHostName(): OpenDatabaseConnection(gffServerDBName) failed\n"); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } ////////////////////////////////// if(0 != mysql_real_query(conn, query, len)){ holder = CheckError(conn,mysql_errno(conn)); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, holder); } results = mysql_store_result(conn); if(results == NULL){ printf("SelectHostIPsByHostName(): mysql_use_result failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } numRows = (unsigned int)mysql_num_rows(results); if(numRows == 0){ mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, NO_RESULTS_FOUND); } //This function expects that the results will be a single column of strings for(unsigned int i = 0; i < numRows; i++){ row = mysql_fetch_row(results); if(row == NULL){ printf("SelectHostIPsByHostName(): mysql_fetch_row failed\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } string temp = (string)row[0]; v->push_back(temp); } mysql_free_result(results); ////////////////////////////////// CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("SelectHostIPsByHostName(): Couldn't release mutex. Exiting thread\n"); return GENERIC_ERROR; } return GENERIC_SUCCESS; }
//TODO: Document me int SelectAllHostsToMeasureForPolling(int tolerance, queue<int> * q){ int hostID; MYSQL_RES * results; MYSQL_ROW row; unsigned int len; int holder; unsigned int numRows = 0, numFields = 0; char query[200]; MYSQL * conn; time_t rawtime; time (&rawtime); unsigned int tempTimeStamp = (unsigned int)rawtime; tempTimeStamp = tempTimeStamp - (unsigned int)tolerance; if(WaitForSingleObject(mysqlMutex, INFINITE) != WAIT_OBJECT_0){ printf("SelectAllHostsToMeasureForPolling: Couldn't acquire mutex. Returning\n"); return GENERIC_ERROR; } conn = OpenDatabaseConnection(gffServerDBName); if(conn == NULL){ printf("SelectAllHostsToMeasureForPolling: OpenDatabaseConnection(gffServerDBName) failed\n"); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } len = sprintf_s(query, 200, "SELECT hostID FROM HostsToMeasure WHERE readiness = %u and lastTimeMeasurementRequested < %u",READY, tempTimeStamp); ////////////////////////////////// if(0 != mysql_real_query(conn, query, len)){ holder = CheckError(conn,mysql_errno(conn)); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, holder); } results = mysql_store_result(conn); if(results == NULL){ printf("SelectAllHostsToMeasureForPolling: mysql_use_result failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } numRows = (unsigned int)mysql_num_rows(results); if(numRows == 0){//Will fail here if an empty set is returned mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, NO_RESULTS_FOUND); } //This function expects that the results will be a single column of integers (IDs) for(unsigned int i = 0; i < numRows; i++){ row = mysql_fetch_row(results); if(row == NULL){ printf("SelectAllHostsToMeasureForPolling: mysql_fetch_row failed\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } hostID = strtoul(row[0], NULL, 10); q->push(hostID); } mysql_free_result(results); ////////////////////////////////// CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("SelectAllHostsToMeasureForPolling: Couldn't release mutex. Exiting thread\n"); return GENERIC_ERROR; } return GENERIC_SUCCESS; }
int SelectAllHostsToMeasure(queue<string> * q, queue<int> * r){ MYSQL_RES * results; MYSQL_ROW row; //really a char ** string hostIP; int hostID; char * endptr = ""; char * fixedInsertStr; unsigned int len; int holder; unsigned int numRows = 0, numFields = 0; MYSQL * conn; fixedInsertStr = "SELECT Hosts.id, Hosts.ip_str FROM Hosts INNER JOIN HostsToMeasure WHERE Hosts.id = HostsToMeasure.hostID"; len = strlen(fixedInsertStr); if(WaitForSingleObject(mysqlMutex, INFINITE) != WAIT_OBJECT_0){ printf("SelectAllHostsToMeasure: Couldn't acquire mutex. Returning\n"); return GENERIC_ERROR; } conn = OpenDatabaseConnection(gffServerDBName); if(conn == NULL){ printf("SelectAllHostsToMeasure: OpenDatabaseConnection(gffServerDBName) failed\n"); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } ////////////////////////////////// if(0 != mysql_real_query(conn, fixedInsertStr, len)){ holder = CheckError(conn,mysql_errno(conn)); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, holder); } results = mysql_store_result(conn); if(results == NULL){ printf("SelectAllHostsToMeasure: mysql_use_result failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } numRows = (unsigned int)mysql_num_rows(results); if(numRows == 0){//Will fail here if an empty set is returned mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, NO_RESULTS_FOUND); } //This function expects that the results will be a single column of integers (IDs) for(unsigned int i = 0; i < numRows; i++){ row = mysql_fetch_row(results); if(row == NULL){ printf("SelectAllHostsToMeasure: mysql_fetch_row failed\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } hostID = strtoul(row[0], &endptr, 10); r->push(hostID); q->push(row[1]); } holder = GENERIC_SUCCESS; mysql_free_result(results); ////////////////////////////////// CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("SelectAllHostsToMeasure: Couldn't release mutex. Exiting thread\n"); return GENERIC_ERROR; } return holder; }
//Document me int SelectModulesToMeasure(vector<string> * v){ MYSQL_RES * results; MYSQL_ROW row; char * fixedInsertStr; unsigned int len; int holder; unsigned int numRows = 0, numFields = 0; MYSQL * conn; fixedInsertStr = "SELECT moduleName FROM ModulesToMeasure"; len = strlen(fixedInsertStr); if(WaitForSingleObject(mysqlMutex, INFINITE) != WAIT_OBJECT_0){ printf("SelectModulesToMeasure: Couldn't acquire mutex. Returning\n"); return GENERIC_ERROR; } conn = OpenDatabaseConnection(gffServerDBName); if(conn == NULL){ printf("SelectModulesToMeasure: OpenDatabaseConnection(gffServerDBName) failed\n"); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } ////////////////////////////////// if(0 != mysql_real_query(conn, fixedInsertStr, len)){ holder = CheckError(conn,mysql_errno(conn)); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, holder); } results = mysql_store_result(conn); if(results == NULL){ printf("SelectModulesToMeasure: mysql_use_result failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } numRows = (unsigned int)mysql_num_rows(results); if(numRows == 0){ mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, NO_RESULTS_FOUND); } //This function expects that the results will be a single column of wstrings for(unsigned int i = 0; i < numRows; i++){ row = mysql_fetch_row(results); if(row == NULL){ printf("SelectModulesToMeasure: mysql_fetch_row failed\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } string temp = (string)row[0]; v->push_back(temp); } mysql_free_result(results); ////////////////////////////////// CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("SelectModulesToMeasure: Couldn't release mutex. Exiting thread\n"); return GENERIC_ERROR; } return GENERIC_SUCCESS; }
int SelectDataSetForLimitCalculations(unsigned int countFromTimeInSeconds, unsigned int count, queue<unsigned int> * q){ MYSQL_RES * results; MYSQL_ROW row; char query[300]; char * fixedInsertStr; unsigned int len; MYSQL * conn; unsigned int counter = 0; fixedInsertStr = "SELECT meRTTInMicroseconds FROM MeasurementEvents WHERE type = %d and timeInSeconds > %d"; len = sprintf_s(query, 300, fixedInsertStr, SELF_ATTESTATION, countFromTimeInSeconds); if(WaitForSingleObject(mysqlMutex, INFINITE) != WAIT_OBJECT_0){ printf("SelectDataSetForLimitCalculations: Couldn't acquire mutex. Returning\n"); return GENERIC_ERROR; } conn = OpenDatabaseConnection(gffServerDBName); if(conn == NULL){ printf("SelectDataSetForLimitCalculations: OpenDatabaseConnection(gffServerDBName) failed\n"); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } ////////////////////////////////// if(0 != mysql_real_query(conn, query, len)){ printf("mysql_real_query() failed in SelectDataSetForLimitCalculations\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } results = mysql_store_result(conn); if(results == NULL){ printf("SelectDataSetForLimitCalculations: mysql_store_result failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } if(mysql_num_rows(results) == 0){ mysql_free_result(results); printf("SelectDataSetForLimitCalculations: mysql_num_rows returned no results\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, NO_RESULTS_FOUND); } while(counter < count){ row = mysql_fetch_row(results); if(row == NULL){ printf("SelectDataSetForLimitCalculations: mysql_fetch_row failed\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } q->push((unsigned int)(atoi(row[0]))); counter++; } ////////////////////////////////// CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("SelectDataSetForLimitCalculations: Couldn't release mutex.\n"); return GENERIC_ERROR; } return GENERIC_SUCCESS; }
int SelectUnfinishedPendingSelfAttestationMeIds(unsigned int timeLimit, vector<int> * v){ MYSQL_RES * results; MYSQL_ROW row; unsigned int len; int holder; unsigned int numRows = 0; MYSQL * conn; char query[400]; len = sprintf_s(query, 400, "SELECT id FROM pendingmeasurementevents WHERE timeInSeconds < %u AND type = 0", timeLimit); if(WaitForSingleObject(mysqlMutex, INFINITE) != WAIT_OBJECT_0){ printf("SelectUnfinishedPendingSelfAttestationMeIds: Couldn't acquire mutex. Returning\n"); return GENERIC_ERROR; } conn = OpenDatabaseConnection(gffServerDBName); if(conn == NULL){ printf("SelectUnfinishedPendingSelfAttestationMeIds: OpenDatabaseConnection(gffServerDBName) failed\n"); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } ////////////////////////////////// if(0 != mysql_real_query(conn, query, len)){ holder = CheckError(conn,mysql_errno(conn)); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, holder); } results = mysql_store_result(conn); if(results == NULL){ printf("SelectUnfinishedPendingSelfAttestationMeIds: mysql_use_result failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } numRows = (unsigned int)mysql_num_rows(results); if(numRows == 0){ mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, NO_RESULTS_FOUND); } for(unsigned int i = 0; i < numRows; i++){ row = mysql_fetch_row(results); if(row == NULL){ printf("SelectUnfinishedPendingSelfAttestationMeIds: mysql_fetch_row failed\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } unsigned int temp = strtoul(row[0], NULL, 10); v->push_back(temp); } mysql_free_result(results); ////////////////////////////////// CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("SelectUnfinishedPendingSelfAttestationMeIds: Couldn't release mutex. Exiting thread\n"); return GENERIC_ERROR; } return GENERIC_SUCCESS; }
int CleanUpStaleMatchingPendingEvents(me_t * pendingME){ char query[256]; char * fixedInsertStr; unsigned int len; unsigned int numRows; int holder; MYSQL * conn; MYSQL_RES * results; MYSQL_ROW row; fixedInsertStr = "SELECT id FROM PendingMeasurementEvents WHERE type = %d AND timeInSeconds = %d AND hostID = %d AND overloadedForeignID = %d AND id <> %d AND timeInSeconds < %d AND nonce = %d"; len = sprintf_s(query, 256, fixedInsertStr, pendingME->type, pendingME->timeInSeconds, pendingME->hostID,pendingME->overloadedForeignID,pendingME->id,pendingME->timeInSeconds,pendingME->nonce); if(WaitForSingleObject(mysqlMutex, INFINITE) != WAIT_OBJECT_0){ printf("CleanUpStaleMatchingPendingEvents: Couldn't acquire mutex. Returning\n"); return GENERIC_ERROR; } conn = OpenDatabaseConnection(gffServerDBName); if(conn == NULL){ printf("CleanUpStaleMatchingPendingEvents: OpenDatabaseConnection(gffServerDBName) failed\n"); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } ////////////////////////////////// if(0 != mysql_real_query(conn, query, len)){ holder = CheckError(conn,mysql_errno(conn)); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, holder); } results = mysql_store_result(conn); if(results == NULL){ printf("CleanUpStaleMatchingPendingEvents: mysql_use_result failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } numRows = (unsigned int)mysql_num_rows(results); if(numRows == 0){ mysql_free_result(results); CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("CleanUpStaleMatchingPendingEvents: Couldn't release mutex.\n"); return GENERIC_ERROR; } return GENERIC_SUCCESS; } for(unsigned int i = 0; i < numRows; i++){ row = mysql_fetch_row(results); if(row == NULL){ printf("CleanUpStaleMatchingPendingEvents: mysql_fetch_row failed\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } unsigned int temp = (unsigned int)row[0]; fixedInsertStr = "DELETE FROM PendingMeasurementEvents WHERE id = %d"; len = sprintf_s(query, 100, fixedInsertStr, temp); //if(0 != mysql_real_query(conn, query, len)){ // holder = CheckError(conn,mysql_errno(conn)); // CloseDatabaseConnection(conn); // return ReleaseMutexAndReturnError(mysqlMutex, holder); //} printf("CleanUpStaleMatchingPendingEvents: delete sql = %s\n",query); } mysql_free_result(results); ////////////////////////////////// CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("CleanUpStaleMatchingPendingEvents: Couldn't release mutex.\n"); return GENERIC_ERROR; } return GENERIC_SUCCESS; }
Socket* LocalWin32Socket::Accept() { HANDLE h[2]; if ( state != SS_OPEN ) { return (NULL); } ConnectData* cdp = (ConnectData*) sendBuffer->dataBuf; cdp->processId = GetCurrentProcessId(); cdp->mutexHandle = watchDogMutex; while (true) { SetEvent( signalHandle[RTR] ); int rc = WaitForSingleObject( signalHandle[RD], ACCEPT_TIMEOUT ); if ( rc == WAIT_OBJECT_0 ) { if ( state != SS_OPEN ) { lastError = EC_NOT_OPENED; return (NULL); } lastError = EC_OK; break; } else if ( rc != WAIT_TIMEOUT ) { lastError = GetLastError(); return (NULL); } } LocalWin32Socket* sock = new LocalWin32Socket(); sock->mutexHandle = ((ConnectData*) recvBuffer->dataBuf)->mutexHandle; AcceptData* adp = (AcceptData*) sendBuffer->dataBuf; adp->bufferHandle = sock->bufferHandle; for ( int i = RD; i <= RTT; i++ ) { adp->signalHandle[(i + TD - RD) & RTT] = sock->signalHandle[i]; } SetEvent( signalHandle[TD] ); h[0] = signalHandle[RD]; h[1] = sock->mutexHandle; int rc = WaitForMultipleObjects( 2, h, FALSE, INFINITE ); if ( rc != WAIT_OBJECT_0 ) { if ( rc == WAIT_OBJECT_0+1 || rc == WAIT_ABANDONED+1 ) { lastError = EC_BROKEN_PIPE; ReleaseMutex( mutexHandle ); } else { lastError = GetLastError(); } delete sock; return (NULL); } return (sock); }
int SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp(self_check_t * selfCheckInput, self_check_t * selfCheckTiresias){ MYSQL_RES * results; MYSQL_ROW row; //really a char ** unsigned int numRows = 0, numFields = 0; char query[200]; unsigned int len; char * fixedSelectStr; MYSQL * conn; fixedSelectStr = "SELECT * FROM Checksums WHERE nonce = %#x AND timeDateStamp = %#x AND baseVA = %#x"; len = sprintf_s(query, 200, fixedSelectStr, selfCheckInput->nonce, selfCheckInput->timeDateStamp, selfCheckInput->baseVA); if(WaitForSingleObject(mysqlMutex, INFINITE) != WAIT_OBJECT_0){ printf("SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp: Couldn't acquire mutex. Returning\n"); return GENERIC_ERROR; } conn = OpenDatabaseConnection(gffTiresiasDBName); if(conn == NULL){ printf("SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp: OpenDatabaseConnection(gffTiresiasDBName) failed\n"); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } ////////////////////////////////// if(0 != mysql_real_query(conn, query, len)){ printf("SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp: mysql_real_query failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } results = mysql_store_result(conn); if(results == NULL){ printf("SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp: mysql_use_result failed\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } numRows = (unsigned int)mysql_num_rows(results); if(numRows == 0){//Will fail here if an empty set is returned mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, NO_RESULTS_FOUND); } //There should only ever be one correct checksum value //for a given combination of nonce/timeDateStamp/baseVA if(numRows > 1){ mysql_free_result(results); printf("SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp: More than one checksum found for the nonce/timeDateStamp/baseVA combination. Check tiresias database\n"); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, TOO_MANY_RESULTS_FOUND); } row = mysql_fetch_row(results); if(row == NULL){ printf("SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp: mysql_fetch_row failed\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } numFields = mysql_num_fields(results); if(numFields != (4 + SELF_CHECKSUM_SIZE)){ printf("SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp: mysql_num_fields says we have the wrong number of fields\n"); mysql_free_result(results); CloseDatabaseConnection(conn); return ReleaseMutexAndReturnError(mysqlMutex, GENERIC_ERROR); } selfCheckTiresias->nonce = selfCheckInput->nonce; selfCheckTiresias->timeDateStamp = selfCheckInput->timeDateStamp; selfCheckTiresias->baseVA = selfCheckInput->baseVA; for(unsigned int i = 0; i < SELF_CHECKSUM_SIZE; i++){ selfCheckTiresias->checksum[i] = strtoul(row[4+i], NULL, 10); } mysql_free_result(results); ////////////////////////////////// CloseDatabaseConnection(conn); if(!ReleaseMutex(mysqlMutex)){ printf("SelectTiresiasChecksumByNonceAndBaseAndTimedatestamp: Couldn't release mutex. Exiting thread\n"); return GENERIC_ERROR; } return GENERIC_SUCCESS; }
bool LocalWin32Socket::Connect( int maxAttempts, time_t timeout ) { char buf[MAX_ADDRESS_LEN]; int rc, i, error_code; HANDLE h[2]; for ( i = RD; i <= RTT; i++ ) { sprintf( buf, "%s.%c", localName.c_str(), ((i + TD - RD) & RTT) + '0' ); signalHandle[i] = CreateEvent( NULL, false, false, buf ); if ( !signalHandle[i] ) { lastError = GetLastError(); while (--i >= 0) { CloseHandle( signalHandle[i] ); } return (false); } } sprintf( buf, "%s.shr", localName.c_str() ); bufferHandle = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(LocalSocketBuffer)*2, buf ); if (!bufferHandle) { lastError = GetLastError(); for (i = RD; i <= RTT; i++) { CloseHandle( signalHandle[i] ); } return (false); } sendBuffer = (LocalSocketBuffer*) MapViewOfFile( bufferHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0 ); if ( !sendBuffer ) { lastError = GetLastError(); for (i = RD; i <= RTT; i++) { CloseHandle( signalHandle[i] ); } CloseHandle( bufferHandle ); return (false); } recvBuffer = sendBuffer+1; state = SS_SHUTDOWN; mutexHandle = NULL; rc = WaitForSingleObject( signalHandle[RTT],timeout*maxAttempts*MILLISECOND ); if ( rc != WAIT_OBJECT_0 ) { error_code = (rc == WAIT_TIMEOUT) ? EC_TIMEOUT_EXPIRED : GetLastError(); Close(); lastError = error_code; return (false); } ConnectData* cdp = (ConnectData*) recvBuffer->dataBuf; HANDLE hServer = OpenProcess( STANDARD_RIGHTS_REQUIRED | PROCESS_DUP_HANDLE, FALSE, cdp->processId ); if ( !hServer ) { error_code = GetLastError(); Close(); lastError = error_code; return (false); } HANDLE hSelf = GetCurrentProcess(); if ( !DuplicateHandle( hServer, cdp->mutexHandle, hSelf, &mutexHandle, 0, FALSE, DUPLICATE_SAME_ACCESS ) || !DuplicateHandle( hSelf, watchDogMutex, hServer, &((ConnectData*) sendBuffer->dataBuf)->mutexHandle, 0, FALSE, DUPLICATE_SAME_ACCESS ) ) { error_code = GetLastError(); CloseHandle( hServer ); Close(); lastError = error_code; return (false); } SetEvent( signalHandle[TD] ); h[0] = signalHandle[RD]; h[1] = mutexHandle; rc = WaitForMultipleObjects( 2, h, FALSE, INFINITE ); if ( rc != WAIT_OBJECT_0 ) { if ( rc == WAIT_OBJECT_0+1 || rc == WAIT_ABANDONED+1 ) { error_code = EC_BROKEN_PIPE; ReleaseMutex( mutexHandle ); } else { error_code = GetLastError(); } CloseHandle( hServer ); Close(); lastError = error_code; return (false); } AcceptData ad = *(AcceptData*) recvBuffer->dataBuf; SetEvent( signalHandle[TD] ); for ( i = RD; i <= RTT; i++ ) { CloseHandle( signalHandle[i] ); } UnmapViewOfFile( sendBuffer ); CloseHandle( bufferHandle ); bufferHandle = NULL; if ( !DuplicateHandle( hServer, ad.bufferHandle, hSelf, &bufferHandle, 0, FALSE, DUPLICATE_SAME_ACCESS ) ) { lastError = GetLastError(); CloseHandle( hServer ); CloseHandle( mutexHandle ); return (false); } else { for (i = RD; i <= RTT; i++) { if (!DuplicateHandle( hServer, ad.signalHandle[i], hSelf, &signalHandle[i], 0, FALSE, DUPLICATE_SAME_ACCESS ) ) { lastError = GetLastError(); CloseHandle( hServer ); CloseHandle( bufferHandle ); CloseHandle( mutexHandle ); while (--i >= 0) { CloseHandle( signalHandle[1] ); } return (false); } } } CloseHandle( hServer ); sendBuffer = (LocalSocketBuffer*) MapViewOfFile( bufferHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0 ); if ( !sendBuffer ) { lastError = GetLastError(); CloseHandle( bufferHandle ); CloseHandle( mutexHandle ); for ( i = RD; i <= RTT; i++ ) { CloseHandle( signalHandle[i] ); } return (false); } recvBuffer = sendBuffer+1; ioSocketBuffer = new SocketBuffer( *this ); ioSocketStream = new iostream( ioSocketBuffer ); ioSocketStream->clear(); lastError = EC_OK; state = SS_OPEN; return (true); }
/*********************************************************************** * OutputDebugStringA (KERNEL32.@) * * Output by an application of an ascii string to a debugger (if attached) * and program log. * * PARAMS * str [I] The message to be logged and given to the debugger. * * RETURNS * * Nothing. */ void WINAPI OutputDebugStringA( LPCSTR str ) { static HANDLE DBWinMutex = NULL; static BOOL mutex_inited = FALSE; /* send string to attached debugger */ SERVER_START_REQ( output_debug_string ) { req->string = wine_server_client_ptr( str ); req->length = strlen(str) + 1; wine_server_call( req ); } SERVER_END_REQ; WARN("%s\n", debugstr_a(str)); /* send string to a system-wide monitor */ /* FIXME should only send to monitor if no debuggers are attached */ if (!mutex_inited) { /* first call to OutputDebugString, initialize mutex handle */ static const WCHAR mutexname[] = {'D','B','W','i','n','M','u','t','e','x',0}; HANDLE mutex = CreateMutexExW( NULL, mutexname, 0, SYNCHRONIZE ); if (mutex) { if (InterlockedCompareExchangePointer( &DBWinMutex, mutex, 0 ) != 0) { /* someone beat us here... */ CloseHandle( mutex ); } } mutex_inited = TRUE; } if (DBWinMutex) { static const WCHAR shmname[] = {'D','B','W','I','N','_','B','U','F','F','E','R',0}; static const WCHAR eventbuffername[] = {'D','B','W','I','N','_','B','U','F','F','E','R','_','R','E','A','D','Y',0}; static const WCHAR eventdataname[] = {'D','B','W','I','N','_','D','A','T','A','_','R','E','A','D','Y',0}; HANDLE mapping; mapping = OpenFileMappingW( FILE_MAP_WRITE, FALSE, shmname ); if (mapping) { LPVOID buffer; HANDLE eventbuffer, eventdata; buffer = MapViewOfFile( mapping, FILE_MAP_WRITE, 0, 0, 0 ); eventbuffer = OpenEventW( SYNCHRONIZE, FALSE, eventbuffername ); eventdata = OpenEventW( EVENT_MODIFY_STATE, FALSE, eventdataname ); if (buffer && eventbuffer && eventdata) { /* monitor is present, synchronize with other OutputDebugString invokations */ WaitForSingleObject( DBWinMutex, INFINITE ); /* acquire control over the buffer */ if (WaitForSingleObject( eventbuffer, 10000 ) == WAIT_OBJECT_0) { int str_len; struct _mon_buffer_t { DWORD pid; char buffer[1]; } *mon_buffer = (struct _mon_buffer_t*) buffer; str_len = strlen( str ); if (str_len > (4096 - sizeof(DWORD) - 1)) str_len = 4096 - sizeof(DWORD) - 1; mon_buffer->pid = GetCurrentProcessId(); memcpy( mon_buffer->buffer, str, str_len ); mon_buffer->buffer[str_len] = 0; /* signal data ready */ SetEvent( eventdata ); } ReleaseMutex( DBWinMutex ); } if (buffer) UnmapViewOfFile( buffer ); if (eventbuffer) CloseHandle( eventbuffer ); if (eventdata) CloseHandle( eventdata ); CloseHandle( mapping ); } } }
bool LocalWin32Socket::Write( const void* buf, size_t size ) { char* src = (char*) buf; lastError = EC_OK; while (size > 0 && state == SS_OPEN) { sendBuffer->sendWaitFlag = true; size_t begin = sendBuffer->dataBeg; size_t end = sendBuffer->dataEnd; size_t snd_size = (begin <= end) ? sizeof(sendBuffer->dataBuf) - end - (begin == 0) : begin - end - 1; if ( snd_size > 0 ) { sendBuffer->sendWaitFlag = false; if ( snd_size >= size ) { memcpy( &sendBuffer->dataBuf[end], src, size ); end += size; size = 0; } else { memcpy( &sendBuffer->dataBuf[end], src, snd_size ); end += snd_size; src += snd_size; size -= snd_size; } sendBuffer->dataEnd = (end == sizeof(sendBuffer->dataBuf)) ? 0 : end; if ( sendBuffer->recvWaitFlag ) { SetEvent( signalHandle[TD] ); } } else { HANDLE h[2]; h[0] = signalHandle[RTT]; h[1] = mutexHandle; int rc = WaitForMultipleObjects( 2, h, FALSE, INFINITE ); recvBuffer->sendWaitFlag = false; if ( rc != WAIT_OBJECT_0 ) { if ( rc == WAIT_OBJECT_0+1 || rc == WAIT_ABANDONED+1 ) { SetStreamState( ios::failbit | ios::eofbit ); lastError = EC_BROKEN_PIPE; ReleaseMutex( mutexHandle ); } else { SetStreamState( ios::failbit ); lastError = GetLastError(); } return (false); } } } return (size == 0); }
size_t VSICurlStreamingHandle::Read( void *pBuffer, size_t nSize, size_t nMemb ) { GByte* pabyBuffer = (GByte*)pBuffer; size_t nBufferRequestSize = nSize * nMemb; if (nBufferRequestSize == 0) return 0; size_t nRemaining = nBufferRequestSize; AcquireMutex(); int bHastComputedFileSizeLocal = bHastComputedFileSize; vsi_l_offset fileSizeLocal = fileSize; ReleaseMutex(); if (bHastComputedFileSizeLocal && curOffset >= fileSizeLocal) { CPLDebug("VSICURL", "Read attempt beyond end of file"); bEOF = TRUE; } if (bEOF) return 0; if (curOffset < nRingBufferFileOffset) PutRingBufferInCache(); if (ENABLE_DEBUG) CPLDebug("VSICURL", "Read [" CPL_FRMT_GUIB ", " CPL_FRMT_GUIB "[ in %s", curOffset, curOffset + nBufferRequestSize, pszURL); #ifdef notdef if( pCachedData != NULL && nCachedSize >= 1024 && nRecomputedChecksumOfFirst1024Bytes == 0 ) { for(size_t i = 0; i < 1024 / sizeof(int); i ++) { int nVal; memcpy(&nVal, pCachedData + i * sizeof(int), sizeof(int)); nRecomputedChecksumOfFirst1024Bytes += nVal; } if( bHastComputedFileSizeLocal ) { poFS->AcquireMutex(); CachedFileProp* cachedFileProp = poFS->GetCachedFileProp(pszURL); if( cachedFileProp->nChecksumOfFirst1024Bytes == 0 ) { cachedFileProp->nChecksumOfFirst1024Bytes = nRecomputedChecksumOfFirst1024Bytes; } else if( nRecomputedChecksumOfFirst1024Bytes != cachedFileProp->nChecksumOfFirst1024Bytes ) { CPLDebug("VSICURL", "Invalidating previously cached file size. First bytes of file have changed!"); AcquireMutex(); bHastComputedFileSize = FALSE; cachedFileProp->bHastComputedFileSize = FALSE; cachedFileProp->nChecksumOfFirst1024Bytes = 0; ReleaseMutex(); } poFS->ReleaseMutex(); } } #endif /* Can we use the cache ? */ if( pCachedData != NULL && curOffset < nCachedSize ) { size_t nSz = MIN(nRemaining, (size_t)(nCachedSize - curOffset)); if (ENABLE_DEBUG) CPLDebug("VSICURL", "Using cache for [%d, %d[ in %s", (int)curOffset, (int)(curOffset + nSz), pszURL); memcpy(pabyBuffer, pCachedData + curOffset, nSz); pabyBuffer += nSz; curOffset += nSz; nRemaining -= nSz; } /* Is the request partially covered by the cache and going beyond file size ? */ if ( pCachedData != NULL && bHastComputedFileSizeLocal && curOffset <= nCachedSize && curOffset + nRemaining > fileSizeLocal && fileSize == nCachedSize ) { size_t nSz = (size_t) (nCachedSize - curOffset); if (ENABLE_DEBUG && nSz != 0) CPLDebug("VSICURL", "Using cache for [%d, %d[ in %s", (int)curOffset, (int)(curOffset + nSz), pszURL); memcpy(pabyBuffer, pCachedData + curOffset, nSz); pabyBuffer += nSz; curOffset += nSz; nRemaining -= nSz; bEOF = TRUE; } /* Has a Seek() being done since the last Read() ? */ if (!bEOF && nRemaining > 0 && curOffset != nRingBufferFileOffset) { /* Backward seek : we need to restart the download from the start */ if (curOffset < nRingBufferFileOffset) StopDownload(); StartDownload(); #define SKIP_BUFFER_SIZE 32768 GByte* pabyTmp = (GByte*)CPLMalloc(SKIP_BUFFER_SIZE); CPLAssert(curOffset >= nRingBufferFileOffset); vsi_l_offset nBytesToSkip = curOffset - nRingBufferFileOffset; while(nBytesToSkip > 0) { vsi_l_offset nBytesToRead = nBytesToSkip; AcquireMutex(); if (nBytesToRead > oRingBuffer.GetSize()) nBytesToRead = oRingBuffer.GetSize(); if (nBytesToRead > SKIP_BUFFER_SIZE) nBytesToRead = SKIP_BUFFER_SIZE; oRingBuffer.Read(pabyTmp, (size_t)nBytesToRead); /* Signal to the producer that we have ingested some bytes */ CPLCondSignal(hCondConsumer); ReleaseMutex(); if (nBytesToRead) AddRegion(nRingBufferFileOffset, (size_t)nBytesToRead, pabyTmp); nBytesToSkip -= nBytesToRead; nRingBufferFileOffset += nBytesToRead; if (nBytesToRead == 0 && nBytesToSkip != 0) { if (ENABLE_DEBUG) CPLDebug("VSICURL", "Waiting for writer to produce some bytes..."); AcquireMutex(); while(oRingBuffer.GetSize() == 0 && bDownloadInProgress) CPLCondWait(hCondProducer, hRingBufferMutex); int bBufferEmpty = (oRingBuffer.GetSize() == 0); ReleaseMutex(); if (bBufferEmpty && !bDownloadInProgress) break; } } CPLFree(pabyTmp); if (nBytesToSkip != 0) { bEOF = TRUE; return 0; } } if (!bEOF && nRemaining > 0) { StartDownload(); CPLAssert(curOffset == nRingBufferFileOffset); } /* Fill the destination buffer from the ring buffer */ while(!bEOF && nRemaining > 0) { AcquireMutex(); size_t nToRead = oRingBuffer.GetSize(); if (nToRead > nRemaining) nToRead = nRemaining; oRingBuffer.Read(pabyBuffer, nToRead); /* Signal to the producer that we have ingested some bytes */ CPLCondSignal(hCondConsumer); ReleaseMutex(); if (nToRead) AddRegion(curOffset, nToRead, pabyBuffer); nRemaining -= nToRead; pabyBuffer += nToRead; curOffset += nToRead; nRingBufferFileOffset += nToRead; if (nToRead == 0 && nRemaining != 0) { if (ENABLE_DEBUG) CPLDebug("VSICURL", "Waiting for writer to produce some bytes..."); AcquireMutex(); while(oRingBuffer.GetSize() == 0 && bDownloadInProgress) CPLCondWait(hCondProducer, hRingBufferMutex); int bBufferEmpty = (oRingBuffer.GetSize() == 0); ReleaseMutex(); if (bBufferEmpty && !bDownloadInProgress) break; } } if (ENABLE_DEBUG) CPLDebug("VSICURL", "Read(%d) = %d", (int)nBufferRequestSize, (int)(nBufferRequestSize - nRemaining)); size_t nRet = (nBufferRequestSize - nRemaining) / nSize; if (nRet < nMemb) bEOF = TRUE; return nRet; }
static void caml_io_mutex_unlock(struct channel * chan) { ReleaseMutex((HANDLE) chan->mutex); TlsSetValue(last_channel_locked_key, NULL); }
vsi_l_offset VSICurlStreamingHandle::GetFileSize() { WriteFuncStruct sWriteFuncData; WriteFuncStruct sWriteFuncHeaderData; AcquireMutex(); if (bHastComputedFileSize) { vsi_l_offset nRet = fileSize; ReleaseMutex(); return nRet; } ReleaseMutex(); #if LIBCURL_VERSION_NUM < 0x070B00 /* Curl 7.10.X doesn't manage to unset the CURLOPT_RANGE that would have been */ /* previously set, so we have to reinit the connection handle */ if (hCurlHandle) { curl_easy_cleanup(hCurlHandle); hCurlHandle = curl_easy_init(); } #endif CURL* hLocalHandle = curl_easy_init(); VSICurlSetOptions(hLocalHandle, pszURL); VSICURLStreamingInitWriteFuncStruct(&sWriteFuncHeaderData); /* HACK for mbtiles driver: proper fix would be to auto-detect servers that don't accept HEAD */ /* http://a.tiles.mapbox.com/v3/ doesn't accept HEAD, so let's start a GET */ /* and interrupt is as soon as the header is found */ if (strstr(pszURL, ".tiles.mapbox.com/") != NULL) { curl_easy_setopt(hLocalHandle, CURLOPT_HEADERDATA, &sWriteFuncHeaderData); curl_easy_setopt(hLocalHandle, CURLOPT_HEADERFUNCTION, VSICurlStreamingHandleWriteFuncForHeader); sWriteFuncHeaderData.bIsHTTP = strncmp(pszURL, "http", 4) == 0; sWriteFuncHeaderData.bDownloadHeaderOnly = TRUE; } else { curl_easy_setopt(hLocalHandle, CURLOPT_NOBODY, 1); curl_easy_setopt(hLocalHandle, CURLOPT_HTTPGET, 0); curl_easy_setopt(hLocalHandle, CURLOPT_HEADER, 1); } /* We need that otherwise OSGEO4W's libcurl issue a dummy range request */ /* when doing a HEAD when recycling connections */ curl_easy_setopt(hLocalHandle, CURLOPT_RANGE, NULL); /* Bug with older curl versions (<=7.16.4) and FTP. See http://curl.haxx.se/mail/lib-2007-08/0312.html */ VSICURLStreamingInitWriteFuncStruct(&sWriteFuncData); curl_easy_setopt(hLocalHandle, CURLOPT_WRITEDATA, &sWriteFuncData); curl_easy_setopt(hLocalHandle, CURLOPT_WRITEFUNCTION, VSICurlStreamingHandleWriteFuncForHeader); char szCurlErrBuf[CURL_ERROR_SIZE+1]; szCurlErrBuf[0] = '\0'; curl_easy_setopt(hLocalHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf ); double dfSize = 0; curl_easy_perform(hLocalHandle); AcquireMutex(); eExists = EXIST_UNKNOWN; bHastComputedFileSize = TRUE; if (strncmp(pszURL, "ftp", 3) == 0) { if (sWriteFuncData.pBuffer != NULL && strncmp(sWriteFuncData.pBuffer, "Content-Length: ", strlen( "Content-Length: ")) == 0) { const char* pszBuffer = sWriteFuncData.pBuffer + strlen("Content-Length: "); eExists = EXIST_YES; fileSize = CPLScanUIntBig(pszBuffer, sWriteFuncData.nSize - strlen("Content-Length: ")); if (ENABLE_DEBUG) CPLDebug("VSICURL", "GetFileSize(%s)=" CPL_FRMT_GUIB, pszURL, fileSize); } } if (eExists != EXIST_YES) { CURLcode code = curl_easy_getinfo(hLocalHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &dfSize ); if (code == 0) { eExists = EXIST_YES; if (dfSize < 0) fileSize = 0; else fileSize = (GUIntBig)dfSize; } else { eExists = EXIST_NO; fileSize = 0; CPLError(CE_Failure, CPLE_AppDefined, "VSICurlStreamingHandle::GetFileSize failed"); } long response_code = 0; curl_easy_getinfo(hLocalHandle, CURLINFO_HTTP_CODE, &response_code); if (response_code != 200) { eExists = EXIST_NO; fileSize = 0; } /* Try to guess if this is a directory. Generally if this is a directory, */ /* curl will retry with an URL with slash added */ char *pszEffectiveURL = NULL; curl_easy_getinfo(hLocalHandle, CURLINFO_EFFECTIVE_URL, &pszEffectiveURL); if (pszEffectiveURL != NULL && strncmp(pszURL, pszEffectiveURL, strlen(pszURL)) == 0 && pszEffectiveURL[strlen(pszURL)] == '/') { eExists = EXIST_YES; fileSize = 0; bIsDirectory = TRUE; } if (ENABLE_DEBUG) CPLDebug("VSICURL", "GetFileSize(%s)=" CPL_FRMT_GUIB " response_code=%d", pszURL, fileSize, (int)response_code); } CPLFree(sWriteFuncData.pBuffer); CPLFree(sWriteFuncHeaderData.pBuffer); poFS->AcquireMutex(); CachedFileProp* cachedFileProp = poFS->GetCachedFileProp(pszURL); cachedFileProp->bHastComputedFileSize = TRUE; #ifdef notdef cachedFileProp->nChecksumOfFirst1024Bytes = nRecomputedChecksumOfFirst1024Bytes; #endif cachedFileProp->fileSize = fileSize; cachedFileProp->eExists = eExists; cachedFileProp->bIsDirectory = bIsDirectory; poFS->ReleaseMutex(); vsi_l_offset nRet = fileSize; ReleaseMutex(); if (hCurlHandle == NULL) hCurlHandle = hLocalHandle; else curl_easy_cleanup(hLocalHandle); return nRet; }
// LJ DEBUG - testing void spoutDirectX::AllowReceiverAccess(HANDLE hAccessMutex) { // For debugging if(!bUseAccessLocks) return; if(hAccessMutex) ReleaseMutex(hAccessMutex); }
int VSICurlStreamingHandle::Exists() { if (eExists == EXIST_UNKNOWN) { /* Consider that only the files whose extension ends up with one that is */ /* listed in CPL_VSIL_CURL_ALLOWED_EXTENSIONS exist on the server */ /* This can speeds up dramatically open experience, in case the server */ /* cannot return a file list */ /* For example : */ /* gdalinfo --config CPL_VSIL_CURL_ALLOWED_EXTENSIONS ".tif" /vsicurl_streaming/http://igskmncngs506.cr.usgs.gov/gmted/Global_tiles_GMTED/075darcsec/bln/W030/30N030W_20101117_gmted_bln075.tif */ const char* pszAllowedExtensions = CPLGetConfigOption("CPL_VSIL_CURL_ALLOWED_EXTENSIONS", NULL); if (pszAllowedExtensions) { char** papszExtensions = CSLTokenizeString2( pszAllowedExtensions, ", ", 0 ); int nURLLen = strlen(pszURL); int bFound = FALSE; for(int i=0;papszExtensions[i] != NULL;i++) { int nExtensionLen = strlen(papszExtensions[i]); if (nURLLen > nExtensionLen && EQUAL(pszURL + nURLLen - nExtensionLen, papszExtensions[i])) { bFound = TRUE; break; } } if (!bFound) { eExists = EXIST_NO; fileSize = 0; poFS->AcquireMutex(); CachedFileProp* cachedFileProp = poFS->GetCachedFileProp(pszURL); cachedFileProp->bHastComputedFileSize = TRUE; cachedFileProp->fileSize = fileSize; cachedFileProp->eExists = eExists; poFS->ReleaseMutex(); CSLDestroy(papszExtensions); return 0; } CSLDestroy(papszExtensions); } char chFirstByte; int bExists = (Read(&chFirstByte, 1, 1) == 1); AcquireMutex(); poFS->AcquireMutex(); CachedFileProp* cachedFileProp = poFS->GetCachedFileProp(pszURL); cachedFileProp->eExists = eExists = bExists ? EXIST_YES : EXIST_NO; poFS->ReleaseMutex(); ReleaseMutex(); Seek(0, SEEK_SET); } return eExists == EXIST_YES; }
void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int iAlign) { // assert(s_Initialized); // Zone now initializes on first use. (During static constructors) if (!s_Initialized) Com_InitZoneMemory(); if (iSize == 0) { #ifdef _DEBUG return (void*)(&s_EmptyBlock.start + 1); #else return (void*)(&s_EmptyBlock.header + 1); #endif } if (iSize < 0) { Z_MallocFail("Negative size", iSize, eTag); return NULL; } #ifndef _GAMECUBE WaitForSingleObject(s_Mutex, INFINITE); #endif // Make new/delete memory temporary if requested if (eTag == TAG_NEWDEL && s_IsNewDeleteTemp) { eTag = TAG_TEMP_WORKSPACE; } // Determine how much space we need with headers and footers int header_size = sizeof(ZoneHeader); int footer_size = 0; if (Z_IsTagLinked(eTag)) { header_size += sizeof(ZoneLinkHeader); } #ifdef _DEBUG header_size += sizeof(ZoneDebugHeader); footer_size += sizeof(ZoneDebugFooter); #endif int real_size = iSize + header_size + footer_size; int align_pad = 0; // Get a bit of free memory. Temporary memory is allocated // from the end. More permanent allocations are done at the // begining of the pool. ZoneFreeBlock* fblock; if (Z_IsTagTemp(eTag)) { fblock = Z_FindLastFree(real_size, header_size, footer_size, iAlign, align_pad); } else { fblock = Z_FindFirstFree(real_size, header_size, footer_size, iAlign, align_pad); } // Did we actually find some memory? if (!fblock) { #ifndef _GAMECUBE ReleaseMutex(s_Mutex); #endif // if(eTag == TAG_TEMP_SND_RAWDATA) { if(eTag == TAG_SND_RAWDATA) { return NULL; } Z_MallocFail("Out of memory", iSize, eTag); return NULL; } // Add any alignment bytes real_size += align_pad; // Split the free block and get a pointer to the start // allocated space. void* ablock; if (Z_IsTagTemp(eTag)) { ablock = Z_SplitFree(fblock, real_size, false); // Append align pad to end of block Z_SetupAlignmentPad( (void*)((char*)ablock + real_size - align_pad), align_pad, false); } else { ablock = Z_SplitFree(fblock, real_size, true); // Insert align pad at block start Z_SetupAlignmentPad(ablock, align_pad, true); ablock = (void*)((char*)ablock + align_pad); } if (!ablock) { Z_MallocFail("Failed to split", iSize, eTag); } // Add linking header if necessary if (Z_IsTagLinked(eTag)) { ZoneLinkHeader* linked = (ZoneLinkHeader*)ablock; linked->m_Next = s_LinkBase; linked->m_Prev = NULL; if (s_LinkBase) { s_LinkBase->m_Prev = linked; } s_LinkBase = linked; assert(Z_ValidateLinks()); // Next... ablock = (void*)((char*)ablock + sizeof(ZoneLinkHeader)); } // Setup the header: // 31 - alignment flag // 25-30 - tag // 0-24 - size without headers/footers assert(iSize >= 0 && iSize < (1 << 25)); assert(eTag >= 0 && eTag < 64); ZoneHeader* header = (ZoneHeader*)ablock; *header = (((unsigned int)eTag) << 25) | ((unsigned int)iSize); if (align_pad) { *header |= (1 << 31); } // Next... ablock = (void*)((char*)ablock + sizeof(ZoneHeader)); #ifdef _DEBUG { // Setup the debug markers ZoneDebugHeader* debug_header = (ZoneDebugHeader*)ablock; ZoneDebugFooter* debug_footer = (ZoneDebugFooter*)((char*)debug_header + (sizeof(ZoneDebugHeader) + iSize)); *debug_header = ZONE_MAGIC; *debug_footer = ZONE_MAGIC; // Next... ablock = (void*)((char*)ablock + sizeof(ZoneDebugHeader)); } #endif // Update the stats s_Stats.m_SizeAlloc += iSize; s_Stats.m_OverheadAlloc += header_size + footer_size + align_pad; s_Stats.m_SizesPerTag[eTag] += iSize; s_Stats.m_CountAlloc++; s_Stats.m_CountsPerTag[eTag]++; if (s_Stats.m_SizeAlloc + s_Stats.m_OverheadAlloc > s_Stats.m_PeakAlloc) { s_Stats.m_PeakAlloc = s_Stats.m_SizeAlloc + s_Stats.m_OverheadAlloc; } // Return a pointer to data memory if (bZeroit) { memset(ablock, 0, iSize); } assert(iAlign == 0 || (unsigned int)ablock % iAlign == 0); /* This is useful for figuring out who's allocating a certain block of memory. Please don't remove it. if(eTag == TAG_NEWDEL && (unsigned int)ablock >= 0x806c0000 && (unsigned int)ablock <= 0x806c1000 && iSize == 24) { int suck = 0; } if(eTag == TAG_SMALL && (iSize == 7 || iSize == 96)) { int suck = 0; } if(eTag == TAG_CLIENTS) { int suck = 0; } if ((unsigned)ablock >= 0x1eb0000 && (unsigned)ablock <= 0x1ec0000 && iSize == 48) { int suck = 0; } */ #ifndef _GAMECUBE ReleaseMutex(s_Mutex); #endif return ablock; }
int VSICurlStreamingHandle::ReceivedBytes(GByte *buffer, size_t count, size_t nmemb) { size_t nSize = count * nmemb; nBodySize += nSize; if (ENABLE_DEBUG) CPLDebug("VSICURL", "Receiving %d bytes...", (int)nSize); if( bHasCandidateFileSize && bCanTrustCandidateFileSize && !bHastComputedFileSize ) { poFS->AcquireMutex(); CachedFileProp* cachedFileProp = poFS->GetCachedFileProp(pszURL); cachedFileProp->fileSize = fileSize = nCandidateFileSize; cachedFileProp->bHastComputedFileSize = bHastComputedFileSize = TRUE; if (ENABLE_DEBUG) CPLDebug("VSICURL", "File size = " CPL_FRMT_GUIB, fileSize); poFS->ReleaseMutex(); } AcquireMutex(); if (eExists == EXIST_UNKNOWN) { poFS->AcquireMutex(); CachedFileProp* cachedFileProp = poFS->GetCachedFileProp(pszURL); cachedFileProp->eExists = eExists = EXIST_YES; poFS->ReleaseMutex(); } else if (eExists == EXIST_NO) { ReleaseMutex(); return 0; } while(TRUE) { size_t nFree = oRingBuffer.GetCapacity() - oRingBuffer.GetSize(); if (nSize <= nFree) { oRingBuffer.Write(buffer, nSize); /* Signal to the consumer that we have added bytes to the buffer */ CPLCondSignal(hCondProducer); if (bAskDownloadEnd) { if (ENABLE_DEBUG) CPLDebug("VSICURL", "Download interruption asked"); ReleaseMutex(); return 0; } break; } else { oRingBuffer.Write(buffer, nFree); buffer += nFree; nSize -= nFree; /* Signal to the consumer that we have added bytes to the buffer */ CPLCondSignal(hCondProducer); if (ENABLE_DEBUG) CPLDebug("VSICURL", "Waiting for reader to consume some bytes..."); while(oRingBuffer.GetSize() == oRingBuffer.GetCapacity() && !bAskDownloadEnd) { CPLCondWait(hCondConsumer, hRingBufferMutex); } if (bAskDownloadEnd) { if (ENABLE_DEBUG) CPLDebug("VSICURL", "Download interruption asked"); ReleaseMutex(); return 0; } } } ReleaseMutex(); return nmemb; }
void __PHYSFS_platformReleaseMutex(void *mutex) { ReleaseMutex((HANDLE) mutex); } /* __PHYSFS_platformReleaseMutex */
int VSICurlStreamingHandle::ReceivedBytesHeader(GByte *buffer, size_t count, size_t nmemb) { size_t nSize = count * nmemb; if (ENABLE_DEBUG) CPLDebug("VSICURL", "Receiving %d bytes for header...", (int)nSize); /* Reset buffer if we have followed link after a redirect */ if (nSize >=9 && (nHTTPCode == 301 || nHTTPCode == 302) && (EQUALN((const char*)buffer, "HTTP/1.0 ", 9) || EQUALN((const char*)buffer, "HTTP/1.1 ", 9))) { nHeaderSize = 0; nHTTPCode = 0; } if (nHeaderSize < HEADER_SIZE) { size_t nSz = MIN(nSize, HEADER_SIZE - nHeaderSize); memcpy(pabyHeaderData + nHeaderSize, buffer, nSz); pabyHeaderData[nHeaderSize + nSz] = '\0'; nHeaderSize += nSz; //CPLDebug("VSICURL", "Header : %s", pabyHeaderData); AcquireMutex(); if (eExists == EXIST_UNKNOWN && nHTTPCode == 0 && strchr((const char*)pabyHeaderData, '\n') != NULL && (EQUALN((const char*)pabyHeaderData, "HTTP/1.0 ", 9) || EQUALN((const char*)pabyHeaderData, "HTTP/1.1 ", 9))) { nHTTPCode = atoi((const char*)pabyHeaderData + 9); if (ENABLE_DEBUG) CPLDebug("VSICURL", "HTTP code = %d", nHTTPCode); /* If moved permanently/temporarily, go on */ if( !(nHTTPCode == 301 || nHTTPCode == 302) ) { poFS->AcquireMutex(); CachedFileProp* cachedFileProp = poFS->GetCachedFileProp(pszURL); cachedFileProp->eExists = eExists = (nHTTPCode == 200) ? EXIST_YES : EXIST_NO; poFS->ReleaseMutex(); } } if ( !(nHTTPCode == 301 || nHTTPCode == 302) && !bHastComputedFileSize) { /* Caution: when gzip compression is enabled, the content-length is the compressed */ /* size, which we are not interested in, so we must not take it into account. */ const char* pszContentLength = strstr((const char*)pabyHeaderData, "Content-Length: "); const char* pszEndOfLine = pszContentLength ? strchr(pszContentLength, '\n') : NULL; if( bCanTrustCandidateFileSize && pszEndOfLine != NULL ) { const char* pszVal = pszContentLength + strlen("Content-Length: "); bHasCandidateFileSize = TRUE; nCandidateFileSize = CPLScanUIntBig(pszVal, pszEndOfLine - pszVal); if (ENABLE_DEBUG) CPLDebug("VSICURL", "Has found candidate file size = " CPL_FRMT_GUIB, nCandidateFileSize); } const char* pszContentEncoding = strstr((const char*)pabyHeaderData, "Content-Encoding: "); pszEndOfLine = pszContentEncoding ? strchr(pszContentEncoding, '\n') : NULL; if( bHasCandidateFileSize && pszEndOfLine != NULL ) { const char* pszVal = pszContentEncoding + strlen("Content-Encoding: "); if( strncmp(pszVal, "gzip", 4) == 0 ) { if (ENABLE_DEBUG) CPLDebug("VSICURL", "GZip compression enabled --> cannot trust candidate file size"); bCanTrustCandidateFileSize = FALSE; } } } ReleaseMutex(); } return nmemb; }
/********************************************************************** Release mutex ***********************************************************************/ void fc_release_mutex(fc_mutex *mutex) { ReleaseMutex(*mutex); }
void MMutex::Unlock () { ReleaseMutex (sem); }