Пример #1
0
int CDb3Mmap::GetContactSettingWorker(MCONTACT contactID, LPCSTR szModule, LPCSTR szSetting, DBVARIANT *dbv, int isStatic)
{
	if (szSetting == NULL || szModule == NULL)
		return 1;

	// the db format can't tolerate more than 255 bytes of space (incl. null) for settings+module name
	int settingNameLen = (int)mir_strlen(szSetting);
	int moduleNameLen = (int)mir_strlen(szModule);
	if (settingNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("GetContactSettingWorker() got a > 255 setting name length. \n");
#endif
		return 1;
	}
	if (moduleNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("GetContactSettingWorker() got a > 255 module name length. \n");
#endif
		return 1;
	}

	mir_cslock lck(m_csDbAccess);

LBL_Seek:
	char *szCachedSettingName = m_cache->GetCachedSetting(szModule, szSetting, moduleNameLen, settingNameLen);
	log3("get [%08p] %s (%p)", hContact, szCachedSettingName, szCachedSettingName);

	DBVARIANT *pCachedValue = m_cache->GetCachedValuePtr(contactID, szCachedSettingName, 0);
	if (pCachedValue != NULL) {
		if (pCachedValue->type == DBVT_ASCIIZ || pCachedValue->type == DBVT_UTF8) {
			int cbOrigLen = dbv->cchVal;
			char *cbOrigPtr = dbv->pszVal;
			memcpy(dbv, pCachedValue, sizeof(DBVARIANT));
			if (isStatic) {
				int cbLen = 0;
				if (pCachedValue->pszVal != NULL)
					cbLen = (int)mir_strlen(pCachedValue->pszVal);

				cbOrigLen--;
				dbv->pszVal = cbOrigPtr;
				if (cbLen < cbOrigLen)
					cbOrigLen = cbLen;
				memcpy(dbv->pszVal, pCachedValue->pszVal, cbOrigLen);
				dbv->pszVal[cbOrigLen] = 0;
				dbv->cchVal = cbLen;
			}
			else {
				dbv->pszVal = (char*)mir_alloc(mir_strlen(pCachedValue->pszVal) + 1);
				mir_strcpy(dbv->pszVal, pCachedValue->pszVal);
			}
		}
		else memcpy(dbv, pCachedValue, sizeof(DBVARIANT));

		log2("get cached %s (%p)", printVariant(dbv), pCachedValue);
		return (pCachedValue->type == DBVT_DELETED) ? 1 : 0;
	}

	// never look db for the resident variable
	if (szCachedSettingName[-1] != 0)
		return 1;

	DBCachedContact *cc;
	DWORD ofsContact = GetContactOffset(contactID, &cc);

	DWORD ofsModuleName = GetModuleNameOfs(szModule);

	DBContact dbc = *(DBContact*)DBRead(ofsContact, NULL);
	if (dbc.signature != DBCONTACT_SIGNATURE)
		return 1;

	DWORD ofsSettingsGroup = GetSettingsGroupOfsByModuleNameOfs(&dbc, ofsModuleName);
	if (ofsSettingsGroup) {
		int bytesRemaining;
		unsigned varLen;
		DWORD ofsBlobPtr = ofsSettingsGroup + offsetof(DBContactSettings, blob);
		PBYTE pBlob = DBRead(ofsBlobPtr, &bytesRemaining);
		while (pBlob[0]) {
			NeedBytes(1 + settingNameLen);
			if (pBlob[0] == settingNameLen && !memcmp(pBlob + 1, szSetting, settingNameLen)) {
				MoveAlong(1 + settingNameLen);
				NeedBytes(5);
				if (isStatic && (pBlob[0] & DBVTF_VARIABLELENGTH) && VLT(dbv->type) != VLT(pBlob[0]))
					return 1;

				BYTE iType = dbv->type = pBlob[0];
				switch (iType) {
				case DBVT_DELETED: /* this setting is deleted */
					dbv->type = DBVT_DELETED;
					return 2;

				case DBVT_BYTE:  dbv->bVal = pBlob[1]; break;
				case DBVT_WORD:  memmove(&(dbv->wVal), (PWORD)(pBlob + 1), 2); break;
				case DBVT_DWORD: memmove(&(dbv->dVal), (PDWORD)(pBlob + 1), 4); break;

				case DBVT_UTF8:
				case DBVT_ASCIIZ:
					varLen = *(PWORD)(pBlob + 1);
					NeedBytes(int(3 + varLen));
					if (isStatic) {
						dbv->cchVal--;
						if (varLen < dbv->cchVal)
							dbv->cchVal = varLen;
						memmove(dbv->pszVal, pBlob + 3, dbv->cchVal); // decode
						dbv->pszVal[dbv->cchVal] = 0;
						dbv->cchVal = varLen;
					}
					else {
						dbv->pszVal = (char*)mir_alloc(1 + varLen);
						memmove(dbv->pszVal, pBlob + 3, varLen);
						dbv->pszVal[varLen] = 0;
					}
					break;

				case DBVT_BLOB:
					varLen = *(PWORD)(pBlob + 1);
					NeedBytes(int(3 + varLen));
					if (isStatic) {
						if (varLen < dbv->cpbVal)
							dbv->cpbVal = varLen;
						memmove(dbv->pbVal, pBlob + 3, dbv->cpbVal);
					}
					else {
						dbv->pbVal = (BYTE *)mir_alloc(varLen);
						memmove(dbv->pbVal, pBlob + 3, varLen);
					}
					dbv->cpbVal = varLen;
					break;

				case DBVT_ENCRYPTED:
					if (m_crypto == NULL)
						return 1;
					else {
						varLen = *(PWORD)(pBlob + 1);
						NeedBytes(int(3 + varLen));
						size_t realLen;
						ptrA decoded(m_crypto->decodeString(pBlob + 3, varLen, &realLen));
						if (decoded == NULL)
							return 1;

						varLen = (WORD)realLen;
						dbv->type = DBVT_UTF8;
						if (isStatic) {
							dbv->cchVal--;
							if (varLen < dbv->cchVal)
								dbv->cchVal = varLen;
							memmove(dbv->pszVal, decoded, dbv->cchVal);
							dbv->pszVal[dbv->cchVal] = 0;
							dbv->cchVal = varLen;
						}
						else {
							dbv->pszVal = (char*)mir_alloc(1 + varLen);
							memmove(dbv->pszVal, decoded, varLen);
							dbv->pszVal[varLen] = 0;
						}
					}
					break;
				}

				/**** add to cache **********************/
				if (iType != DBVT_BLOB && iType != DBVT_ENCRYPTED) {
					pCachedValue = m_cache->GetCachedValuePtr(contactID, szCachedSettingName, 1);
					if (pCachedValue != NULL) {
						m_cache->SetCachedVariant(dbv, pCachedValue);
						log3("set cached [%08p] %s (%p)", hContact, szCachedSettingName, pCachedValue);
					}
				}

				return 0;
			}
			NeedBytes(1);
			MoveAlong(pBlob[0] + 1);
			NeedBytes(3);
			MoveAlong(1 + GetSettingValueLength(pBlob));
			NeedBytes(1);
		}
	}

	// try to get the missing mc setting from the active sub
	if (cc && cc->IsMeta() && ValidLookupName(szModule, szSetting)) {
		if (contactID = db_mc_getDefault(contactID)) {
			if (szModule = GetContactProto(contactID)) {
				moduleNameLen = (int)mir_strlen(szModule);
				goto LBL_Seek;
			}
		}
	}

	logg();
	return 1;
}
Пример #2
0
bool CAPTcpConnect::interactWithDev(int clientSocket, int sessionID, void *in, void *out, int type,int waitTime){
    std::unique_lock<std::mutex> lck(m_mtx);
    char *rbufheader = NULL;
    char *rbufbody = NULL;
    char *buf = NULL;
    int rlen=0;
    int wlen=0;
    char *cur=buf;
    char *rcur=rbufheader;
    int bufLen=0;
    int headlen=sizeof(struct ap_header);
    int rbufLen_body=0;
    fd_set read_flags;
    fd_set write_flags;
    int selectRet;
    timeval m_waitTime;
    m_waitTime.tv_sec=waitTime/1000;
    m_waitTime.tv_usec=(waitTime%1000)*1000;
    struct ap_header header={0};
    memset(&header, 0xA5, sizeof(struct ap_header));
    bool bRes = false;
    header.HeadFlag = 0xFF;
    header.Reserved4 = 0x5A;
    header.Reserved5 = 0xA5;

    switch (type){
    case APTCPCONNECT_DEV_LOGIN:
        header.MsgId = 11000;
        header.DataLen = strlen((char *)in);
        bufLen = header.DataLen+headlen;
        break;
    case APTCPCONNECT_DEV_SETWIFI:
    case APTCPCONNECT_SET_DHCP:
    case APTCPCONNECT_SET_NTP:
    case APTCPCONNECT_SET_OSD:
    case APTCPCONNECT_SET_AP_SWAP:
        header.MsgId = 11040;
        header.SID = sessionID;
        header.DataLen = strlen((char *)in);
        bufLen = header.DataLen+headlen;
        break;
    case APTCPCONNECT_GET_DHCP:
    case APTCPCONNECT_GET_NTP:
    case APTCPCONNECT_GET_OSD:
    case APTCPCONNECT_GET_WIFI_STATUS:
        header.MsgId = 11042;
        header.SID = sessionID;
        header.DataLen = strlen((char *)in);
        bufLen = header.DataLen+headlen;
        break;
    case APTCPCONNECT_GET_ONLINE_STATUS:
        header.MsgId = 11006;
        header.SID = sessionID;
        header.DataLen = strlen((char *)in);
        bufLen = header.DataLen+headlen;
    default:
        break;
    }

    rbufheader=(char *)malloc(headlen);
    buf=(char *)malloc(bufLen);
    if(rbufheader==NULL || buf==NULL){
        err=_MALLOC_ERR;

        return false;
    }
    memset(rbufheader,0,headlen);
    memset(buf,0,bufLen);
    cur=buf;
    memcpy(cur,(char*)&header,sizeof(struct ap_header));
    cur+=sizeof(struct ap_header);
    memcpy(cur,(char*)in,bufLen-sizeof(struct ap_header));

    FD_ZERO(&write_flags);
    FD_SET(clientSocket,&write_flags);
    selectRet=select(clientSocket+1,NULL,&write_flags,NULL,&m_waitTime);
    if(selectRet<0){
        err=_SELECTSOCKET_ERR;
        goto ERREXIT;
    }else if(selectRet==0){
        err=_TIMEOUT;
        goto ERREXIT;
    }
    do{
        wlen =write(clientSocket,buf,bufLen);
        if(wlen==-1){
            if(errno==EINTR)
            {
                continue;
            } else{
                err=_WRITESOCKET_ERR;
                goto ERREXIT;
            }
        }
        break;
    }while(1);

    FD_ZERO(&read_flags);
    FD_SET(clientSocket,&read_flags);
    selectRet=select(clientSocket+1,&read_flags,NULL,NULL,&m_waitTime);
    if(selectRet<0){
        err=_SELECTSOCKET_ERR;
        goto ERREXIT;
    }else if(selectRet==0){
        err=_TIMEOUT;
        goto ERREXIT;
    }

    do{
        rlen =read(clientSocket,rbufheader,headlen);  //读取包头,获取包体长度
        if(rlen==-1){
            if(errno==EINTR)
            {
                continue;
            }
            else{
                err=_READSOCKET_ERR;
                goto ERREXIT;
            }
        }
        rcur=rbufheader;
        rbufLen_body = ((struct ap_header *)rcur)->DataLen;
        rbufbody=(char *)malloc(rbufLen_body);
        memset(rbufbody,0,rbufLen_body);
        rlen =read(clientSocket,rbufbody,rbufLen_body);  //读取包体

        if(rlen==-1){
            if(errno==EINTR)
            {
                continue;
            }else{
                err=_READSOCKET_ERR;
                goto ERREXIT;
            }
        }
        break;
    }while(1);
    rcur=rbufbody;
    switch (type) {
    case APTCPCONNECT_DEV_LOGIN:
    {
        if(rlen > 0) {
            struct LoginResponse ret;
            memset(&ret, 0, sizeof(struct LoginResponse));
            std::string temp = rcur;
            TExchangeAL<struct LoginResponse>::parseConfig(temp, ret);

            if(ret.iRet == 100)
                bRes = true;

            *((int *)out) = ret.uiSessionId;
        }
    }
        break;
    case APTCPCONNECT_GET_WIFI_STATUS:
    {
        if(rlen > 0) {
            unsigned int nSession = 0;
            int nRet = 0;
            struct NetWifiStatus ret;
            std::string temp = rcur;
            std::string name = "NetWork.WifiStatus";
            //TExchangeAL<struct NetWifiStatus>::parseConfig(temp, ret);
            TExchangeAL<struct NetWifiStatus>::parseConfig(temp, name, nSession, nRet, ret);
            if(nRet == 100) {
                bRes = true;
                *((int *)out) = ret.nWifiStatus;
            }
        }
    }
        break;
    case APTCPCONNECT_SET_DHCP:
    case APTCPCONNECT_DEV_SETWIFI:
    case APTCPCONNECT_SET_NTP:
    case APTCPCONNECT_GET_ONLINE_STATUS:
    case APTCPCONNECT_SET_AP_SWAP:
    {
        if(rlen > 0) {
            struct DefaultResponse ret;
            std::string temp = rcur;
            TExchangeAL<struct DefaultResponse>::parseConfig(temp, ret);
            if(ret.iRet == 100 || ret.iRet == 603)
                bRes = true;
        }
    }
        break;
    case APTCPCONNECT_GET_NTP:
    {
        if(rlen>0){
            NetNTPConfig ret;//=(struct NetNTPConfig*)out;
            std::string temp = rcur;
            TExchangeAL<struct NetNTPConfig>::parseConfig(temp,ret);
            strncpy((char*)out,(char*)(&ret),sizeof(NetNTPConfig));
           bRes = true;
        }
    }
        break;
    case APTCPCONNECT_GET_OSD:
    {
        if(rlen>0){
            CONFIG_VIDEOWIDGET ret;//=(struct CONFIG_VIDEOWIDGET*)out;
            std::string temp = rcur;

            TExchangeAL<struct CONFIG_VIDEOWIDGET>::parseConfig(temp, ret);


            strncpy((char*)out,(char*)(&ret),sizeof(CONFIG_VIDEOWIDGET));

            bRes = true;
        }
    }
        break;
    case APTCPCONNECT_GET_DHCP:
    {
        if(rlen>0){
            struct NetDHCPConfigAll ret;//=(struct CONFIG_VIDEOWIDGET*)out;
            std::string temp = rcur;

            TExchangeAL<struct NetDHCPConfigAll>::parseConfig(temp, ret);
            strncpy((char*)out,(char*)(&ret),sizeof(struct NetDHCPConfigAll));
            bRes = true;
        }
    }
        break;
    default:
        break;
    }
    if(rbufheader)  free(rbufheader);
    if(rbufbody)  free(rbufbody);
    if(buf)  free(buf);
    return bRes;

ERREXIT:
    if(rbufheader)  free(rbufheader);
    if(rbufbody)  free(rbufbody);
    if(buf)  free(buf);
    return false;
}
Пример #3
0
	void Event::reset()
	{
		std::unique_lock<std::mutex> lck(mtx);

		signaled = false;
	}
