bool cpiPython::OnParsedMsgChat(cConnDC *conn, cMessageDC *msg) { if (!online) return true; if((conn != NULL) && (conn->mpUser != NULL) && (msg != NULL)) { int func = W_OnParsedMsgChat; w_Targs* args = lib_pack( "ss", conn->mpUser->mNick.c_str(), msg->ChunkString(eCH_CH_MSG).c_str()); log2("PY: Call %s: parameters %s\n", lib_hookname(func), lib_packprint(args)); bool ret = true; w_Targs *result; long l; char *nick = NULL; char *message = NULL; if(Size()) { tvPythonInterpreter::iterator it; for(it = mPython.begin(); it != mPython.end(); ++it) { result = (*it)->CallFunction(func, args); if(!result) { log3("PY: Call %s: returned NULL\n", lib_hookname(func)); continue; } if(lib_unpack(result, "l", &l)) // default return value is 1L meaning: further processing, { log3("PY: Call %s: returned l:%ld\n", lib_hookname(func), l); if (!l) ret = false; // 0L means no more processing outside this plugin } else if (lib_unpack(result, "ss", &nick, &message)) // script wants to change nick or contents of the message { // normally you would use SendDataToAll and return 0 from your script // but this kind of message modification allows you to process it not by just one but as many scripts as you want log2("PY: modifying message - Call %s: returned %s\n", lib_hookname(func), lib_packprint(result)); if (nick) { string &nick0 = msg->ChunkString(eCH_CH_NICK); nick0 = nick; msg->ApplyChunk(eCH_CH_NICK); } if (message) { string &message0 = msg->ChunkString(eCH_CH_MSG); message0 = message; msg->ApplyChunk(eCH_CH_MSG); } ret = true; // we've changed the message so we want the hub to process it and send it } else // something unknown was returned... we will let the hub call other plugins log1("PY: Call %s: unexpected return value: %s\n", lib_hookname(func), lib_packprint(result)); free(result); } } free(args); return ret; } return true; }
/* @Core */ Mat PDCounter::detect(Mat& input) { string log1("Begin detecting...\n"); Mat output = input.clone(); for (vector<PDDetector>::iterator it = Detectors.begin(); it != Detectors.end(); it++) { (*it).detect(output, Trackers);// NO parallel } string log2("All areas are detected...\n"); string lost = i_to_s(Trackers.tracking(output)); // NO parallel string log3("Tracking completed...\nThe trackers lost " + lost + " pedestrians in this frame.\n"); if (showPedestrian) { drawFounds(output, Trackers.getCurrRects(), PEDESTRIAN_COLOR); } if (showArea) { for (vector<PDDetector>::iterator it = Detectors.begin(); it != Detectors.end(); it++) { drawArea(output, (*it).getArea(), AREA_COLOR); } } if (showTrajectory) { for (int i = 0; i < Trackers.getSize(); i++) { drawTrajectory(output, Trackers[i].getTrajectory(), Trajectory_COLOR); } } string log4("Drawing completed"); lastLog = log1 + log2 + log3 + log4; return output; }
bool cpiPython::CallAll(int func, w_Targs* args) // the default handler: returns true unless the calback returns 0 { if (!online) return true; w_Targs* result; bool ret = true; long l; if (func != W_OnTimer) log2("PY: CallAll %s: parameters %s\n", lib_hookname(func), lib_packprint(args)) // no ';' since this would break 'else' else log4("PY: CallAll %s\n", lib_hookname(func)); if(Size()) { tvPythonInterpreter::iterator it; for(it = mPython.begin(); it != mPython.end(); ++it) { result = (*it)->CallFunction(func, args); if(!result) { // callback doesn't exist or a failure if (func != W_OnTimer) log4("PY: CallAll %s: returned NULL\n", lib_hookname(func)); continue; } if(lib_unpack(result, "l", &l)) // default return value is 1L meaning: further processing, { if (func != W_OnTimer) log3("PY: CallAll %s: returned l:%ld\n", lib_hookname(func), l); if (!l) ret = false; // 0L means no more processing outside this plugin } else // something unknown was returned... we will let the hub call other plugins { log1("PY: CallAll %s: unexpected return value %s\n", lib_hookname(func), lib_packprint(result)); } free(result); } } free(args); // WARNING: args is freed, do not try to access it after calling CallAll! return ret; }
void ReMap(DWORD needed) { KillTimer(NULL,flushBuffersTimerId); log3("remapping %d + %d (file end: %d)",dwFileSize,needed,dbHeader.ofsFileEnd); if (needed > ChunkSize) { if ((needed + dwFileSize) - dbHeader.ofsFileEnd > ChunkSize) DatabaseCorruption( _T("%s (Too large increment)")); else { DWORD x = dbHeader.ofsFileEnd/ChunkSize; dwFileSize = (x+1)*ChunkSize; } } else dwFileSize += ChunkSize; // FlushViewOfFile(pDbCache, 0); UnmapViewOfFile(pDbCache); pDbCache = NULL; CloseHandle(hMap); Map(); }
/// \brief Log: SE3 -> se3. /// /// Pseudo-inverse of exp from SE3 -> { v,w \in se3, ||w|| < 2pi }. template <typename _Scalar, int _Options> MotionTpl<_Scalar,_Options> log6(const SE3Tpl<_Scalar, _Options> & m) { typedef _Scalar Scalar; typedef typename SE3Tpl<Scalar,_Options>::Vector3 Vector3; typedef typename SE3Tpl<Scalar,_Options>::Matrix3 Matrix3; const Matrix3 & R = m.rotation(); const Vector3 & p = m.translation(); Vector3 w(log3(R)); Vector3 v; Scalar t = w.norm(); if (t > 1e-15) { Matrix3 S(skew(w)); double ct,st; SINCOS (t,&st,&ct); Matrix3 V( Matrix3::Identity() + (1 - ct) / (t * t) * S + (t - st) / (t * t * t) * S * S); v = V.inverse() * p; } else { v = p; } return MotionTpl<_Scalar,_Options>(v, w); }
void die_controls() { if (control_last.s) { log3("alert: cannot start: unable to read controls (", control_last.s, ")\n"); } else { log1("alert: cannot start: unable to read controls\n"); } _exit(111); }
void updateAllMiners(IMP) { register ULONG ship; register Ship_t *rsh; /* set up the pointer */ rsh = &IS->is_request.rq_u.ru_ship; #ifdef DEBUG_LIB if (IS->is_DEBUG) { log3(IS, ">>> In updateAllMiners", "", ""); } #endif /* loop through all the ships in the world looking for miners */ for (ship = 0; ship < IS->is_world.w_shipNext; ship++) { /* read the current ship in */ server(IS, rt_readShip, ship); /* if it is a miner, update it */ if ((rsh->sh_type == st_m) && (rsh->sh_owner != NO_OWNER)) { #ifdef DEBUG_LIB if (IS->is_DEBUG) { char numBuff[80]; sprintf(&numBuff[0], "%lu", ship); log3(IS, "!!! About to lock miner ", &numBuff[0], ""); } #endif server(IS, rt_lockShip, ship); updateMiner(IS); server(IS, rt_unlockShip, ship); } } #ifdef DEBUG_LIB if (IS->is_DEBUG) { log3(IS, "<<< Out of updateAllMiners", "", ""); } #endif }
bool cpiPython::SetConf(const char *conf, const char *var, const char *val) { if (!conf || !var || !val) { log2("PY: SetConf: wrong parameters\n"); return false; } // first let's check hub's internal config: if(!strcmp(conf, "config")) { string file(server->mDBConf.config_name); cConfigItemBase *ci = NULL; if(file == server->mDBConf.config_name) { ci = server->mC[var]; if (ci) { ci->ConvertFrom(val); log3("PY: SetConf set the value directly in mDBConf to: %s\n", val); return true; } } return false; /*if (SetConfig((char*)conf, (char*)var, (char*)val)) return true; return false;*/ } // let's try searching the database directly: if (!lib_begin || !lib_pack || !lib_unpack || !lib_packprint) return false; log3("PY: SetConf file != 'config', file == '%s'\n", conf); string query = string() + "delete from SetupList where file='" + conf + "' and var='" + var + "'"; w_Targs *a = lib_pack( "sl", query.c_str(), (long)1 ); log3("PY: SetConf calling SQL with params: %s\n", lib_packprint(a)); w_Targs *ret = SQL (-2, a); if (a) free(a); long res, rows, cols; char **list; log3("PY: SetConf SQL returned %s\n", lib_packprint(ret)); if (!lib_unpack( ret, "lllp", &res, &rows, &cols, (void**) &list )) { log3("PY: SetConf call to SQL function failed\n"); freee(ret); return false; } freee(ret->args[3].p); freee(ret); if (!res) { log2("requested config variable ( %s in %s ) does not exist\n", var, conf); }; query = string("") + "insert into SetupList (file, var, val) values ('" + conf + "', '" + var + "', '" + val + "')"; a = lib_pack( "sl", query.c_str(), (long)1 ); log3("PY: SetConf calling SQL with params: %s\n", lib_packprint(a)); ret = SQL (-2, a); freee(a); log3("PY: SetConf SQL returned %s\n", lib_packprint(ret)); if (!lib_unpack( ret, "lllp", &res, &rows, &cols, (void**) &list )) { log3("PY: SetConf call to SQL function failed\n"); freee(ret); return false; } freee(ret->args[3].p); freee(ret); if (!res) return false; return true; }
void minerList(IMP) { MinerScan_t mns; (void) skipBlanks(IS); #ifdef DEBUG_LIB if (IS->is_DEBUG) { log3(IS, ">>> In minerList()", "", ""); } #endif if (*IS->is_textInPos == '\0') { mns.mns_minerPatternType = mnp_none; mns.mns_cs.cs_conditionCount = 0; } else { if (!reqMiners(IS, &mns, "Miners to report on")) { return; } } /* display the report header */ user(IS, " Number | Plan/Shp | T | Eff | Ore | Bars | Space | " "Energ | OMG\n=========+==========+===+=====+=======+=======+=" "======+=======+====\n"); if (scanMiners(IS, &mns, doMinerRep) == 0) { err(IS, "no miners matched"); } else { userNL(IS); } #ifdef DEBUG_LIB if (IS->is_DEBUG) { log3(IS, "<<< Out of minerList()", "", ""); } #endif }
//we are assumed to be in a mutex here PBYTE DBRead(DWORD ofs,int bytesRequired,int *bytesAvail) { // buggy read if (ofs>=dwFileSize) { log2("read from outside %d@%08x",bytesRequired,ofs); if (bytesAvail!=NULL) *bytesAvail = ChunkSize; return pNull; } log3((ofs+bytesRequired>dwFileSize)?"read %d@%08x, only %d avaliable":"read %d@%08x",bytesRequired,ofs,dwFileSize-ofs); if (bytesAvail!=NULL) *bytesAvail = dwFileSize - ofs; return pDbCache+ofs; }
void DBMoveChunk(DWORD ofsDest,DWORD ofsSource,int bytes) { DWORD bytesRead; PBYTE buf; log3("move %d %08x->%08x",bytes,ofsSource,ofsDest); buf=(PBYTE)mir_alloc(bytes); SetFilePointer(hDbFile,ofsSource,NULL,FILE_BEGIN); ReadFile(hDbFile,buf,bytes,&bytesRead,NULL); DBWrite(ofsDest,buf,bytes); mir_free(buf); logg(); }
void DBMoveChunk(DWORD ofsDest,DWORD ofsSource,int bytes) { int x = 0; log3("move %d %08x->%08x",bytes,ofsSource,ofsDest); if (ofsDest+bytes>dwFileSize) ReMap(ofsDest+bytes-dwFileSize); if (ofsSource+bytes>dwFileSize) { x = ofsSource+bytes-dwFileSize; log0("buggy move!"); _ASSERT(0); } if (x > 0) ZeroMemory(pDbCache+ofsDest+bytes-x, x); if (ofsSource < dwFileSize) MoveMemory(pDbCache+ofsDest,pDbCache+ofsSource, bytes-x); logg(); }
const char *cpiPython::GetConf(const char *conf, const char *var) { if (!conf || !var) { log2("PY: GetConf wrong parameters\n"); return NULL; } // first let's check hub's internal config: if(!strcmp(conf, "config")) { static string res, file(server->mDBConf.config_name); cConfigItemBase *ci = NULL; if(file == server->mDBConf.config_name) { ci = server->mC[var]; if (ci) { ci->ConvertTo(res); log3("PY: GetConf got result from mDBConf: %s\n", res.c_str()); return strdup(res.c_str()); } } return NULL; /*char *s = (char*) calloc(1000, sizeof(char)); int size = GetConfig((char*)conf, (char*)var, (char*)s, 999); if (size < 0) { log("PY: GetConf: error in script_api's GetConfig"); return NULL; } if (size > 999) { free(s); s = (char*) calloc(size+1, sizeof(char)); GetConfig((char*)conf, (char*)var, s, 999); return s; }*/ } // let's try searching the database directly: if (!lib_begin || !lib_pack || !lib_unpack || !lib_packprint) return NULL; log3("PY: GetConf file != 'config'... calling SQL\n"); string query = string() + "select val from SetupList where file='" + conf + "' and var='" + var + "'"; w_Targs *a = lib_pack( "sl", query.c_str(), (long)1 ); log3("PY: GetConf calling SQL with params: %s\n", lib_packprint(a)); w_Targs *ret = SQL (-2, a); freee(a); if (!ret) return NULL; long res, rows, cols; char **list; log3("PY: GetConf SQL returned %s\n", lib_packprint(ret)); if (!lib_unpack( ret, "lllp", &res, &rows, &cols, (void**) &list )) { log3("PY: GetConf call to SQL function failed\n"); freee(ret); return NULL; } freee(ret); if (!res || !rows || !cols || !list || !list[0]) return NULL; log3("PY: GetConf returning value: %s\n", list[0]); const char * result = list[0]; free(list); return result; }
/* This routine runs along the task list and executes any job that wants * to be run. */ static inline void check_runs(struct tm *now) { centry task; int pid; char *av[5]; char s[26]; char *q; if (tasklist == NULL) return; for (task = tasklist; task != NULL; task = task->next) { if (bit_test(task->minutes, now->tm_min) && bit_test(task->hours, now->tm_hour) && bit_test(task->months, now->tm_mon+1) && bit_test(task->dom, now->tm_mday) && bit_test(task->dow, now->tm_wday)) { asctime_r(now, s); q = strchr(s, '\n'); if (q != NULL) *q = '\0'; log3(s, " Running: ", task->prog); av[0] = "cron-parent"; /* Build the cron-parent's argv structure */ av[1] = task->prog; av[2] = itoa(task->user); av[3] = task->username; av[4] = NULL; pid = vfork(); if (pid == 0) { /* Child */ /* This job is ready to run. Exec the special cron parent * process which actually runs the job. */ //execve("/bin/cron", av, task->environ); /*Tony*/ execve("/usr/sbin/crond", av, task->environ); error("Unable to exec task: cron-parent"); _exit(0); } if (pid < 0) error2("Unable to exec task: ", task->prog); } } }
DWORD CDb3Mmap::ReallocSpace(DWORD ofs, int oldSize, int newSize) { if (oldSize >= newSize) return ofs; DWORD ofsNew; if (ofs + oldSize == m_dbHeader.ofsFileEnd) { ofsNew = ofs; m_dbHeader.ofsFileEnd += newSize - oldSize; DBWrite(0, &m_dbHeader, sizeof(m_dbHeader)); log3("adding newspace %d@%08x+%d", newSize, ofsNew, oldSize); } else { ofsNew = CreateNewSpace(newSize); DBMoveChunk(ofsNew, ofs, oldSize); DeleteSpace(ofs, oldSize); } return ofsNew; }
TEST(LoggerTest, LevelTest) { std::ostringstream ss; Logger log1(ss, Logger::TRACE_); Logger log2(ss, Logger::VERBOSE_); Logger log3(ss, Logger::DEBUG_); Logger log4(ss, Logger::INFO_); Logger log5(ss, Logger::WARN_); Logger log6(ss, Logger::ERROR_); ASSERT_TRUE(log1.t()); ASSERT_TRUE(log1.v()); ASSERT_TRUE(log1.d()); ASSERT_TRUE(log1.i()); ASSERT_FALSE(log2.t()); ASSERT_TRUE(log2.v()); ASSERT_TRUE(log2.d()); ASSERT_TRUE(log2.i()); ASSERT_FALSE(log3.t()); ASSERT_FALSE(log3.v()); ASSERT_TRUE(log3.d()); ASSERT_TRUE(log3.i()); ASSERT_FALSE(log4.t()); ASSERT_FALSE(log4.v()); ASSERT_FALSE(log4.d()); ASSERT_TRUE(log4.i()); ASSERT_FALSE(log5.t()); ASSERT_FALSE(log5.v()); ASSERT_FALSE(log5.d()); ASSERT_FALSE(log5.i()); ASSERT_FALSE(log6.t()); ASSERT_FALSE(log6.v()); ASSERT_FALSE(log6.d()); ASSERT_FALSE(log6.i()); }
/* Load the configuration file if necessary. * Return non-zero if we've successifully read the file or if the * file hasn't changed. */ static inline int load_file(const char *fname) { int fp; struct stat lst, fst; char buf[BUFSIZ]; centry task, next_task; char *p; int line = 0; int res; int moreinput; static time_t file_mtime = 0; /* Stage one is open the file for read */ fp = open(fname, O_RDONLY); if (fp == -1) { error("Cannot open crontab"); goto failed; } /* Stage two is check permissions on file */ if (0 != lstat(fname, &lst) || 0 != fstat(fp, &fst)) { error("Cannot stat crontab"); goto failed; } if ((lst.st_mode & S_IFREG) == 0) { error("Crontab not regular file"); goto failed; } if (fst.st_ino != lst.st_ino) { error("Crontab inode changed between stat and open"); goto failed; } if (fst.st_dev != lst.st_dev) { error("Crontab device changed between stat and open"); goto failed; } if (fst.st_uid) { error("Crontab not owned by uid 0"); goto failed; } if (fst.st_mode & (S_IWGRP | S_IWOTH)) { error("Crontab group and/or world writable"); goto failed; } /* Check to see if the file has been modified */ if (fst.st_mtime == file_mtime) goto success; file_mtime = fst.st_mtime; log3("Loading crontab file: ", fname, NULL); /* Purge any existing tasks from the task list */ for (task = tasklist; task != NULL; task=next_task) { next_task = task->next; if (task->username != NULL) free(task->username); if (task->prog != NULL) free(task->prog); if (task->environ != NULL) free(task->environ); free(task); } tasklist = NULL; /* Purge any saved environment and restore to default */ zapenv(); stoenv("SHELL", "/bin/sh"); stoenv("PATH", "/bin:/usr/bin:/etc"); /* Finally get around to reading the file */ do { moreinput = fdgets(buf, BUFSIZ, fp); line++; /* Remove trailing newline and spaces if present */ if ((p = strchr(buf, '\n')) == NULL) goto failed; while (isspace(*p)) *p-- = '\0'; /* Remove leading spaces */ for (p = buf; *p != '\0' && isspace(*p); p++); if (*p == '\0') continue; if (*p == '#') continue; /* Now decode everything */ if (isdigit(*p) || *p == '*') { /* Assume this is a command */ res = decode_line(p); } else { /* This will be an environment variable setting */ res = decode_env(p); } if (!res) { error2("Crontab has malformed input line ", itoa(line)); } } while (moreinput); zapenv(); /* Do it again to save memory */ success: close(fp); return 1; /* Come here on failure for any reason */ failed: if (fp >= 0) close(fp); return 0; }
void DocumentRenderer::renderGL() { resizeGL(); m_document.getDefaultLayer()->updateIfDirty(); for(auto& obj : m_document.getObjectsList().get()) { if(dynamic_cast<BaseLayer*>(obj.get())) obj->updateIfDirty(); } { helper::ScopedEvent log1("prepareRender"); types::Color col = m_document.getBackgroundColor(); glClearColor(col.r, col.g, col.b, col.a); auto renderSize = m_document.getRenderSize(); glViewport(0, 0, renderSize.width(), renderSize.height()); m_secondRenderFBO.bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_secondRenderFBO.release(); m_renderFBO.bind(); } m_mergeLayersShader.bind(); m_mergeLayersShader.setUniformValueMat4("MVP", m_MVP.data()); { helper::ScopedEvent log("merge default Layer"); m_mergeLayersShader.setUniformValue("opacity", 1.0f); m_mergeLayersShader.setUniformValue("mode", 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_document.getDefaultLayer()->getTextureId()); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_secondRenderFBO.texture()); glActiveTexture(GL_TEXTURE0); m_rectModel.render(); m_renderFBO.release(); } bool inverse = false; for(auto& obj : m_document.getObjectsList().get()) { BaseLayer* layer = dynamic_cast<BaseLayer*>(obj.get()); if(layer) { float opacity = (float)layer->getOpacity(); if(!opacity) continue; helper::ScopedEvent log2("merge Layer"); m_mergeLayersShader.setUniformValue("opacity", opacity); m_mergeLayersShader.setUniformValue("mode", layer->getCompositionMode()); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, layer->getTextureId()); inverse = !inverse; if(inverse) { m_secondRenderFBO.bind(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_renderFBO.texture()); } else { m_renderFBO.bind(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_secondRenderFBO.texture()); } m_rectModel.render(); glActiveTexture(GL_TEXTURE0); if(inverse) m_secondRenderFBO.release(); else m_renderFBO.release(); } } m_mergeLayersShader.release(); if(inverse) { helper::ScopedEvent log3("blit FBO"); graphics::Framebuffer::blitFramebuffer(m_renderFBO, m_secondRenderFBO); } }
static __inline int GetContactSettingWorker(HANDLE hContact,DBCONTACTGETSETTING *dbcgs,int isStatic) { struct DBContact *dbc; DWORD ofsModuleName,ofsContact,ofsSettingsGroup,ofsBlobPtr; int settingNameLen,moduleNameLen; int bytesRemaining; PBYTE pBlob; char* szCachedSettingName; if ((!dbcgs->szSetting) || (!dbcgs->szModule)) return 1; // the db format can't tolerate more than 255 bytes of space (incl. null) for settings+module name settingNameLen = (int)strlen(dbcgs->szSetting); moduleNameLen = (int)strlen(dbcgs->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; } EnterCriticalSection(&csDbAccess); log3("get [%08p] %s/%s",hContact,dbcgs->szModule,dbcgs->szSetting); szCachedSettingName = GetCachedSetting(dbcgs->szModule,dbcgs->szSetting,moduleNameLen,settingNameLen); { DBVARIANT* pCachedValue = GetCachedValuePtr( hContact, szCachedSettingName, 0 ); if ( pCachedValue != NULL ) { if ( pCachedValue->type == DBVT_ASCIIZ || pCachedValue->type == DBVT_UTF8 ) { int cbOrigLen = dbcgs->pValue->cchVal; char* cbOrigPtr = dbcgs->pValue->pszVal; memcpy( dbcgs->pValue, pCachedValue, sizeof( DBVARIANT )); if ( isStatic ) { int cbLen = 0; if ( pCachedValue->pszVal != NULL ) cbLen = (int)strlen( pCachedValue->pszVal ); cbOrigLen--; dbcgs->pValue->pszVal = cbOrigPtr; if(cbLen<cbOrigLen) cbOrigLen=cbLen; CopyMemory(dbcgs->pValue->pszVal,pCachedValue->pszVal,cbOrigLen); dbcgs->pValue->pszVal[cbOrigLen]=0; dbcgs->pValue->cchVal=cbLen; } else { dbcgs->pValue->pszVal = (char*)mir_alloc(strlen(pCachedValue->pszVal)+1); strcpy(dbcgs->pValue->pszVal,pCachedValue->pszVal); } } else memcpy( dbcgs->pValue, pCachedValue, sizeof( DBVARIANT )); switch( dbcgs->pValue->type ) { case DBVT_BYTE: log1( "get cached byte: %d", dbcgs->pValue->bVal ); break; case DBVT_WORD: log1( "get cached word: %d", dbcgs->pValue->wVal ); break; case DBVT_DWORD: log1( "get cached dword: %d", dbcgs->pValue->dVal ); break; case DBVT_UTF8: case DBVT_ASCIIZ: log1( "get cached string: '%s'", dbcgs->pValue->pszVal); break; default: log1( "get cached crap: %d", dbcgs->pValue->type ); break; } LeaveCriticalSection(&csDbAccess); return ( pCachedValue->type == DBVT_DELETED ) ? 1 : 0; } } ofsModuleName=GetModuleNameOfs(dbcgs->szModule); if(hContact==NULL) ofsContact=dbHeader.ofsUser; else ofsContact=(DWORD)hContact; dbc=(struct DBContact*)DBRead(ofsContact,sizeof(struct DBContact),NULL); if(dbc->signature!=DBCONTACT_SIGNATURE) { LeaveCriticalSection(&csDbAccess); return 1; } ofsSettingsGroup=GetSettingsGroupOfsByModuleNameOfs(dbc,ofsModuleName); if(ofsSettingsGroup) { ofsBlobPtr=ofsSettingsGroup+offsetof(struct DBContactSettings,blob); pBlob = DBRead(ofsBlobPtr,sizeof(struct DBContactSettings),&bytesRemaining); while(pBlob[0]) { NeedBytes(1+settingNameLen); if(pBlob[0]==settingNameLen && !memcmp(pBlob+1,dbcgs->szSetting,settingNameLen)) { MoveAlong(1+settingNameLen); NeedBytes(5); if(isStatic && pBlob[0]&DBVTF_VARIABLELENGTH && VLT(dbcgs->pValue->type) != VLT(pBlob[0])) { LeaveCriticalSection(&csDbAccess); return 1; } dbcgs->pValue->type=pBlob[0]; switch(pBlob[0]) { case DBVT_DELETED: { /* this setting is deleted */ dbcgs->pValue->type=DBVT_DELETED; LeaveCriticalSection(&csDbAccess); return 2; } case DBVT_BYTE: dbcgs->pValue->bVal=pBlob[1]; break; case DBVT_WORD: DecodeCopyMemory(&(dbcgs->pValue->wVal), (PWORD)(pBlob+1), 2); break; case DBVT_DWORD: DecodeCopyMemory(&(dbcgs->pValue->dVal), (PDWORD)(pBlob+1), 4); break; case DBVT_UTF8: case DBVT_ASCIIZ: NeedBytes(3+*(PWORD)(pBlob+1)); if(isStatic) { dbcgs->pValue->cchVal--; if(*(PWORD)(pBlob+1)<dbcgs->pValue->cchVal) dbcgs->pValue->cchVal=*(PWORD)(pBlob+1); DecodeCopyMemory(dbcgs->pValue->pszVal,pBlob+3,dbcgs->pValue->cchVal); dbcgs->pValue->pszVal[dbcgs->pValue->cchVal]=0; dbcgs->pValue->cchVal=*(PWORD)(pBlob+1); } else { dbcgs->pValue->pszVal=(char*)mir_alloc(1+*(PWORD)(pBlob+1)); DecodeCopyMemory(dbcgs->pValue->pszVal,pBlob+3,*(PWORD)(pBlob+1)); dbcgs->pValue->pszVal[*(PWORD)(pBlob+1)]=0; } break; case DBVT_BLOB: NeedBytes(3+*(PWORD)(pBlob+1)); if(isStatic) { if(*(PWORD)(pBlob+1)<dbcgs->pValue->cpbVal) dbcgs->pValue->cpbVal=*(PWORD)(pBlob+1); DecodeCopyMemory(dbcgs->pValue->pbVal,pBlob+3,dbcgs->pValue->cpbVal); } else { dbcgs->pValue->pbVal=(char*)mir_alloc(*(PWORD)(pBlob+1)); DecodeCopyMemory(dbcgs->pValue->pbVal,pBlob+3,*(PWORD)(pBlob+1)); } dbcgs->pValue->cpbVal=*(PWORD)(pBlob+1); break; } /**** add to cache **********************/ if ( dbcgs->pValue->type != DBVT_BLOB ) { DBVARIANT* pCachedValue = GetCachedValuePtr( hContact, szCachedSettingName, 1 ); if ( pCachedValue != NULL ) SetCachedVariant(dbcgs->pValue,pCachedValue); } LeaveCriticalSection(&csDbAccess); logg(); return 0; } NeedBytes(1); MoveAlong(pBlob[0]+1); NeedBytes(3); MoveAlong(1+GetSettingValueLength(pBlob)); NeedBytes(1); } } /**** nullbie: query info from preset **********************/ if (!hContact && DBPreset_QuerySetting(dbcgs->szModule, dbcgs->szSetting, dbcgs->pValue, isStatic)) { /**** add to cache **********************/ if ( dbcgs->pValue->type != DBVT_BLOB ) { DBVARIANT* pCachedValue = GetCachedValuePtr( hContact, szCachedSettingName, 1 ); if ( pCachedValue != NULL ) SetCachedVariant(dbcgs->pValue,pCachedValue); } return 0; } /**** add missing setting to cache **********************/ if ( dbcgs->pValue->type != DBVT_BLOB ) { DBVARIANT* pCachedValue = GetCachedValuePtr( hContact, szCachedSettingName, 1 ); if ( pCachedValue != NULL ) pCachedValue->type = DBVT_DELETED; } LeaveCriticalSection(&csDbAccess); logg(); return 1; }
static __inline int GetContactSettingWorker(HANDLE hContact,DBCONTACTGETSETTING *dbcgs,int isStatic) { struct DBContact dbc; struct DBContactSettings dbcs; DWORD ofsModuleName,ofsContact,ofsSettingsGroup,ofsBlobPtr; int settingNameLen; int bytesRemaining; PBYTE pBlob; char* szCachedSettingName; if ((!dbcgs->szSetting) || (!dbcgs->szModule)) return 1; settingNameLen=(int)strlen(dbcgs->szSetting); EnterCriticalSection(&csDbAccess); log3("get [%08p] %s/%s",hContact,dbcgs->szModule,dbcgs->szSetting); szCachedSettingName = GetCachedSetting(dbcgs->szModule,dbcgs->szSetting,settingNameLen); { DBVARIANT* pCachedValue = GetCachedValuePtr( hContact, szCachedSettingName, 0 ); if ( pCachedValue != NULL ) { if ( pCachedValue->type == DBVT_ASCIIZ || pCachedValue->type == DBVT_UTF8 ) { int cbOrigLen = dbcgs->pValue->cchVal; char* cbOrigPtr = dbcgs->pValue->pszVal; memcpy( dbcgs->pValue, pCachedValue, sizeof( DBVARIANT )); if ( isStatic ) { int cbLen = 0; if ( pCachedValue->pszVal != NULL ) cbLen = (int)strlen( pCachedValue->pszVal ); cbOrigLen--; dbcgs->pValue->pszVal = cbOrigPtr; if(cbLen<cbOrigLen) cbOrigLen=cbLen; CopyMemory(dbcgs->pValue->pszVal,pCachedValue->pszVal,cbOrigLen); dbcgs->pValue->pszVal[cbOrigLen]=0; dbcgs->pValue->cchVal=cbLen; } else { dbcgs->pValue->pszVal = (char*)mir_alloc(strlen(pCachedValue->pszVal)+1); strcpy(dbcgs->pValue->pszVal,pCachedValue->pszVal); } } else memcpy( dbcgs->pValue, pCachedValue, sizeof( DBVARIANT )); switch( dbcgs->pValue->type ) { case DBVT_BYTE: log1( "get cached byte: %d", dbcgs->pValue->bVal ); break; case DBVT_WORD: log1( "get cached word: %d", dbcgs->pValue->wVal ); break; case DBVT_DWORD: log1( "get cached dword: %d", dbcgs->pValue->dVal ); break; case DBVT_UTF8: case DBVT_ASCIIZ: log1( "get cached string: '%s'", dbcgs->pValue->pszVal); break; default: log1( "get cached crap: %d", dbcgs->pValue->type ); break; } LeaveCriticalSection(&csDbAccess); return ( pCachedValue->type == DBVT_DELETED ) ? 1 : 0; } } ofsModuleName=GetModuleNameOfs(dbcgs->szModule); if(hContact==NULL) ofsContact=dbHeader.ofsUser; else ofsContact=(DWORD)hContact; dbc=*(struct DBContact*)DBRead(ofsContact,sizeof(struct DBContact),NULL); if(dbc.signature!=DBCONTACT_SIGNATURE) { LeaveCriticalSection(&csDbAccess); return 1; } ofsSettingsGroup=GetSettingsGroupOfsByModuleNameOfs(&dbc,ofsContact,ofsModuleName); if(ofsSettingsGroup) { dbcs=*(struct DBContactSettings*)DBRead(ofsSettingsGroup,sizeof(struct DBContactSettings),&bytesRemaining); ofsBlobPtr=ofsSettingsGroup+offsetof(struct DBContactSettings,blob); pBlob=(PBYTE)DBRead(ofsBlobPtr,1,&bytesRemaining); while(pBlob[0]) { NeedBytes(1+settingNameLen); if(pBlob[0]==settingNameLen && !memcmp(pBlob+1,dbcgs->szSetting,settingNameLen)) { MoveAlong(1+settingNameLen); NeedBytes(5); if(isStatic && pBlob[0]&DBVTF_VARIABLELENGTH && VLT(dbcgs->pValue->type) != VLT(pBlob[0])) { LeaveCriticalSection(&csDbAccess); return 1; } dbcgs->pValue->type=pBlob[0]; switch(pBlob[0]) { case DBVT_DELETED: { /* this setting is deleted */ dbcgs->pValue->type=DBVT_DELETED; LeaveCriticalSection(&csDbAccess); return 2; } case DBVT_BYTE: dbcgs->pValue->bVal=pBlob[1]; break; case DBVT_WORD: dbcgs->pValue->wVal=*(PWORD)(pBlob+1); break; case DBVT_DWORD: dbcgs->pValue->dVal=*(PDWORD)(pBlob+1); break; case DBVT_UTF8: case DBVT_ASCIIZ: NeedBytes(3+*(PWORD)(pBlob+1)); if(isStatic) { dbcgs->pValue->cchVal--; if(*(PWORD)(pBlob+1)<dbcgs->pValue->cchVal) dbcgs->pValue->cchVal=*(PWORD)(pBlob+1); CopyMemory(dbcgs->pValue->pszVal,pBlob+3,dbcgs->pValue->cchVal); dbcgs->pValue->pszVal[dbcgs->pValue->cchVal]=0; dbcgs->pValue->cchVal=*(PWORD)(pBlob+1); } else { dbcgs->pValue->pszVal=(char*)mir_alloc(1+*(PWORD)(pBlob+1)); CopyMemory(dbcgs->pValue->pszVal,pBlob+3,*(PWORD)(pBlob+1)); dbcgs->pValue->pszVal[*(PWORD)(pBlob+1)]=0; } break; case DBVT_BLOB: NeedBytes(3+*(PWORD)(pBlob+1)); if(isStatic) { if(*(PWORD)(pBlob+1)<dbcgs->pValue->cpbVal) dbcgs->pValue->cpbVal=*(PWORD)(pBlob+1); CopyMemory(dbcgs->pValue->pbVal,pBlob+3,dbcgs->pValue->cpbVal); } else { dbcgs->pValue->pbVal=(char*)mir_alloc(*(PWORD)(pBlob+1)); CopyMemory(dbcgs->pValue->pbVal,pBlob+3,*(PWORD)(pBlob+1)); } dbcgs->pValue->cpbVal=*(PWORD)(pBlob+1); break; } /**** add to cache **********************/ if ( dbcgs->pValue->type != DBVT_BLOB ) { DBVARIANT* pCachedValue = GetCachedValuePtr( hContact, szCachedSettingName, 1 ); if ( pCachedValue != NULL ) SetCachedVariant(dbcgs->pValue,pCachedValue); } LeaveCriticalSection(&csDbAccess); logg(); return 0; } NeedBytes(1); MoveAlong(pBlob[0]+1); NeedBytes(3); MoveAlong(1+GetSettingValueLength(pBlob)); NeedBytes(1); } } /**** add missing setting to cache **********************/ if ( dbcgs->pValue->type != DBVT_BLOB ) { DBVARIANT* pCachedValue = GetCachedValuePtr( hContact, szCachedSettingName, 1 ); if ( pCachedValue != NULL ) pCachedValue->type = DBVT_DELETED; } LeaveCriticalSection(&csDbAccess); logg(); return 1; }
/* get an option with bounds checking (warning, result is not aligned). */ uint8_t* FAST_FUNC get_option(struct dhcp_packet *packet, int code) { uint8_t *optionptr; int len; int rem; int overload = 0; enum { FILE_FIELD101 = FILE_FIELD * 0x101, SNAME_FIELD101 = SNAME_FIELD * 0x101, }; /* option bytes: [code][len][data1][data2]..[dataLEN] */ optionptr = packet->options; rem = sizeof(packet->options); while (1) { if (rem <= 0) { bb_error_msg("bogus packet, malformed option field"); return NULL; } if (optionptr[OPT_CODE] == DHCP_PADDING) { rem--; optionptr++; continue; } if (optionptr[OPT_CODE] == DHCP_END) { if ((overload & FILE_FIELD101) == FILE_FIELD) { /* can use packet->file, and didn't look at it yet */ overload |= FILE_FIELD101; /* "we looked at it" */ optionptr = packet->file; rem = sizeof(packet->file); continue; } if ((overload & SNAME_FIELD101) == SNAME_FIELD) { /* can use packet->sname, and didn't look at it yet */ overload |= SNAME_FIELD101; /* "we looked at it" */ optionptr = packet->sname; rem = sizeof(packet->sname); continue; } break; } len = 2 + optionptr[OPT_LEN]; rem -= len; if (rem < 0) continue; /* complain and return NULL */ if (optionptr[OPT_CODE] == code) { log_option("Option found", optionptr); return optionptr + OPT_DATA; } if (optionptr[OPT_CODE] == DHCP_OPTION_OVERLOAD) { overload |= optionptr[OPT_DATA]; /* fall through */ } optionptr += len; } /* log3 because udhcpc uses it a lot - very noisy */ log3("Option 0x%02x not found", code); return NULL; }
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; }
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) { DBVARIANT *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; }
/** * Do all socket creation and initialization */ void create_sockets(void) { struct addrinfo ai_hints, *ai_rval; int family, rval, fdflag, i; #if (defined IPV6_RECVTCLASS || defined IP_RECVTCLASS || defined IP_RECVTOS) &&\ !(defined WINDOWS && _WIN32_WINNT < _WIN32_WINNT_LONGHORN) int tosflag; #endif family = AF_INET; for (i = 0; i < pub_multi_count; i++) { if (pub_multi[i].ss.ss_family == AF_INET6) { family = AF_INET6; break; } } if ((listener = socket(family, SOCK_DGRAM, 0)) == INVALID_SOCKET) { sockerror(0, 0, 0, "Error creating socket for listener"); exit(ERR_SOCKET); } #if (defined WINDOWS && _WIN32_WINNT >= _WIN32_WINNT_LONGHORN) ||\ (!defined WINDOWS && !defined NO_DUAL) if (family == AF_INET6) { int v6flag = 0; if (setsockopt(listener, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6flag, sizeof(v6flag)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting v6only"); closesocket(listener); exit(ERR_SOCKET); } } #endif memset(&ai_hints, 0, sizeof(ai_hints)); ai_hints.ai_family = family; ai_hints.ai_socktype = SOCK_DGRAM; ai_hints.ai_protocol = 0; ai_hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV; if ((rval = getaddrinfo(NULL, portname, &ai_hints, &ai_rval)) != 0) { log0(0, 0, 0, "Error getting bind address: %s", gai_strerror(rval)); exit(ERR_SOCKET); } if (bind(listener, ai_rval->ai_addr, ai_rval->ai_addrlen) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error binding socket for listener"); closesocket(listener); exit(ERR_SOCKET); } freeaddrinfo(ai_rval); #ifdef WINDOWS fdflag = 1; if (ioctlsocket(listener, FIONBIO, &fdflag) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting non-blocking option"); closesocket(listener); exit(ERR_SOCKET); } #else if ((fdflag = fcntl(listener, F_GETFL)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error getting socket descriptor flags"); closesocket(listener); exit(ERR_SOCKET); } fdflag |= O_NONBLOCK; if (fcntl(listener, F_SETFL, fdflag) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting non-blocking option"); closesocket(listener); exit(ERR_SOCKET); } #endif if (family == AF_INET6) { #if defined IPV6_TCLASS && !defined WINDOWS if (setsockopt(listener, IPPROTO_IPV6, IPV6_TCLASS, (char *)&dscp, sizeof(dscp)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting dscp"); closesocket(listener); exit(ERR_SOCKET); } #endif #ifdef IPV6_RECVTCLASS #if !(defined WINDOWS && _WIN32_WINNT < _WIN32_WINNT_LONGHORN) tosflag = 1; if (setsockopt(listener, IPPROTO_IPV6, IPV6_RECVTCLASS, (char *)&tosflag, sizeof(tosflag)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting recv tos"); closesocket(listener); exit(ERR_SOCKET); } #endif #endif #ifdef IPV6_MTU_DISCOVER { int mtuflag = IP_PMTUDISC_DONT; if (setsockopt(listener, IPPROTO_IPV6, IPV6_MTU_DISCOVER, (char *)&mtuflag, sizeof(mtuflag)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error disabling MTU discovery"); closesocket(listener); exit(ERR_SOCKET); } } #endif } #if (defined WINDOWS && _WIN32_WINNT < _WIN32_WINNT_LONGHORN) ||\ (defined NO_DUAL) if (family == AF_INET) { #endif if (setsockopt(listener, IPPROTO_IP, IP_TOS, (char *)&dscp, sizeof(dscp)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting dscp"); closesocket(listener); exit(ERR_SOCKET); } #ifdef IP_RECVTCLASS #if !(defined WINDOWS && _WIN32_WINNT < _WIN32_WINNT_LONGHORN) tosflag = 1; if (setsockopt(listener, IPPROTO_IP, IP_RECVTCLASS, (char *)&tosflag, sizeof(tosflag)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting recv tos"); closesocket(listener); exit(ERR_SOCKET); } #endif #elif defined IP_RECVTOS tosflag = 1; if (setsockopt(listener, IPPROTO_IP, IP_RECVTOS, (char *)&tosflag, sizeof(tosflag)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting recv tos"); closesocket(listener); exit(ERR_SOCKET); } #endif #ifdef IP_MTU_DISCOVER { int mtuflag = IP_PMTUDISC_DONT; if (setsockopt(listener, IPPROTO_IP, IP_MTU_DISCOVER, (char *)&mtuflag, sizeof(mtuflag)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error disabling MTU discovery"); closesocket(listener); exit(ERR_SOCKET); } } #endif #if (defined WINDOWS && _WIN32_WINNT < _WIN32_WINNT_LONGHORN) ||\ (defined NO_DUAL) } #endif if (rcvbuf) { if (setsockopt(listener, SOL_SOCKET, SO_RCVBUF, (char *)&rcvbuf, sizeof(rcvbuf)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting receive buffer size"); exit(ERR_SOCKET); } } else { rcvbuf = DEF_RCVBUF; if (setsockopt(listener, SOL_SOCKET, SO_RCVBUF, (char *)&rcvbuf, sizeof(rcvbuf)) == SOCKET_ERROR) { rcvbuf = DEF_BSD_RCVBUF; if (setsockopt(listener, SOL_SOCKET, SO_RCVBUF, (char *)&rcvbuf, sizeof(rcvbuf)) == SOCKET_ERROR) { sockerror(0, 0, 0, "Error setting receive buffer size"); exit(ERR_SOCKET); } } } for (i = 0; i < pub_multi_count; i++) { if (server_count > 0) { log3(0, 0, 0, "joining ssm for server IPs"); if (!multicast_join(listener, 0, &pub_multi[i], m_interface, interface_count, server_keys, server_count)) { exit(ERR_SOCKET); } if (has_proxy) { log3(0, 0, 0, "joining ssm for proxy IPs"); if (!multicast_join(listener, 0, &pub_multi[i], m_interface, interface_count, &proxy_info, 1)) { exit(ERR_SOCKET); } } } else { if (!multicast_join(listener, 0, &pub_multi[i], m_interface, interface_count, NULL, 0)) { exit(ERR_SOCKET); } } } }
int main (int argc, char **argv) { struct sockaddr_in self, from; struct hostent *h; int master, n, addrlen, peeraddrlen; fd_set mask, m; struct timeval timo; for (;;) { switch (getopt (argc, argv, "vDL:")) { case -1: break; case 'v': ++verbose; continue; case 'D': ++debug; continue; case 'L': logfile = optarg; continue; } break; } time (&t0); signal (SIGPIPE, SIG_IGN); addrlen = sizeof (struct sockaddr_in); if (getsockname (0, (struct sockaddr*) &self, &addrlen) < 0) { log2 ("cannot get socket name: %s", strerror (errno)); quit (-2); } port = ntohs (self.sin_port); addrlen = sizeof (struct sockaddr_in); if (recvfrom (0, buf, MTU, MSG_PEEK, (struct sockaddr*) &from, &addrlen) <= 0) { log2 ("cannot get peer address: %s", strerror (errno)); quit (-2); } peerfrom = from; peeraddrlen = addrlen; h = gethostbyaddr ((char*) &from.sin_addr, sizeof (from.sin_addr), AF_INET); if (h) strcpy (peername, h->h_name); else log2 ("cannot get peer host name: %s", inet_ntoa (from.sin_addr)); log3 ("connection from %s port %d", inet_ntoa (from.sin_addr), ntohs (from.sin_port)); n = IPTOS_LOWDELAY; if (setsockopt (0, IPPROTO_IP, IP_TOS, (char*) &n, sizeof(int)) < 0) log1 ("setsockopt (IP_TOS) failed"); master = forklogin (peername); if (master < 0) quit (-1); FD_ZERO (&mask); FD_SET (0, &mask); /* socket */ FD_SET (master, &mask); /* pty */ for (;;) { m = mask; timo.tv_sec = 30; timo.tv_usec = 0; switch (select (32, &m, 0, 0, &timo)) { case -1: log2 ("select failed: %s", strerror (errno)); quit (-1); case 0: log1 ("timed out"); quit (-1); default: break; } if (FD_ISSET (0, &m)) { /* new packet arrived */ n = recvfrom (0, buf, MTU, 0, (struct sockaddr*) &from, &addrlen); if (n <= 0) { log2 ("recv failed: %s", strerror (errno)); quit (-1); } if (addrlen != peeraddrlen || bcmp (&from, &peerfrom, sizeof (from)) != 0) { log3 ("strange packet from %s port %d", inet_ntoa (from.sin_addr), ntohs (from.sin_port)); continue; } switch (*buf) { case DLP_DATA: ibytes += n-1; ipackets++; write (master, buf+1, n-1); break; case DLP_LOGOUT: quit (0); case DLP_ALIVE: /* log1 ("keepalive"); */ break; default: log1 ("invalid packet"); quit (-1); } } if (FD_ISSET (master, &m)) { /* pty input pending */ n = read (master, buf+1, MTU-1); if (n < 0) { log2 ("pty read failed: %s", strerror (errno)); quit (-1); } if (n == 0) quit (0); obytes += n; opackets++; *buf = DLP_DATA; sendto (0, buf, n+1, 0, (struct sockaddr*) &peerfrom, sizeof peerfrom); } } }
bool cpiPython::OnFirstMyINFO(cConnDC *conn, cMessageDC *msg) { if (!online) return true; if((conn != NULL) && (conn->mpUser != NULL) && (msg != NULL)) { int func = W_OnFirstMyINFO; const char *original = msg->mStr.c_str(); const char *origdesc = NULL, *origtag = NULL, *origspeed = NULL, *origmail = NULL, *origsize = NULL; const char *n, *desc, *tag, *speed, *mail, *size; // will be assigned by SplitMyINFO (even with NULL values) const char *nick = conn->mpUser->mNick.c_str(); if (!SplitMyINFO(original, &n, &origdesc, &origtag, &origspeed, &origmail, &origsize)) { log1("PY: Call OnFirstMyINFO: malformed myinfo message: %s\n", original); return true; } w_Targs* args = lib_pack( "ssssss", n, origdesc, origtag, origspeed, origmail, origsize); log2("PY: Call %s: parameters %s\n", lib_hookname(func), lib_packprint(args)); bool ret = true; w_Targs *result; long l; if(Size()) { tvPythonInterpreter::iterator it; for(it = mPython.begin(); it != mPython.end(); ++it) { result = (*it)->CallFunction(func, args); if(!result) { log3("PY: Call %s: returned NULL\n", lib_hookname(func)); continue; } if(lib_unpack(result, "l", &l)) // default return value is 1L meaning: further processing, { log3("PY: Call %s: returned l:%ld\n", lib_hookname(func), l); if (!l) ret = false; // 0L means no more processing outside this plugin } else if (lib_unpack(result, "sssss", &desc, &tag, &speed, &mail, &size)) // script wants to change the contents of myinfo { log2("PY: modifying message - Call %s: returned %s\n", lib_hookname(func), lib_packprint(result)); if (desc || tag || speed || mail || size) { // message chunks need updating to new MyINFO // $MyINFO $ALL <nick> <interest>$ $<speed\x01>$<e-mail>$<sharesize>$ // $MyINFO $ALL nick <++ V:0.668,M:P,H:39/0/0,S:1>$ $DSL$$74894830123$ string newinfo = "$MyINFO $ALL "; newinfo += nick; newinfo += " "; newinfo += (desc) ? desc : origdesc; newinfo += (tag) ? tag : origtag; newinfo += "$ $"; newinfo += (speed) ? speed : origspeed; newinfo += "$"; newinfo += (mail) ? mail : origmail; newinfo += "$"; newinfo += (size) ? size : origsize; newinfo += "$"; log3("myinfo: [ %s ] will become: [ %s ]\n", original, newinfo.c_str()); msg->ReInit(); msg->mStr = newinfo; //msg->mType = eDC_MYINFO; msg->Parse(); if (msg->SplitChunks()) log1("cpiPython::OnFirstMyINFO: failed to split new MyINFO into chunks\n"); conn->mpUser->mEmail = msg->ChunkString(eCH_MI_MAIL); } ret = true; // we've changed myinfo so we want the hub to store it now } else // something unknown was returned... we will let the hub call other plugins log1("PY: Call %s: unexpected return value: %s\n", lib_hookname(func), lib_packprint(result)); free(result); } } freee(args); freee(n); freee(origdesc); freee(origtag); freee(origspeed); freee(origmail); freee(origsize); return ret; } return true; // true means further processing }
Eigen::Matrix<typename Matrix3Like::Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like)::Options> log3_proxy(const Matrix3Like & R) { return log3(R); }
/* Get an option with bounds checking (warning, result is not aligned) */ uint8_t* FAST_FUNC udhcp_get_option(struct dhcp_packet *packet, int code) { uint8_t *optionptr; int len; int rem; int overload = 0; enum { FILE_FIELD101 = FILE_FIELD * 0x101, SNAME_FIELD101 = SNAME_FIELD * 0x101, }; /* option bytes: [code][len][data1][data2]..[dataLEN] */ optionptr = packet->options; rem = sizeof(packet->options); while (1) { if (rem <= 0) { complain: bb_error_msg("bad packet, malformed option field"); return NULL; } /* DHCP_PADDING and DHCP_END have no [len] byte */ if (optionptr[OPT_CODE] == DHCP_PADDING) { rem--; optionptr++; continue; } if (optionptr[OPT_CODE] == DHCP_END) { if ((overload & FILE_FIELD101) == FILE_FIELD) { /* can use packet->file, and didn't look at it yet */ overload |= FILE_FIELD101; /* "we looked at it" */ optionptr = packet->file; rem = sizeof(packet->file); continue; } if ((overload & SNAME_FIELD101) == SNAME_FIELD) { /* can use packet->sname, and didn't look at it yet */ overload |= SNAME_FIELD101; /* "we looked at it" */ optionptr = packet->sname; rem = sizeof(packet->sname); continue; } break; } if (rem <= OPT_LEN) goto complain; /* complain and return NULL */ len = 2 + optionptr[OPT_LEN]; rem -= len; if (rem < 0) goto complain; /* complain and return NULL */ if (optionptr[OPT_CODE] == code) { if (optionptr[OPT_LEN] == 0) { /* So far no valid option with length 0 known. * Having this check means that searching * for DHCP_MESSAGE_TYPE need not worry * that returned pointer might be unsafe * to dereference. */ goto complain; /* complain and return NULL */ } log_option("option found", optionptr); return optionptr + OPT_DATA; } if (optionptr[OPT_CODE] == DHCP_OPTION_OVERLOAD) { if (len >= 3) overload |= optionptr[OPT_DATA]; /* fall through */ } optionptr += len; } /* log3 because udhcpc uses it a lot - very noisy */ log3("option 0x%02x not found", code); return NULL; }
void doMinerRep(IMP, ULONG minerNumber, register Ship_t *sh) { #ifdef DEBUG_LIB Ship_t saveSh; #endif #ifdef DEBUG_LIB if (IS->is_DEBUG) { saveSh = *sh; log3(IS, ">>> In doMinerRep", "", ""); *sh = saveSh; } #endif /* display the miner's number */ userF(IS, minerNumber, 8); user(IS, " | "); if (sh->sh_dragger == NO_ITEM) { /* the miner is on a planet */ if (sh->sh_planet == NO_ITEM) { /* should never happen */ user(IS, "******** | ?"); } else { userF(IS, sh->sh_planet, 8); user(IS, " | \x50"); } } else { userF(IS, sh->sh_dragger, 8); user(IS, " | S"); } user(IS, " | "); userF(IS, sh->sh_efficiency, 3); user(IS, " | "); userF(IS, sh->sh_items[it_ore], 5); user(IS, " | "); userF(IS, sh->sh_items[it_bars], 5); user(IS, " | "); userF(IS, IS->is_world.w_shipCargoLim[st_m] - sh->sh_cargo, 5); user(IS, " | "); userF(IS, sh->sh_energy, 5); user(IS, " | "); switch(sh->sh_weapon[0]) { case 0: userC(IS, 'N'); break; case 1: userC(IS, 'L'); break; case 2: userC(IS, 'M'); break; case 3: userC(IS, 'H'); break; default: userC(IS, '?'); break; } switch(sh->sh_weapon[1]) { case 0: userC(IS, 'N'); break; case 1: userC(IS, 'L'); break; case 2: userC(IS, 'M'); break; case 3: userC(IS, 'H'); break; default: userC(IS, '?'); break; } switch(sh->sh_weapon[2]) { case 0: userC(IS, 'N'); break; case 1: userC(IS, 'L'); break; case 2: userC(IS, 'M'); break; case 3: userC(IS, 'H'); break; default: userC(IS, '?'); break; } userNL(IS); #ifdef DEBUG_LIB if (IS->is_DEBUG) { saveSh = *sh; log3(IS, "<<< Out of doMinerRep", "", ""); *sh = saveSh; } #endif }
BOOL cmd_run(IMP) { register Ship_t *rsh; register Nav_t *nav; Fleet_t fl; ULONG shNum, curNum; USHORT msc, flagRow, flagCol, flagMobil, minMobil, i; char progBuf[MAX_PROG_STEPS]; char fleet; BOOL gotOne, tooMany; /* get the number of the ship */ if (reqShip(IS, &shNum, "Run program on which ship")) { rsh = &IS->is_request.rq_u.ru_ship; server(IS, rt_readShip, shNum); gotOne = FALSE; tooMany = FALSE; if (rsh->sh_owner != IS->is_player.p_number) { user(IS, "You don't own that ship\n"); } else if (rsh->sh_type == st_m) { user(IS, "You do not need to use the 'run' command with a " "miner\n"); return FALSE; } else if (rsh->sh_course[0] == '\0') { user(IS, "Ship has no program!\n"); } else { msc = 0; /* copy the current course */ strcpy(&progBuf[0], &rsh->sh_course[0]); /* set the default for the fleet */ fleet = '*'; /* see if the ship is in a fleet */ if (rsh->sh_fleet != '*') { /* it is, so set fleet apropriately */ fleet = rsh->sh_fleet; } /* was there a fleet? */ if (fleet == '*') { /* no, so do single-ship things */ accessShip(IS, shNum); if (rsh->sh_efficiency < EFFIC_WARN) { err(IS, "that ship isn't efficient enough to navigate"); } else { IS->is_movingShipCount = 1; msc = 1; nav = &IS->is_movingShips[0]; nav->n_ship = shNum; nav->n_mobil = ((short)rsh->sh_energy) * 10; nav->n_active = TRUE; flagMobil = rsh->sh_energy; minMobil = rsh->sh_energy; flagRow = rsh->sh_row; flagCol = rsh->sh_col; decrShipCount(IS, mapSector(IS, rsh->sh_row, rsh->sh_col)); } } else { /* yes, so set it up */ i = fleetPos(fleet); if (IS->is_player.p_fleets[i] == NO_FLEET) { log3(IS, "attempted to run a program for fleet not used " "by player ", &IS->is_player.p_name[0], ""); err(IS, "you are not using the fleet listed for the ship!" " Notify the deity!"); } else { server(IS, rt_readFleet, IS->is_player.p_fleets[i]); fl = IS->is_request.rq_u.ru_fleet; if (fl.f_count == 0) { log3(IS, "attempted to run a program for fleet " "which believed itself to be empty " "by player ", &IS->is_player.p_name[0], ""); err(IS, "fleet believes it has no ships! " "Notify the deity!"); } else { gotOne = TRUE; for (i = 0; i < fl.f_count; i++) { curNum = fl.f_ship[i]; accessShip(IS, curNum); if (rsh->sh_efficiency < EFFIC_WARN) { user(IS, getShipName(rsh->sh_type)); userN3(IS, " #", curNum, " isn't efficient enough to " "navigate.\n"); } else if (rsh->sh_planet != NO_ITEM) { user(IS, getShipName(rsh->sh_type)); userN3(IS, " #", curNum, " is on the surface of a planet\n"); } else { if (msc == 0) { flagMobil = rsh->sh_energy; minMobil = rsh->sh_energy; flagRow = rsh->sh_row; flagCol = rsh->sh_col; } if (msc == MAX_NAV_SHIPS) { if (!tooMany) { tooMany = TRUE; err(IS, "too many ships to navigate " "at once"); } } else { nav = &IS->is_movingShips[msc]; nav->n_ship = curNum; nav->n_mobil = ((short)rsh->sh_energy) * 10; nav->n_active = TRUE; msc++; IS->is_movingShipCount = msc; if (rsh->sh_energy < minMobil) { minMobil = rsh->sh_energy; } decrShipCount(IS, mapSector(IS, rsh->sh_row, rsh->sh_col)); } } } } } } if (msc == 0) { if (gotOne) { err(IS, "no ships in that fleet can navigate"); } } else if (flagMobil == 0) { err(IS, "no energy"); } else if (!tooMany) { /* scale mobilities by 10 */ flagMobil = flagMobil * 10; minMobil = minMobil * 10; /* now actually run the program */ runNavProg(IS, &progBuf[0], &flagRow, &flagCol, &flagMobil, &minMobil); /* now remove the ships from the navlist */ for (i = 0; i < IS->is_movingShipCount; i++) { nav = &IS->is_movingShips[i]; if (nav->n_active) { curNum = nav->n_ship; server(IS, rt_lockShip, curNum); rsh->sh_energy = nav->n_mobil / 10; server(IS, rt_unlockShip, curNum); incrShipCount(IS, mapSector(IS, rsh->sh_row, rsh->sh_col)); } } /* copy the modifief course back into the ship */ server(IS, rt_lockShip, shNum); strcpy(&rsh->sh_course[0], &progBuf[0]); server(IS, rt_unlockShip, shNum); } } return TRUE; } return FALSE; }