Пример #4
0
void LoadAlarms() {
	int num_alarms = db_get_w(0, MODULE, "Count", 0);
	char buff[256];
	DBVARIANT dbv;
	ALARM alarm;
	SYSTEMTIME now;
	GetLocalTime(&now);

	mir_cslock lck(alarm_cs);
	alarms.clear();

	for(int i = 0; i < num_alarms; i++) {
		memset(&alarm, 0, sizeof(ALARM));

		mir_snprintf(buff, "Title%d", i);
		if (!db_get_ts(0, MODULE, buff, &dbv)) {
			alarm.szTitle = mir_tstrdup(dbv.ptszVal);
			db_free(&dbv);
		}
		mir_snprintf(buff, "Desc%d", i);
		if (!db_get_ts(0, MODULE, buff, &dbv)) {
			alarm.szDesc = mir_tstrdup(dbv.ptszVal);
			db_free(&dbv);
		}
		mir_snprintf(buff, "Occ%d", i);
		alarm.occurrence = (Occurrence)db_get_w(0, MODULE, buff, 0);

		mir_snprintf(buff, "STHour%d", i);
		alarm.time.wHour = db_get_w(0, MODULE, buff, 0);
		mir_snprintf(buff, "STMinute%d", i);
		alarm.time.wMinute = db_get_w(0, MODULE, buff, 0);
		mir_snprintf(buff, "STSecond%d", i);
		alarm.time.wSecond = db_get_w(0, MODULE, buff, 0);

		switch(alarm.occurrence) {

		case OC_ONCE:
			mir_snprintf(buff, "STYear%d", i);
			alarm.time.wYear = db_get_w(0, MODULE, buff, 0);
			mir_snprintf(buff, "STMonth%d", i);
			alarm.time.wMonth = db_get_w(0, MODULE, buff, 0);
			mir_snprintf(buff, "STDay%d", i);
			alarm.time.wDay = db_get_w(0, MODULE, buff, 0);
			break;
		case OC_WEEKLY:
			mir_snprintf(buff, "STDayOfWeek%d", i);
			alarm.time.wDayOfWeek = db_get_w(0, MODULE, buff, 0);
			break;
		case OC_WEEKDAYS:
			break;
		case OC_DAILY:
			break;
		case OC_MONTHLY:
			mir_snprintf(buff, "STDay%d", i);
			alarm.time.wDay = db_get_w(0, MODULE, buff, 0);
			break;
		case OC_YEARLY:
			mir_snprintf(buff, "STMonth%d", i);
			alarm.time.wMonth = db_get_w(0, MODULE, buff, 0);
			mir_snprintf(buff, "STDay%d", i);
			alarm.time.wDay = db_get_w(0, MODULE, buff, 0);
			break;
		}

		if (UpdateAlarm(alarm.time, alarm.occurrence)) {
			mir_snprintf(buff, "ActionFlags%d", i);
			alarm.action = (unsigned short)db_get_dw(0, MODULE, buff, AAF_POPUP | AAF_SOUND);
			if (alarm.action & AAF_COMMAND) {
				mir_snprintf(buff, "ActionCommand%d", i);
				if (!db_get_ts(0, MODULE, buff, &dbv)) {
					alarm.szCommand = mir_tstrdup(dbv.ptszVal);
					db_free(&dbv);
					mir_snprintf(buff, "ActionParams%d", i);
					if (!db_get_ts(0, MODULE, buff, &dbv)) {
						alarm.szCommandParams = mir_tstrdup(dbv.ptszVal);
						db_free(&dbv);
					}
				}
			}

			mir_snprintf(buff, "SoundNum%d", i);
			alarm.sound_num = (int)db_get_b(0, MODULE, buff, 1);

			mir_snprintf(buff, "Snoozer%d", i);
			alarm.snoozer = db_get_b(0, MODULE, buff, 0) == 1;

			mir_snprintf(buff, "Hidden%d", i);
			alarm.flags |= (db_get_b(0, MODULE, buff, 0) == 1 ? ALF_HIDDEN : 0);

			mir_snprintf(buff, "Suspended%d", i);
			alarm.flags |= (db_get_b(0, MODULE, buff, 0) == 1 ? ALF_SUSPENDED : 0);

			mir_snprintf(buff, "NoStartup%d", i);
			alarm.flags |= (db_get_b(0, MODULE, buff, 0) == 1 ? ALF_NOSTARTUP : 0);

			mir_snprintf(buff, "Flags%d", i);
			alarm.flags = db_get_dw(0, MODULE, buff, alarm.flags);

			alarm.id = next_alarm_id++;
			alarms.push_back(&alarm);
		}
		free_alarm_data(&alarm);
	}
}
Пример #5
0
void GetPluginTime(SYSTEMTIME *t) {
	mir_cslock lck(alarm_cs);
	*t = last_check;
}
Пример #6
0
    Status LegacyReplicationCoordinator::processHeartbeat(const ReplSetHeartbeatArgs& args,
                                                          ReplSetHeartbeatResponse* response) {
        if (args.getProtocolVersion() != 1) {
            return Status(ErrorCodes::BadValue, "incompatible replset protocol version");
        }

        {
            if (_settings.ourSetName() != args.getSetName()) {
                log() << "replSet set names do not match, our cmdline: " << _settings.replSet
                      << rsLog;
                log() << "replSet s: " << args.getSetName() << rsLog;
                response->noteMismatched();
                return Status(ErrorCodes::BadValue, "repl set names do not match");
            }
        }

        response->noteReplSet();
        if( (theReplSet == 0) || (theReplSet->startupStatus == ReplSetImpl::LOADINGCONFIG) ) {
            if (!args.getSenderHost().empty()) {
                scoped_lock lck( _settings.discoveredSeeds_mx );
                _settings.discoveredSeeds.insert(args.getSenderHost().toString());
            }
            response->setHbMsg("still initializing");
            return Status::OK();
        }

        if (theReplSet->name() != args.getSetName()) {
            response->noteMismatched();
            return Status(ErrorCodes::BadValue, "repl set names do not match (2)");
        }
        response->setSetName(theReplSet->name());

        MemberState currentState = theReplSet->state();
        response->setState(currentState.s);
        if (currentState == MemberState::RS_PRIMARY) {
            response->setElectionTime(theReplSet->getElectionTime().asDate());
        }

        response->setElectable(theReplSet->iAmElectable());
        response->setHbMsg(theReplSet->hbmsg());
        response->setTime((long long) time(0));
        response->setOpTime(theReplSet->lastOpTimeWritten.asDate());
        const Member *syncTarget = BackgroundSync::get()->getSyncTarget();
        if (syncTarget) {
            response->setSyncingTo(syncTarget->fullName());
        }

        int v = theReplSet->config().version;
        response->setVersion(v);
        if (v > args.getConfigVersion()) {
            ReplicaSetConfig config;
            fassert(18635, config.initialize(theReplSet->config().asBson()));
            response->setConfig(config);
        }

        Member* from = NULL;
        if (v == args.getConfigVersion() && args.getSenderId() != -1) {
            from = theReplSet->getMutableMember(args.getSenderId());
        }
        if (!from) {
            from = theReplSet->findByName(args.getSenderHost().toString());
            if (!from) {
                return Status::OK();
            }
        }

        // if we thought that this node is down, let it know
        if (!from->hbinfo().up()) {
            response->noteStateDisagreement();
        }

        // note that we got a heartbeat from this node
        theReplSet->mgr->send(stdx::bind(&ReplSet::msgUpdateHBRecv,
                                         theReplSet, from->hbinfo().id(), time(0)));


        return Status::OK();
    }
Пример #7
0
void AudioChannel::FindSourceAndPlay(size_t id, const float3& pos, const float3& velocity, float volume, bool relative)
{
	std::lock_guard<spring::recursive_mutex> lck(soundMutex);

	if (!enabled)
		return;

	if (volume <= 0.0f)
		return;

	// generate the sound item
	SoundItem* sndItem = sound->GetSoundItem(id);

	if (sndItem == nullptr) {
		sound->numEmptyPlayRequests++;
		return;
	}

	// check distance to listener
	if (pos.distance(sound->GetListenerPos()) > sndItem->MaxDistance()) {
		if (!relative)
			return;

		LOG("CSound::PlaySample: maxdist ignored for relative playback: %s", sndItem->Name().c_str());
	}

	// don't spam to many sounds per frame
	if (emitsThisFrame >= emitsPerFrame)
		return;
	emitsThisFrame++;

	// check if the sound item is already played
	if (curSources.size() >= maxConcurrentSources) {
		CSoundSource* src = nullptr;

		int prio = INT_MAX;

		for (auto it = curSources.begin(); it != curSources.end(); ++it) {
			if ((*it)->GetCurrentPriority() < prio) {
				src  = *it;
				prio = src->GetCurrentPriority();
			}
		}

		if (src == nullptr || prio > sndItem->GetPriority()) {
			LOG_L(L_DEBUG, "CSound::PlaySample: Max concurrent sounds in channel reached! Dropping playback!");
			return;
		}

		src->Stop();
	}

	// find a sound source to play the item in
	CSoundSource* sndSource = sound->GetNextBestSource();

	if (sndSource == nullptr || (sndSource->GetCurrentPriority() >= sndItem->GetPriority())) {
		LOG_L(L_DEBUG, "CSound::PlaySample: Max sounds reached! Dropping playback!");
		return;
	}
	if (sndSource->IsPlaying())
		sound->numAbortedPlays++;

	// play the sound item
	sndSource->PlayAsync(this, sndItem, pos, velocity, volume, relative);
	curSources.insert(sndSource);
}
Пример #8
0
 bool BackgroundSync::isAssumingPrimary() {
     boost::unique_lock<boost::mutex> lck(_mutex);
     return _assumingPrimary;
 }
Пример #9
0
LRESULT CALLBACK TopToolBarProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static bool supressRepos = false;

	switch(msg) {
	case WM_CREATE:
		g_ctrl->hWnd = hwnd;
		PostMessage(hwnd, TTB_UPDATEFRAMEVISIBILITY, 0, 0);
		return FALSE;

	case WM_DESTROY:
		g_ctrl->hWnd = NULL;
		break;

	case WM_MOVE:
		return 0;

	case WM_WINDOWPOSCHANGING:
	case WM_SIZE:
		if (g_ctrl->nLastHeight != HIWORD(lParam)) {
			db_set_dw(0, TTB_OPTDIR, "LastHeight", g_ctrl->nLastHeight = HIWORD(lParam));
			ArrangeButtons();
		}
		if (supressRepos) {
			supressRepos = false;
			break;
		}
		// fall through

	case TTB_REPOSBUTTONS:
		if (g_ctrl->hWnd == hwnd) {
			int iHeight = ArrangeButtons();
			if ( g_ctrl->bAutoSize) {
				RECT rcClient;
				GetClientRect(g_ctrl->hWnd, &rcClient);
				rcClient.bottom -= rcClient.top;
				if (rcClient.bottom != iHeight && iHeight && rcClient.bottom) {
					supressRepos = true;
					PostMessage(hwnd, TTB_UPDATEFRAMEVISIBILITY, 0, 0);
				}
			}
			return 0;
		}
		break;

	case WM_NCPAINT:
	case WM_PAINT:
		PaintToolbar(hwnd);
		return 0;

	case WM_LBUTTONDOWN:
		if (db_get_b(NULL, "CLUI", "ClientAreaDrag", 0)) {
			POINT pt;
			GetCursorPos(&pt);
			return SendMessage(GetParent(hwnd), WM_SYSCOMMAND, SC_MOVE|HTCAPTION, MAKELPARAM(pt.x, pt.y));
		}
		return 0;

	case WM_COMMAND:
		switch (HIWORD(wParam)) {
		case BN_CLICKED:
		case BN_DOUBLECLICKED:
			{
				int id = GetWindowLongPtr((HWND)lParam, GWLP_USERDATA);
				if (id != 0) {
					mir_cslock lck(csButtonsHook);
					TopButtonInt* b = idtopos(id);
					if (b == NULL || b->isSep())
						return 0;

					if (b->dwFlags & TTBBF_ASPUSHBUTTON)
						b->bPushed = !b->bPushed;

					if (b->bPushed) { //Dn -> Up
						if (!(b->dwFlags & TTBBF_ISLBUTTON)) // must be always true
							if (b->pszService != NULL)
								CallService(b->pszService, b->wParamUp, b->lParamUp);
					}
					else { //Up -> Dn
						if (b->pszService != NULL)
							CallService(b->pszService, b->wParamDown, b->lParamDown);
					}

					b->SetBitmap();
				}
			}
			break;
		}
		break;

	case TTB_UPDATEFRAMEVISIBILITY:
		{
			bool bResize = false;

			if (g_ctrl->bAutoSize) {
				int Height = ArrangeButtons();
				INT_PTR frameopt = CallService(MS_CLIST_FRAMES_GETFRAMEOPTIONS, MAKEWPARAM(FO_HEIGHT, g_ctrl->hFrame), 0);
				if (Height != frameopt) {
					CallService(MS_CLIST_FRAMES_SETFRAMEOPTIONS, MAKEWPARAM(FO_HEIGHT, g_ctrl->hFrame), Height);
					bResize = TRUE;
				}
			}

			if (g_ctrl->bOrderChanged)
				bResize = TRUE, g_ctrl->bOrderChanged = FALSE;

			if (bResize)
				CallService(MS_CLIST_FRAMES_UPDATEFRAME, (WPARAM)g_ctrl->hFrame, FU_FMPOS);
		}
		break;

	case TTB_SETCUSTOMDATASIZE:
		g_ctrl = (TTBCtrl*)mir_realloc(g_ctrl, lParam);
		if (lParam > sizeof(TTBCtrl))
			memset(g_ctrl+1, 0, lParam - sizeof(TTBCtrl));

		SetWindowLongPtr(hwnd, 0, (LONG_PTR)g_ctrl);
		break;

	default:
		return DefWindowProc(hwnd, msg, wParam, lParam);
	}
	return TRUE;
}
Пример #10
0
 void lualambda_master::push_worker(size_t workerid) {
   std::unique_lock<graphlab::mutex> lck(mtx);
   worker_queue.push(workerid);
   lck.unlock();
   cv.notify_one();
 }
Пример #11
0
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");
	}
}
Пример #12
0
        void sync_server::receive()
        {
            int packet_size;
            int rsize;
            int rs;

            while(true)
            {
                    memset(recv_buf, 0, BUFF_SIZE);

                    //receiving head info
                    rsize = 0;
                    packet_size = UDT_PACKET_HEAD_LEN;
                    while (rsize < packet_size)
                    {
                       try
                       {
                           if (UDT::ERROR == (rs = UDT::recv(recver, recv_buf + rsize, packet_size - rsize, 0)))
                           {
                              LOG(INFO) << "recv:" << UDT::getlasterror().getErrorMessage();
                              break;
                           }
                       }
                       catch(...)
                       {
                           LOG(INFO)<<"Something was wrong in recv......";
                       }

                       rsize += rs;
                    }

                    //加锁, 开始保护结构体变量recv_packet
                    std::unique_lock<std::mutex> lck(cmd_finished_mtx);

                    if(rsize == packet_size)
                    {
                        memset(&recv_packet.head_union.head, 0, sizeof(recv_packet.head_union.head));
                        memcpy(&recv_packet.head_union.head, recv_buf, sizeof(recv_packet.head_union.head));
                        LOG(INFO)<<"cmd = "<<int2hex(ntohl(recv_packet.head_union.head.cmd))<<"; receive successful (head)......";
                    }
                    else
                    {
                        LOG(ERROR)<<"recv() fuction error (receiving head)......";
                        break;
                    }

                    recv_packet.head_union.head.cmd = ntohl(recv_packet.head_union.head.cmd);
                    recv_packet.head_union.head.total_length = ntohl(recv_packet.head_union.head.total_length);
                    recv_packet.head_union.head.cnt = ntohl(recv_packet.head_union.head.cnt);
                    recv_packet.head_union.head.check = ntohl(recv_packet.head_union.head.check);
                    recv_packet.head_union.head.priority = ntohl(recv_packet.head_union.head.priority);
                    recv_packet.head_union.head.status = ntohl(recv_packet.head_union.head.status);

                    //receive data
                    int data_len = recv_packet.head_union.head.total_length - UDT_PACKET_HEAD_LEN;

                    if(data_len == 0)
                    {
                        recv_packet.p_data = NULL;
                    }
                    else if(data_len >0)
                    {
                        memset(recv_buf, 0, BUFF_SIZE);
                        //LOG(INFO)<<"Before ::recv(data).....";

                        //receiving data...
                        rsize = 0;
                        packet_size = data_len;
                        while (rsize < packet_size)
                        {
                           //int rcv_size;
                           //int var_size = sizeof(int);
                           //UDT::getsockopt(recver, 0, UDT_RCVDATA, &rcv_size, &var_size);
                           if (UDT::ERROR == (rs = UDT::recv(recver, recv_buf + rsize, packet_size - rsize, 0)))
                           {
                              LOG(INFO) << "recv:" << UDT::getlasterror().getErrorMessage();
                              break;
                           }

                           //LOG(INFO) << "received size for this time is : "<< rs;

                           rsize += rs;
                        }

                        if(rsize == packet_size)
                        {
                            recv_packet.p_data = new char[data_len];
                            memcpy(recv_packet.p_data, recv_buf, data_len);
                        }
                        else
                        {
                            LOG(ERROR)<<"recv() fuction error (receiving data)......";
                            break;
                        }
                    }

                    //释放互斥锁cmd_finished_mutex
                    //LOG(INFO) << "Before pthread_mutex_unlock ...... ";
                    //pthread_mutex_unlock(&cmd_finished_mutex);
                    //LOG(INFO) << "After pthread_mutex_unlock ...... ";

                    /*********************此段文字有待于进一步斟酌*******************************************
                     为了确保pthread_cond_timewait(...)函数先于pthread_cond_broadcast(...)函数执行
                    此处如果用互斥锁或者是在单元函数中为pthread_cond_timewait(...)函数单独开辟线程,则程序变得非常复杂,不容易被理解。
                    同时,也不能从根本上解决问题。比如,如果是为pthread_cond_timewait(...)函数单独开辟线程,并将开辟线程代码放在
                    package_post(...)函数之前,会有如下问题:
                    1. 互斥锁或许还是先被receive线程锁住,等receive线程释放锁之后
                    2. 若在线程开辟后再加入延迟,以确保互斥锁后被receive线程锁住,则不如直接在receive的parse中加入延迟后进行广播,
                       来的容易理解和方便。
                    ***************************************************************************************/
                    usleep(10000);    //delay 10ms to ensure entering timewait... before broadcasting.......

                    //网络上接收的数据已经准备好,保存在结构体变量recv_packet中,此处发出广播
                    //LOG(INFO) << "Before pthread_cond_broadcast ...... ";
                    //pthread_cond_broadcast(&gVar::cmd_finished_cond);
                    //pthread_cond_broadcast(gVar::cmd_finished_cond_QMap[recv_packet.head_union.head.cmd]);
                    //LOG(INFO) << "After pthread_cond_broadcast ...... ";

                    //(*cmd_finished_cond_map[recv_packet.head_union.head.cmd]).notify_one();
                    parse(recv_packet);

                }
        }
Пример #13
0
        void sync_server::send()
        {
            int packet_size;
            int ssize;
            int ss;

            while(true)
            {
                std::unique_lock<std::mutex> lck(sending_mutex);
                if(send_queue.empty())
                {
                    sending_cv.wait(lck);
                }
                else
                {
                    /*********************************************************************/
                    send_packet = send_queue.top();    //取最高优先级的队列元素。。。。。。
                    send_queue.pop();                  //取出元素后,删除队列头的元素。。。。。。
                    /*********************************************************************/

                    int data_len = ntohl(send_packet.head_union.head.total_length) - UDT_PACKET_HEAD_LEN;
                    //LOG(INFO)<<"data_len is:"<<data_len<<".........................";

                    memset(send_buf, 0, sizeof(send_buf));
                    //copy head info into send_buf...........
                    memcpy(send_buf, &send_packet, sizeof(UDT_PACKET_HEAD_STRUCT));

                    //sending head info
                    packet_size = sizeof(UDT_PACKET_HEAD_STRUCT);
                    ssize = 0;
                    while (ssize < packet_size)
                    {
                      if (UDT::ERROR == (ss = UDT::send(recver, send_buf + ssize, packet_size - ssize, 0)))
                      {
                        LOG(INFO) << "send:" << UDT::getlasterror().getErrorMessage() << endl;
                        break;
                      }

                      ssize += ss;
                    }

                    if(ssize == packet_size)
                    {
                        LOG(INFO)<<"cmd = "<<int2hex(ntohl(send_packet.head_union.head.cmd))<<"; send head successful......";
                    }
                    else
                    {
                        LOG(ERROR)<<"send function error......";
                        is_connected = false;
                        break;
                    }

                    usleep(100);

                    if (data_len != 0)
                    {
                        //copy data into send_buf................
                        memcpy(send_buf + sizeof(UDT_PACKET_HEAD_STRUCT), send_packet.p_data, data_len);

                        //int bytes_sent1 = ::sendto(main_socket.socket_fd, send_buf + sizeof(NET_PACKET_HEAD_STRUCT), data_len, 0,(struct sockaddr*)&main_sockaddr_UDP,sizeof(main_sockaddr_UDP));

                        //sending data info
                        packet_size = data_len;
                        ssize = 0;
                        while (ssize < packet_size)
                        {
                          if (UDT::ERROR == (ss = UDT::send(recver, send_buf + sizeof(UDT_PACKET_HEAD_STRUCT) + ssize, packet_size - ssize, 0)))
                          {
                            LOG(INFO) << "send:" << UDT::getlasterror().getErrorMessage() << endl;
                            break;
                          }

                          ssize += ss;
                        }

                        //LOG(INFO) << "After ::send(...) function......";
                        //LOG(INFO)<<"data_len is "<<data_len;

                        if(ssize == packet_size)
                        {
                            LOG(INFO)<<"cmd = "<<int2hex(ntohl(send_packet.head_union.head.cmd))<<"; send data successful......";
                            delete[] send_packet.p_data;
                        }
                        else
                        {
                            LOG(ERROR)<<"send function error......";
                            is_connected = false;
                            break;
                        }
                    }
                }
            }
        }
Пример #14
0
STDMETHODIMP_(BOOL) CDb3Mmap::DeleteContactSetting(MCONTACT contactID, LPCSTR szModule, LPCSTR szSetting)
{
	if (!szModule || !szSetting)
		return 1;

	// the db format can't tolerate more than 255 bytes of space (incl. null) for settings+module name
	int settingNameLen = (int)mir_strlen(szSetting);
	int moduleNameLen = (int)mir_strlen(szModule);
	if (settingNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("DeleteContactSetting() got a > 255 setting name length. \n");
#endif
		return 1;
	}
	if (moduleNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("DeleteContactSetting() got a > 255 module name length. \n");
#endif
		return 1;
	}

	MCONTACT saveContact = contactID;
	{
		mir_cslock lck(m_csDbAccess);
		char *szCachedSettingName = m_cache->GetCachedSetting(szModule, szSetting, moduleNameLen, settingNameLen);
		if (szCachedSettingName[-1] == 0) { // it's not a resident variable
			DWORD ofsModuleName = GetModuleNameOfs(szModule);
			DWORD ofsContact = GetContactOffset(contactID);
			DBContact *dbc = (DBContact*)DBRead(ofsContact, NULL);
			if (dbc->signature != DBCONTACT_SIGNATURE)
				return 1;

			// make sure the module group exists
			DWORD ofsSettingsGroup = GetSettingsGroupOfsByModuleNameOfs(dbc, ofsModuleName);
			if (ofsSettingsGroup == 0)
				return 1;

			// find if the setting exists
			DWORD ofsBlobPtr = ofsSettingsGroup + offsetof(DBContactSettings, blob);
			int bytesRemaining;
			PBYTE pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
			while (pBlob[0]) {
				NeedBytes(settingNameLen + 1);
				if (pBlob[0] == settingNameLen && !memcmp(pBlob + 1, szSetting, settingNameLen))
					break;
				NeedBytes(1);
				MoveAlong(pBlob[0] + 1);
				NeedBytes(3);
				MoveAlong(1 + GetSettingValueLength(pBlob));
				NeedBytes(1);
			}
			if (!pBlob[0]) //setting didn't exist
				return 1;

			// bin it
			MoveAlong(1 + settingNameLen);
			NeedBytes(3);
			int nameLen = 1 + settingNameLen;
			int valLen = 1 + GetSettingValueLength(pBlob);
			DWORD ofsSettingToCut = ofsBlobPtr - nameLen;
			MoveAlong(valLen);
			NeedBytes(1);
			while (pBlob[0]) {
				MoveAlong(pBlob[0] + 1);
				NeedBytes(3);
				MoveAlong(1 + GetSettingValueLength(pBlob));
				NeedBytes(1);
			}
			DBMoveChunk(ofsSettingToCut, ofsSettingToCut + nameLen + valLen, ofsBlobPtr + 1 - ofsSettingToCut);
			DBFlush(1);

			// remove a value from cache anyway
			m_cache->GetCachedValuePtr(saveContact, szCachedSettingName, -1);
		}
		else { // resident variable
			// if a value doesn't exist, simply return error
			if (m_cache->GetCachedValuePtr(saveContact, szCachedSettingName, -1) == NULL)
				return 1;
		}
	}

	// notify
	DBCONTACTWRITESETTING dbcws = { 0 };
	dbcws.szModule = szModule;
	dbcws.szSetting = szSetting;
	dbcws.value.type = DBVT_DELETED;
	NotifyEventHooks(hSettingChangeEvent, saveContact, (LPARAM)&dbcws);
	return 0;
}
Пример #15
0
void Semaphore::flag() {
  std::unique_lock<std::mutex> lck(master);
  ++count;
}
Пример #16
0
//--------------------------
bool ofxTCPServer::isClientConnected(int clientID) {
    std::unique_lock<std::mutex> lck( mConnectionsLock );
    return isClientSetup(clientID) && getClient(clientID).isConnected();
}
Пример #17
0
void print_ids (int id) {
  std::unique_lock<MyMutex> lck (mtx);
  std::cout << "thread #" << id << " locked mutex " << lck.mutex()->id() << '\n';
}
Пример #18
0
void ofxTCPServer::waitConnectedClient() {
    std::unique_lock<std::mutex> lck( mConnectionsLock );
    if(TCPConnections.empty()) {
        serverReady.wait(lck);
    }
}
Пример #19
0
bool CLoadScreen::Draw()
{
	//! Limit the Frames Per Second to not lock a singlethreaded CPU from loading the game
	if (mt_loading) {
		spring_time now = spring_gettime();
		unsigned diff_ms = spring_tomsecs(now - last_draw);
		static unsigned min_frame_time = 40; //! 40ms = 25FPS
		if (diff_ms < min_frame_time) {
			spring_time nap = spring_msecs(min_frame_time - diff_ms);
			spring_sleep(nap);
		}
		last_draw = now;
	}

	//! cause of `curLoadMessage`
	boost::recursive_mutex::scoped_lock lck(mutex);

	ClearScreen();

	float xDiv = 0.0f;
	float yDiv = 0.0f;
	const float ratioComp = globalRendering->aspectRatio / aspectRatio;
	if (fabs(ratioComp - 1.0f) < 0.01f) { //! ~= 1
		//! show Load-Screen full screen
		//! nothing to do
	} else if (ratioComp > 1.0f) {
		//! show Load-Screen on part of the screens X-Axis only
		xDiv = (1.0f - (1.0f / ratioComp)) * 0.5f;
	} else {
		//! show Load-Screen on part of the screens Y-Axis only
		yDiv = (1.0f - ratioComp) * 0.5f;
	}

	//! Draw loading screen & print load msg.
	if (startupTexture) {
		glBindTexture(GL_TEXTURE_2D,startupTexture);
		glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f + xDiv, 0.0f + yDiv);
			glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f + xDiv, 1.0f - yDiv);
			glTexCoord2f(1.0f, 0.0f); glVertex2f(1.0f - xDiv, 1.0f - yDiv);
			glTexCoord2f(1.0f, 1.0f); glVertex2f(1.0f - xDiv, 0.0f + yDiv);
		glEnd();
	}

	font->Begin();
		font->SetTextColor(0.5f,0.5f,0.5f,0.9f);
		font->glPrint(0.1f,0.9f,   globalRendering->viewSizeY / 35.0f, FONT_NORM,
			oldLoadMessages);

		font->SetTextColor(0.9f,0.9f,0.9f,0.9f);
		float posy = font->GetTextNumLines(oldLoadMessages) * font->GetLineHeight() * globalRendering->viewSizeY / 35.0f;
		font->glPrint(0.1f,0.9f - posy * globalRendering->pixelY,   globalRendering->viewSizeY / 35.0f, FONT_NORM,
			curLoadMessage);


		font->SetOutlineColor(0.0f,0.0f,0.0f,0.65f);
		font->SetTextColor(1.0f,1.0f,1.0f,1.0f);
#ifdef USE_GML
		font->glFormat(0.5f,0.06f, globalRendering->viewSizeY / 35.0f, FONT_OUTLINE | FONT_CENTER | FONT_NORM,
			"Spring %s (%d threads)", SpringVersion::GetFull().c_str(), gmlThreadCount);
#else
		font->glFormat(0.5f,0.06f, globalRendering->viewSizeY / 35.0f, FONT_OUTLINE | FONT_CENTER | FONT_NORM,
			"Spring %s", SpringVersion::GetFull().c_str());
#endif
		font->glFormat(0.5f,0.02f, globalRendering->viewSizeY / 50.0f, FONT_OUTLINE | FONT_CENTER | FONT_NORM,
			"This program is distributed under the GNU General Public License, see license.html for more info");
	font->End();

	if (!mt_loading)
		SDL_GL_SwapBuffers();

	return true;
}
Пример #20
0
void ofxTCPServer::waitConnectedClient(int ms) {
    std::unique_lock<std::mutex> lck( mConnectionsLock );
    if(TCPConnections.empty()) {
        serverReady.wait_for(lck, std::chrono::milliseconds(ms));
    }
}
Пример #21
0
 void atomic_func(F &f)
 {
    scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock);
    f();
 }
Пример #22
0
//--------------------------
bool ofxTCPServer::disconnectAllClients() {
    std::unique_lock<std::mutex> lck( mConnectionsLock );
    TCPConnections.clear();
    return true;
}
Пример #23
0
void SaveAlarms() {
	int index = 0;
	char buff[256];

	mir_cslock lck(alarm_cs);

	ALARM *i;
	for(alarms.reset(); i = alarms.current(); alarms.next(), index++) {
		mir_snprintf(buff, "Title%d", index);
		db_set_ts(0, MODULE, buff, i->szTitle);
		mir_snprintf(buff, "Desc%d", index);
		db_set_ts(0, MODULE, buff, i->szDesc);
		mir_snprintf(buff, "Occ%d", index);
		db_set_w(0, MODULE, buff, i->occurrence);

		mir_snprintf(buff, "STHour%d", index);
		db_set_w(0, MODULE, buff, i->time.wHour);
		mir_snprintf(buff, "STMinute%d", index);
		db_set_w(0, MODULE, buff, i->time.wMinute);
		mir_snprintf(buff, "STSecond%d", index);
		db_set_w(0, MODULE, buff, i->time.wSecond);

		switch(i->occurrence) {
		case OC_DAILY:
			break;
		case OC_WEEKDAYS:
			break;
		case OC_WEEKLY:
			mir_snprintf(buff, "STDayOfWeek%d", index);
			db_set_w(0, MODULE, buff, i->time.wDayOfWeek);
			break;

		case OC_ONCE:
			mir_snprintf(buff, "STYear%d", index);
			db_set_w(0, MODULE, buff, i->time.wYear);
		case OC_YEARLY:
			mir_snprintf(buff, "STMonth%d", index);
			db_set_w(0, MODULE, buff, i->time.wMonth);
		case OC_MONTHLY:
			mir_snprintf(buff, "STDay%d", index);
			db_set_w(0, MODULE, buff, i->time.wDay);
			break;
		}
		mir_snprintf(buff, "ActionFlags%d", index);
		db_set_dw(0, MODULE, buff, i->action);
		if (i->action & AAF_COMMAND) {
			if (mir_tstrlen(i->szCommand)) {
				mir_snprintf(buff, "ActionCommand%d", index);
				db_set_ts(0, MODULE, buff, i->szCommand);
				if (mir_tstrlen(i->szCommandParams)) {
					mir_snprintf(buff, "ActionParams%d", index);
					db_set_ts(0, MODULE, buff, i->szCommandParams);
				}
			}
		}
		
		mir_snprintf(buff, "SoundNum%d", index);
		db_set_b(0, MODULE, buff, i->sound_num);

		mir_snprintf(buff, "Snoozer%d", index);
		db_set_b(0, MODULE, buff, i->snoozer ? 1 : 0);

		mir_snprintf(buff, "Flags%d", index);
		db_set_dw(0, MODULE, buff, i->flags);
	}
	db_set_w(0, MODULE, "Count", index);
}
/**
* Locks rectangle on both (left/right) surfaces.
***/
HRESULT WINAPI D3D9ProxySurface::LockRect(D3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags)
{
	SHOW_CALL("D3D9ProxySurface::LockRect");

	D3DSURFACE_DESC desc;
	m_pActualSurface->GetDesc(&desc);
	if (desc.Pool != D3DPOOL_DEFAULT)
	{
		//Can't really handle stereo for this, so just lock on the original texture
		return m_pActualSurface->LockRect(pLockedRect, pRect, Flags);
	}

	//Guard against multithreaded access as this could be causing us problems
	std::lock_guard<std::mutex> lck (m_mtx);

	//Create lockable system memory surfaces
	if (pRect && !fullSurface)
	{
		lockedRects.push_back(*pRect);
	}
	else
	{
		lockedRects.clear();
		fullSurface = true;
	}

	HRESULT hr = D3DERR_INVALIDCALL;
	IDirect3DSurface9 *pSurface = NULL;
	bool createdTexture = false;
	if (!lockableSysMemTexture)
	{
		hr = m_pOwningDevice->getActual()->CreateTexture(desc.Width, desc.Height, 1, 0, 
			desc.Format, D3DPOOL_SYSTEMMEM, &lockableSysMemTexture, NULL);

		if (FAILED(hr))
			return hr;

		createdTexture = true;
	}

	lockableSysMemTexture->GetSurfaceLevel(0, &pSurface);

	//Only copy the render taget (if possible) on the creation of the memory texture
	if (createdTexture)
	{
		hr = D3DXLoadSurfaceFromSurface(pSurface, NULL, NULL, m_pActualSurface, NULL, NULL, D3DX_DEFAULT, 0);
		if (FAILED(hr))
		{
#ifdef _DEBUG
			vireio::debugf("Failed: D3DXLoadSurfaceFromSurface hr = 0x%0.8x", hr);
#endif
		}
	}

	//And finally, lock the memory surface
	hr = pSurface->LockRect(pLockedRect, pRect, Flags);
	if (FAILED(hr))
		return hr;

	lockedRect = *pLockedRect;

	pSurface->Release();

	return hr;
}
Пример #25
0
// wait for the next request to complete
HRESULT
CAsyncIo::WaitForNext(
    DWORD dwTimeout,
    LPVOID     * ppContext,
    DWORD_PTR  * pdwUser,
    LONG       * pcbActual)
{
    CheckPointer(ppContext,E_POINTER);
    CheckPointer(pdwUser,E_POINTER);
    CheckPointer(pcbActual,E_POINTER);

    // some errors find a sample, others don't. Ensure that
    // *ppContext is NULL if no sample found
    *ppContext = NULL;

    // wait until the event is set, but since we are not
    // holding the critsec when waiting, we may need to re-wait
    for(;;)
    {
        if(!m_evDone.Wait(dwTimeout))
        {
            // timeout occurred
            return VFW_E_TIMEOUT;
        }

        // get next event from list
        CAsyncRequest* pRequest = GetDoneItem();
        if(pRequest)
        {
            // found a completed request

            // check if ok
            HRESULT hr = pRequest->GetHResult();
            if(hr == S_FALSE)
            {
                // this means the actual length was less than
                // requested - may be ok if he aligned the end of file
                if((pRequest->GetActualLength() +
                    pRequest->GetStart()) == Size())
                {
                    hr = S_OK;
                }
                else
                {
                    // it was an actual read error
                    hr = E_FAIL;
                }
            }

            // return actual bytes read
            *pcbActual = pRequest->GetActualLength();

            // return his context
            *ppContext = pRequest->GetContext();
            *pdwUser = pRequest->GetUser();

            delete pRequest;
            return hr;
        }
        else
        {
            //  Hold the critical section while checking the list state
            CAutoLock lck(&m_csLists);
            if(m_bFlushing && !m_bWaiting)
            {
                // can't block as we are between BeginFlush and EndFlush

                // but note that if m_bWaiting is set, then there are some
                // items not yet complete that we should block for.

                return VFW_E_WRONG_STATE;
            }
        }

        // done item was grabbed between completion and
        // us locking m_csLists.
    }
}
/**
* Unlocks rectangle on both (left/right) surfaces.
***/
HRESULT WINAPI D3D9ProxySurface::UnlockRect()
{
	SHOW_CALL("D3D9ProxySurface::UnlockRect");

	D3DSURFACE_DESC desc;
	m_pActualSurface->GetDesc(&desc);
	if (desc.Pool != D3DPOOL_DEFAULT)
	{
		return m_pActualSurface->UnlockRect();
	}

	//Guard against multithreaded access as this could be causing us problems
	std::lock_guard<std::mutex> lck (m_mtx);

	//This would mean nothing to do
	if (lockedRects.size() == 0 && !fullSurface)
		return S_OK;

	IDirect3DSurface9 *pSurface = NULL;
	HRESULT hr = lockableSysMemTexture ? lockableSysMemTexture->GetSurfaceLevel(0, &pSurface) : D3DERR_INVALIDCALL;
	if (FAILED(hr))
		return hr;

	hr = pSurface->UnlockRect();

	if (IsStereo())
	{
		if (fullSurface)
		{
			hr = m_pOwningDevice->getActual()->UpdateSurface(pSurface, NULL, m_pActualSurfaceRight, NULL);
			if (FAILED(hr))
				WriteDesc(desc);
		}
		else
		{
			std::vector<RECT>::iterator rectIter = lockedRects.begin();
			while (rectIter != lockedRects.end())
			{
				POINT p;
				p.x = rectIter->left;
				p.y = rectIter->top;
				hr = m_pOwningDevice->getActual()->UpdateSurface(pSurface, &(*rectIter), m_pActualSurfaceRight, &p);
				if (FAILED(hr))
					WriteDesc(desc);
				rectIter++;
			}
		}
	}

	if (fullSurface)
	{
		hr = m_pOwningDevice->getActual()->UpdateSurface(pSurface, NULL, m_pActualSurface, NULL);
		if (FAILED(hr))
			WriteDesc(desc);
	}
	else
	{
		std::vector<RECT>::iterator rectIter = lockedRects.begin();
		while (rectIter != lockedRects.end())
		{
			POINT p;
			p.x = rectIter->left;
			p.y = rectIter->top;
			hr = m_pOwningDevice->getActual()->UpdateSurface(pSurface, &(*rectIter), m_pActualSurface, &p);
			if (FAILED(hr))
				WriteDesc(desc);
			rectIter++;
		}
	}

	pSurface->Release();

	fullSurface = false;
	return hr;
}
Пример #27
0
	void Event::notify()
	{
		std::unique_lock<std::mutex> lck(mtx);
		signaled = true;
		cv.notify_all();
	}
void CBaseStreamControl::Flushing(BOOL bInProgress)
{
    CAutoLock lck(&m_CritSec);
    m_bIsFlushing = bInProgress;
    m_StreamEvent.Set();
}
Пример #29
0
	bool Event::notifed()
	{
		std::unique_lock<std::mutex> lck(mtx);

		return signaled;
	}
Пример #30
0
STDMETHODIMP_(BOOL) CDb3Mmap::WriteContactSetting(MCONTACT contactID, DBCONTACTWRITESETTING *dbcws)
{
	if (dbcws == NULL || dbcws->szSetting == NULL || dbcws->szModule == NULL || m_bReadOnly)
		return 1;

	// the db format can't tolerate more than 255 bytes of space (incl. null) for settings+module name
	int settingNameLen = (int)mir_strlen(dbcws->szSetting);
	int moduleNameLen = (int)mir_strlen(dbcws->szModule);
	if (settingNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("WriteContactSetting() got a > 255 setting name length. \n");
#endif
		return 1;
	}
	if (moduleNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("WriteContactSetting() got a > 255 module name length. \n");
#endif
		return 1;
	}

	// used for notifications
	DBCONTACTWRITESETTING dbcwNotif = *dbcws;
	if (dbcwNotif.value.type == DBVT_WCHAR) {
		if (dbcwNotif.value.pszVal != NULL) {
			char* val = mir_utf8encodeW(dbcwNotif.value.pwszVal);
			if (val == NULL)
				return 1;

			dbcwNotif.value.pszVal = (char*)alloca(mir_strlen(val) + 1);
			mir_strcpy(dbcwNotif.value.pszVal, val);
			mir_free(val);
			dbcwNotif.value.type = DBVT_UTF8;
		}
		else return 1;
	}

	if (dbcwNotif.szModule == NULL || dbcwNotif.szSetting == NULL)
		return 1;

	DBCONTACTWRITESETTING dbcwWork = dbcwNotif;

	mir_ptr<BYTE> pEncoded(NULL);
	bool bIsEncrypted = false;
	switch (dbcwWork.value.type) {
	case DBVT_BYTE: case DBVT_WORD: case DBVT_DWORD:
		break;

	case DBVT_ASCIIZ: case DBVT_UTF8:
		bIsEncrypted = m_bEncrypted || IsSettingEncrypted(dbcws->szModule, dbcws->szSetting);
	LBL_WriteString:
		if (dbcwWork.value.pszVal == NULL)
			return 1;
		dbcwWork.value.cchVal = (WORD)mir_strlen(dbcwWork.value.pszVal);
		if (bIsEncrypted) {
			size_t len;
			BYTE *pResult = m_crypto->encodeString(dbcwWork.value.pszVal, &len);
			if (pResult != NULL) {
				pEncoded = dbcwWork.value.pbVal = pResult;
				dbcwWork.value.cpbVal = (WORD)len;
				dbcwWork.value.type = DBVT_ENCRYPTED;
			}
		}
		break;

	case DBVT_UNENCRYPTED:
		dbcwNotif.value.type = dbcwWork.value.type = DBVT_UTF8;
		goto LBL_WriteString;

	case DBVT_BLOB: case DBVT_ENCRYPTED:
		if (dbcwWork.value.pbVal == NULL)
			return 1;
		break;
	default:
		return 1;
	}

	mir_cslockfull lck(m_csDbAccess);

	DWORD ofsBlobPtr, ofsContact = GetContactOffset(contactID);
	if (ofsContact == 0) {
		_ASSERT(false); // contact doesn't exist?
		return 2;
	}

	char *szCachedSettingName = m_cache->GetCachedSetting(dbcwWork.szModule, dbcwWork.szSetting, moduleNameLen, settingNameLen);
	log3("set [%08p] %s (%p)", hContact, szCachedSettingName, szCachedSettingName);

	// we don't cache blobs and passwords
	if (dbcwWork.value.type != DBVT_BLOB && dbcwWork.value.type != DBVT_ENCRYPTED && !bIsEncrypted) {
		DBVARIANT *pCachedValue = m_cache->GetCachedValuePtr(contactID, szCachedSettingName, 1);
		if (pCachedValue != NULL) {
			bool bIsIdentical = false;
			if (pCachedValue->type == dbcwWork.value.type) {
				switch (dbcwWork.value.type) {
				case DBVT_BYTE:   bIsIdentical = pCachedValue->bVal == dbcwWork.value.bVal;  break;
				case DBVT_WORD:   bIsIdentical = pCachedValue->wVal == dbcwWork.value.wVal;  break;
				case DBVT_DWORD:  bIsIdentical = pCachedValue->dVal == dbcwWork.value.dVal;  break;
				case DBVT_UTF8:
				case DBVT_ASCIIZ: bIsIdentical = mir_strcmp(pCachedValue->pszVal, dbcwWork.value.pszVal) == 0; break;
				}
				if (bIsIdentical)
					return 0;
			}
			m_cache->SetCachedVariant(&dbcwWork.value, pCachedValue);
		}
		if (szCachedSettingName[-1] != 0) {
			lck.unlock();
			log2(" set resident as %s (%p)", printVariant(&dbcwWork.value), pCachedValue);
			NotifyEventHooks(hSettingChangeEvent, contactID, (LPARAM)&dbcwWork);
			return 0;
		}
	}
	else m_cache->GetCachedValuePtr(contactID, szCachedSettingName, -1);

	log1(" write database as %s", printVariant(&dbcwWork.value));

	DWORD ofsModuleName = GetModuleNameOfs(dbcwWork.szModule);
	DBContact dbc = *(DBContact*)DBRead(ofsContact, NULL);
	if (dbc.signature != DBCONTACT_SIGNATURE)
		return 1;

	// make sure the module group exists
	PBYTE pBlob;
	int bytesRequired, bytesRemaining;
	DBContactSettings dbcs;
	DWORD ofsSettingsGroup = GetSettingsGroupOfsByModuleNameOfs(&dbc, ofsModuleName);
	if (ofsSettingsGroup == 0) {  //module group didn't exist - make it
		switch (dbcwWork.value.type) {
		case DBVT_ASCIIZ: case DBVT_UTF8:
			bytesRequired = dbcwWork.value.cchVal + 2;
			break;
		case DBVT_BLOB: case DBVT_ENCRYPTED:
			bytesRequired = dbcwWork.value.cpbVal + 2;
			break;
		default:
			bytesRequired = dbcwWork.value.type;
		}
		bytesRequired += 2 + settingNameLen;
		bytesRequired += (DB_SETTINGS_RESIZE_GRANULARITY - (bytesRequired % DB_SETTINGS_RESIZE_GRANULARITY)) % DB_SETTINGS_RESIZE_GRANULARITY;
		ofsSettingsGroup = CreateNewSpace(bytesRequired + offsetof(DBContactSettings, blob));
		dbcs.signature = DBCONTACTSETTINGS_SIGNATURE;
		dbcs.ofsNext = dbc.ofsFirstSettings;
		dbcs.ofsModuleName = ofsModuleName;
		dbcs.cbBlob = bytesRequired;
		dbcs.blob[0] = 0;
		dbc.ofsFirstSettings = ofsSettingsGroup;
		DBWrite(ofsContact, &dbc, sizeof(DBContact));
		DBWrite(ofsSettingsGroup, &dbcs, sizeof(DBContactSettings));
		ofsBlobPtr = ofsSettingsGroup + offsetof(DBContactSettings, blob);
		pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
	}
	else {
		dbcs = *(DBContactSettings*)DBRead(ofsSettingsGroup, &bytesRemaining);

		// find if the setting exists
		ofsBlobPtr = ofsSettingsGroup + offsetof(DBContactSettings, blob);
		pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
		while (pBlob[0]) {
			NeedBytes(settingNameLen + 1);
			if (pBlob[0] == settingNameLen && !memcmp(pBlob + 1, dbcwWork.szSetting, settingNameLen))
				break;
			NeedBytes(1);
			MoveAlong(pBlob[0] + 1);
			NeedBytes(3);
			MoveAlong(1 + GetSettingValueLength(pBlob));
			NeedBytes(1);
		}

		// setting already existed, and up to end of name is in cache
		if (pBlob[0]) {
			MoveAlong(1 + settingNameLen);
			// if different type or variable length and length is different
			NeedBytes(3);
			if (pBlob[0] != dbcwWork.value.type ||
				((pBlob[0] == DBVT_ASCIIZ || pBlob[0] == DBVT_UTF8) && *(PWORD)(pBlob + 1) != dbcwWork.value.cchVal) ||
				((pBlob[0] == DBVT_BLOB || pBlob[0] == DBVT_ENCRYPTED) && *(PWORD)(pBlob + 1) != dbcwWork.value.cpbVal))
			{
				// bin it
				NeedBytes(3);
				int nameLen = 1 + settingNameLen;
				int valLen = 1 + GetSettingValueLength(pBlob);
				DWORD ofsSettingToCut = ofsBlobPtr - nameLen;
				MoveAlong(valLen);
				NeedBytes(1);
				while (pBlob[0]) {
					MoveAlong(pBlob[0] + 1);
					NeedBytes(3);
					MoveAlong(1 + GetSettingValueLength(pBlob));
					NeedBytes(1);
				}
				DBMoveChunk(ofsSettingToCut, ofsSettingToCut + nameLen + valLen, ofsBlobPtr + 1 - ofsSettingToCut);
				ofsBlobPtr -= nameLen + valLen;
				pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
			}
			else {
				// replace existing setting at pBlob
				MoveAlong(1);	// skip data type
				switch (dbcwWork.value.type) {
				case DBVT_BYTE:  DBWrite(ofsBlobPtr, &dbcwWork.value.bVal, 1); break;
				case DBVT_WORD:  DBWrite(ofsBlobPtr, &dbcwWork.value.wVal, 2); break;
				case DBVT_DWORD: DBWrite(ofsBlobPtr, &dbcwWork.value.dVal, 4); break;
				case DBVT_BLOB:
					DBWrite(ofsBlobPtr + 2, dbcwWork.value.pbVal, dbcwWork.value.cpbVal);
					break;
				case DBVT_ENCRYPTED:
					DBWrite(ofsBlobPtr + 2, dbcwWork.value.pbVal, dbcwWork.value.cpbVal);
					break;
				case DBVT_UTF8:
				case DBVT_ASCIIZ:
					DBWrite(ofsBlobPtr + 2, dbcwWork.value.pszVal, dbcwWork.value.cchVal);
					break;
				}
				// quit
				DBFlush(1);
				lck.unlock();
				// notify
				NotifyEventHooks(hSettingChangeEvent, contactID, (LPARAM)&dbcwNotif);
				return 0;
			}
		}
	}

	// cannot do a simple replace, add setting to end of list
	// pBlob already points to end of list
	// see if it fits
	switch (dbcwWork.value.type) {
	case DBVT_ASCIIZ: case DBVT_UTF8:
		bytesRequired = dbcwWork.value.cchVal + 2;
		break;
	case DBVT_BLOB: case DBVT_ENCRYPTED:
		bytesRequired = dbcwWork.value.cpbVal + 2;
		break;
	default:
		bytesRequired = dbcwWork.value.type;
	}

	bytesRequired += 2 + settingNameLen;
	bytesRequired += ofsBlobPtr + 1 - (ofsSettingsGroup + offsetof(DBContactSettings, blob));

	if ((DWORD)bytesRequired > dbcs.cbBlob) {
		// doesn't fit: move entire group
		DBContactSettings *dbcsPrev;
		DWORD ofsDbcsPrev, ofsNew;

		InvalidateSettingsGroupOfsCacheEntry(ofsSettingsGroup);
		bytesRequired += (DB_SETTINGS_RESIZE_GRANULARITY - (bytesRequired % DB_SETTINGS_RESIZE_GRANULARITY)) % DB_SETTINGS_RESIZE_GRANULARITY;
		// find previous group to change its offset
		ofsDbcsPrev = dbc.ofsFirstSettings;
		if (ofsDbcsPrev == ofsSettingsGroup) ofsDbcsPrev = 0;
		else {
			dbcsPrev = (DBContactSettings*)DBRead(ofsDbcsPrev, NULL);
			while (dbcsPrev->ofsNext != ofsSettingsGroup) {
				if (dbcsPrev->ofsNext == 0) DatabaseCorruption(NULL);
				ofsDbcsPrev = dbcsPrev->ofsNext;
				dbcsPrev = (DBContactSettings*)DBRead(ofsDbcsPrev, NULL);
			}
		}

		// create the new one
		ofsNew = ReallocSpace(ofsSettingsGroup, dbcs.cbBlob + offsetof(DBContactSettings, blob), bytesRequired + offsetof(DBContactSettings, blob));

		dbcs.cbBlob = bytesRequired;

		DBWrite(ofsNew, &dbcs, offsetof(DBContactSettings, blob));
		if (ofsDbcsPrev == 0) {
			dbc.ofsFirstSettings = ofsNew;
			DBWrite(ofsContact, &dbc, sizeof(DBContact));
		}
		else {
			dbcsPrev = (DBContactSettings*)DBRead(ofsDbcsPrev, NULL);
			dbcsPrev->ofsNext = ofsNew;
			DBWrite(ofsDbcsPrev, dbcsPrev, offsetof(DBContactSettings, blob));
		}
		ofsBlobPtr += ofsNew - ofsSettingsGroup;
		ofsSettingsGroup = ofsNew;
		pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
	}

	// we now have a place to put it and enough space: make it
	DBWrite(ofsBlobPtr, &settingNameLen, 1);
	DBWrite(ofsBlobPtr + 1, (PVOID)dbcwWork.szSetting, settingNameLen);
	MoveAlong(1 + settingNameLen);
	DBWrite(ofsBlobPtr, &dbcwWork.value.type, 1);
	MoveAlong(1);
	switch (dbcwWork.value.type) {
	case DBVT_BYTE: DBWrite(ofsBlobPtr, &dbcwWork.value.bVal, 1); MoveAlong(1); break;
	case DBVT_WORD: DBWrite(ofsBlobPtr, &dbcwWork.value.wVal, 2); MoveAlong(2); break;
	case DBVT_DWORD: DBWrite(ofsBlobPtr, &dbcwWork.value.dVal, 4); MoveAlong(4); break;

	case DBVT_BLOB:
		DBWrite(ofsBlobPtr, &dbcwWork.value.cpbVal, 2);
		DBWrite(ofsBlobPtr + 2, dbcwWork.value.pbVal, dbcwWork.value.cpbVal);
		MoveAlong(2 + dbcwWork.value.cpbVal);
		break;

	case DBVT_ENCRYPTED:
		DBWrite(ofsBlobPtr, &dbcwWork.value.cpbVal, 2);
		DBWrite(ofsBlobPtr + 2, dbcwWork.value.pbVal, dbcwWork.value.cpbVal);
		MoveAlong(2 + dbcwWork.value.cpbVal);
		break;

	case DBVT_UTF8: case DBVT_ASCIIZ:
		DBWrite(ofsBlobPtr, &dbcwWork.value.cchVal, 2);
		DBWrite(ofsBlobPtr + 2, dbcwWork.value.pszVal, dbcwWork.value.cchVal);
		MoveAlong(2 + dbcwWork.value.cchVal);
		break;
	}

	BYTE zero = 0;
	DBWrite(ofsBlobPtr, &zero, 1);

	// quit
	DBFlush(1);
	lck.unlock();

	// notify
	NotifyEventHooks(hSettingChangeEvent, contactID, (LPARAM)&dbcwNotif);
	return 0;
}