static int engine_find_datadir(char *argv0) { /* 1) use provided data-dir override */ if(datadir[0]) { if(fs_is_dir(datadir)) return 0; else { dbg_msg("Config", "specified data-dir '%s' does not exist", datadir); return -1; } } /* 2) use data-dir in PWD if present */ if(fs_is_dir("data")) { strcpy(datadir, "data"); return 0; } /* 3) use compiled-in data-dir if present */ if (fs_is_dir(DATA_DIR)) { strcpy(datadir, DATA_DIR); return 0; } /* 4) check for usable path in argv[0] */ { unsigned int pos = strrchr(argv0, '/') - argv0; if (pos < sizeof(datadir)) { char basedir[sizeof(datadir)]; strncpy(basedir, argv0, pos); basedir[pos] = '\0'; str_format(datadir, sizeof(datadir), "%s/data", basedir); if (fs_is_dir(datadir)) return 0; } } #if defined(CONF_FAMILY_UNIX) /* 5) check for all default locations */ { const char *sdirs[] = { "/usr/share/teeworlds", "/usr/local/share/teeworlds" "/opt/teeworlds" }; const int sdirs_count = sizeof(sdirs) / sizeof(sdirs[0]); int i; for (i = 0; i < sdirs_count; i++) { if (fs_is_dir(sdirs[i])) { strcpy(datadir, sdirs[i]); return 0; } } } #endif /* no data-dir found */ dbg_msg("Config", "warning no data directory found"); return -1; }
bool ISOSendSlowInit() { const int bufsize=32; u8 rcvbuf[bufsize]; u8 len; GPIO_InitTypeDef GPIO_InitStructure; len = 0; if(!KWPWaitBusFree()){ return false; } USART3->CR1 &= (~0x00000004); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIOB->BRR=GPIO_Pin_10; DelayMs(200); GPIOB->BSRR=GPIO_Pin_10; DelayMs(400); GPIOB->BRR=GPIO_Pin_10; DelayMs(400); GPIOB->BSRR=GPIO_Pin_10; DelayMs(400); GPIOB->BRR=GPIO_Pin_10; DelayMs(400); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); // dbg_msg("send 5 baut ok!"); USART3->CR1 |= 0x04; len=ISOReceiveFrameByAutoLength(rcvbuf,bufsize,800); if(len!=3){ dbg_msg("~~~no 0x55!"); return false; } DelayMs(40); if(!KWPSendFrame("\xf7",1)) { dbg_msg("sed error!"); return false; } if(!ISOReceiveFrameByAutoLength(rcvbuf,bufsize,1000)) { dbg_msg("rec error!"); DelayMs(1000); return false; } dbg_msg("f7:"); dbg_msg(rcvbuf); DelayMs(100); // KWPSendBytes(pdata,length); return true; }
int CNetConnection::Update() { int64 Now = time_get(); if(State() == NET_CONNSTATE_OFFLINE || State() == NET_CONNSTATE_ERROR) return 0; // check for timeout if(State() != NET_CONNSTATE_OFFLINE && State() != NET_CONNSTATE_CONNECT && (Now-m_LastRecvTime) > time_freq()*10) { m_State = NET_CONNSTATE_ERROR; SetError("Timeout"); } // fix resends if(m_Buffer.First()) { CNetChunkResend *pResend = m_Buffer.First(); // check if we have some really old stuff laying around and abort if not acked if(Now-pResend->m_FirstSendTime > time_freq()*10) { m_State = NET_CONNSTATE_ERROR; SetError("Too weak connection (not acked for 10 seconds)"); } else { // resend packet if we havn't got it acked in 1 second if(Now-pResend->m_LastSendTime > time_freq()) ResendChunk(pResend); } } // send keep alives if nothing has happend for 250ms if(State() == NET_CONNSTATE_ONLINE) { if(time_get()-m_LastSendTime > time_freq()/2) // flush connection after 500ms if needed { int NumFlushedChunks = Flush(); if(NumFlushedChunks && g_Config.m_Debug) dbg_msg("connection", "flushed connection due to timeout. %d chunks.", NumFlushedChunks); } if(time_get()-m_LastSendTime > time_freq()) SendControl(NET_CTRLMSG_KEEPALIVE, 0, 0); } else if(State() == NET_CONNSTATE_CONNECT) { if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect every 500ms SendControl(NET_CTRLMSG_CONNECT, 0, 0); } else if(State() == NET_CONNSTATE_PENDING) { if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms SendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0); } return 0; }
void CMapLayers::OnRender() { if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK) return; CUIRect Screen; Graphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h); vec2 Center = m_pClient->m_pCamera->m_Center; //float center_x = gameclient.camera->center.x; //float center_y = gameclient.camera->center.y; bool PassedGameLayer = false; for(int g = 0; g < m_pLayers->NumGroups(); g++) { CMapItemGroup *pGroup = m_pLayers->GetGroup(g); if(!pGroup) { dbg_msg("MapLayers", "Error:Group was null, Group Number = %d, Total Groups = %d", g, m_pLayers->NumGroups()); dbg_msg("MapLayers", "This is here to prevent a crash but the source of this is unknown, please report this for it to get fixed"); dbg_msg("MapLayers", "we need mapname and crc and the map that caused this if possible, and anymore info you think is relevant"); continue; } if(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping) { // set clipping float Points[4]; MapScreenToGroup(Center.x, Center.y, m_pLayers->GameGroup(), m_pClient->m_pCamera->m_Zoom); Graphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]); float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]); float y0 = (pGroup->m_ClipY - Points[1]) / (Points[3]-Points[1]); float x1 = ((pGroup->m_ClipX+pGroup->m_ClipW) - Points[0]) / (Points[2]-Points[0]); float y1 = ((pGroup->m_ClipY+pGroup->m_ClipH) - Points[1]) / (Points[3]-Points[1]); Graphics()->ClipEnable((int)(x0*Graphics()->ScreenWidth()), (int)(y0*Graphics()->ScreenHeight()), (int)((x1-x0)*Graphics()->ScreenWidth()), (int)((y1-y0)*Graphics()->ScreenHeight())); } MapScreenToGroup(Center.x, Center.y, pGroup, m_pClient->m_pCamera->m_Zoom); for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l); bool Render = false; bool IsGameLayer = false; bool IsFrontLayer = false; bool IsSwitchLayer = false; bool IsTeleLayer = false; bool IsSpeedupLayer = false; if(pLayer == (CMapItemLayer*)m_pLayers->GameLayer()) { IsGameLayer = true; PassedGameLayer = 1; } if(pLayer == (CMapItemLayer*)m_pLayers->FrontLayer()) IsFrontLayer = true; if(pLayer == (CMapItemLayer*)m_pLayers->SwitchLayer()) IsSwitchLayer = true; if(pLayer == (CMapItemLayer*)m_pLayers->TeleLayer()) IsTeleLayer = true; if(pLayer == (CMapItemLayer*)m_pLayers->SpeedupLayer()) IsSpeedupLayer = true; // skip rendering if detail layers if not wanted if(pLayer->m_Flags&LAYERFLAG_DETAIL && !g_Config.m_GfxHighDetail && !IsGameLayer) continue; if(m_Type == -1) Render = true; else if(m_Type == 0) { if(PassedGameLayer) return; Render = true; } else { if(PassedGameLayer && !IsGameLayer) Render = true; } if(Render && pLayer->m_Type == LAYERTYPE_TILES && Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown(KEY_KP0)) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data); CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); char aFilename[256]; str_format(aFilename, sizeof(aFilename), "dumps/tilelayer_dump_%s-%d-%d-%dx%d.txt", CurrentServerInfo.m_aMap, g, l, pTMap->m_Width, pTMap->m_Height); IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(File) { #if defined(CONF_FAMILY_WINDOWS) static const char Newline[] = "\r\n"; #else static const char Newline[] = "\n"; #endif for(int y = 0; y < pTMap->m_Height; y++) { for(int x = 0; x < pTMap->m_Width; x++) io_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index)); io_write(File, Newline, sizeof(Newline)-1); } io_close(File); } } if((Render && !IsGameLayer && (!g_Config.m_ClShowEntities || !g_Config.m_ClDDRaceCheats)) || ((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsGameLayer)) { //layershot_begin(); if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; if(pTMap->m_Image == -1) { if(!g_Config.m_ClShowEntities) Graphics()->TextureSet(-1); else Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); } else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pTMap->m_Image)); CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); Graphics()->BlendNormal(); RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } else if(pLayer->m_Type == LAYERTYPE_QUADS) { CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; if(pQLayer->m_Image == -1) Graphics()->TextureSet(-1); else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pQLayer->m_Image)); CQuad *pQuads = (CQuad *)m_pLayers->Map()->GetDataSwapped(pQLayer->m_Data); Graphics()->BlendNone(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this); Graphics()->BlendNormal(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this); } //layershot_end(); } else if((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsFrontLayer) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); CTile *pFrontTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Front); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); Graphics()->BlendNormal(); RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } else if((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsSwitchLayer) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); CSwitchTile *pSwitchTiles = (CSwitchTile *)m_pLayers->Map()->GetData(pTMap->m_Switch); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderSwitchOverlay(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f); } else if((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsTeleLayer) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); CTeleTile *pTeleTiles = (CTeleTile *)m_pLayers->Map()->GetData(pTMap->m_Tele); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderTeleOverlay(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f); } else if((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsSpeedupLayer) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); CSpeedupTile *pSpeedupTiles = (CSpeedupTile *)m_pLayers->Map()->GetData(pTMap->m_Speedup); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderSpeedupOverlay(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f); } } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); // reset the screen like it was before Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); }
const NETADDR *CServerBrowserFavorites::UpdateFavorites() { NETADDR *pResult = 0; // check if hostname lookup for favourites is done if(m_FavLookup.m_Active && m_FavLookup.m_HostLookup.m_Job.Status() == CJob::STATE_DONE) { // check if favourite has not been removed in the meanwhile if(m_FavLookup.m_FavoriteIndex != -1) { if(m_FavLookup.m_HostLookup.m_Job.Result() == 0) { CFavoriteServer *pEntry = FindFavoriteByAddr(m_FavLookup.m_HostLookup.m_Addr, 0); if(pEntry) { // address is already in the list -> acquire hostname if existing entry lacks it and drop multiple address entry if(pEntry->m_State != FAVSTATE_HOST) { str_copy(pEntry->m_aHostname, m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname, sizeof(pEntry->m_aHostname)); pEntry->m_State = FAVSTATE_HOST; dbg_msg("test", "fav aquired hostname, %s", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname); } RemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex); dbg_msg("test", "fav removed multiple entry"); } else { // address wasn't in the list yet -> add it (optional check if hostname matches given address -> drop entry on fail) if(m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State == FAVSTATE_LOOKUP || net_addr_comp(&m_aFavoriteServers[m_NumFavoriteServers].m_Addr, &m_FavLookup.m_HostLookup.m_Addr) == 0) { m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_Addr = m_FavLookup.m_HostLookup.m_Addr; m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State = FAVSTATE_HOST; pResult = &m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_Addr; dbg_msg("test", "fav added, %s", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname); } else { RemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex); dbg_msg("test", "fav removed entry that failed hostname-address check"); } } } else { // hostname lookup failed if(m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State == FAVSTATE_LOOKUP) { m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State = FAVSTATE_INVALID; dbg_msg("test", "fav invalid, %s", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname); } else { RemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex); dbg_msg("test", "fav removed invalid check-based entry"); } } } m_FavLookup.m_Active = false; } // add hostname lookup for favourites if(m_FavLookup.m_LookupCount > 0 && !m_FavLookup.m_Active) { for(int i = 0; i < m_NumFavoriteServers; i++) { if(m_aFavoriteServers[i].m_State <= FAVSTATE_LOOKUPCHECK) { m_pEngine->HostLookup(&m_FavLookup.m_HostLookup, m_aFavoriteServers[i].m_aHostname, m_pNetClient->NetType()); m_FavLookup.m_FavoriteIndex = i; --m_FavLookup.m_LookupCount; m_FavLookup.m_Active = true; break; } } } return pResult; }
static int interpret_table_entry(const char *line) { char buf[1024], type, *path = NULL, *name = NULL; int len; struct path_htbl_element *ph_elt = NULL; struct name_htbl_element *nh_elt = NULL; unsigned int mode = 0755, uid = 0, gid = 0, major = 0, minor = 0; unsigned int start = 0, increment = 0, count = 0; buf[1023] = 0; if (sscanf(line, "%1023s %c %o %u %u %u %u %u %u %u", buf, &type, &mode, &uid, &gid, &major, &minor, &start, &increment, &count) < 0) return sys_err_msg("sscanf failed"); dbg_msg(3, "name %s, type %c, mode %o, uid %u, gid %u, major %u, " "minor %u, start %u, inc %u, cnt %u", buf, type, mode, uid, gid, major, minor, start, increment, count); len = strlen(buf); if (len == 1023) return err_msg("too long path"); if (!strcmp(buf, "/")) return err_msg("device table entries require absolute paths"); if (buf[1] == '\0') return err_msg("root directory cannot be created"); if (strstr(buf, "//")) return err_msg("'//' cannot be used in the path"); if (buf[len - 1] == '/') return err_msg("do not put '/' at the end"); if (strstr(buf, "/./") || strstr(buf, "/../") || !strcmp(buf + len - 2, "/.") || !strcmp(buf + len - 3, "/..")) return err_msg("'.' and '..' cannot be used in the path"); switch (type) { case 'd': mode |= S_IFDIR; break; case 'f': mode |= S_IFREG; break; case 'p': mode |= S_IFIFO; break; case 'c': mode |= S_IFCHR; break; case 'b': mode |= S_IFBLK; break; default: return err_msg("unsupported file type '%c'", type); } if (separate_last(buf, len, &path, &name)) return -1; /* * Check if this path already exist in the path hash table and add it * if it is not. */ ph_elt = hashtable_search(path_htbl, path); if (!ph_elt) { dbg_msg(3, "inserting '%s' into path hash table", path); ph_elt = malloc(sizeof(struct path_htbl_element)); if (!ph_elt) { err_msg("cannot allocate %zd bytes of memory", sizeof(struct path_htbl_element)); goto out_free; } if (!hashtable_insert(path_htbl, path, ph_elt)) { err_msg("cannot insert into path hash table"); goto out_free; } ph_elt->path = path; path = NULL; ph_elt->name_htbl = create_hashtable(128, &r5_hash, &is_equivalent); if (!ph_elt->name_htbl) { err_msg("cannot create name hash table"); goto out_free; } } if (increment != 0 && count == 0) return err_msg("count cannot be zero if increment is non-zero"); /* * Add the file/directory/device node (last component of the path) to * the name hashtable. The name hashtable resides in the corresponding * path hashtable element. */ if (count == 0) { /* This entry does not require any iterating */ nh_elt = malloc(sizeof(struct name_htbl_element)); if (!nh_elt) { err_msg("cannot allocate %zd bytes of memory", sizeof(struct name_htbl_element)); goto out_free; } nh_elt->mode = mode; nh_elt->uid = uid; nh_elt->gid = gid; nh_elt->dev = makedev(major, minor); dbg_msg(3, "inserting '%s' into name hash table (major %d, minor %d)", name, major(nh_elt->dev), minor(nh_elt->dev)); if (hashtable_search(ph_elt->name_htbl, name)) return err_msg("'%s' is referred twice", buf); nh_elt->name = name; if (!hashtable_insert(ph_elt->name_htbl, name, nh_elt)) { err_msg("cannot insert into name hash table"); goto out_free; } } else { int i, num = start + count, len = strlen(name) + 20; char *nm; for (i = start; i < num; i++) { nh_elt = malloc(sizeof(struct name_htbl_element)); if (!nh_elt) { err_msg("cannot allocate %zd bytes of memory", sizeof(struct name_htbl_element)); goto out_free; } nh_elt->mode = mode; nh_elt->uid = uid; nh_elt->gid = gid; nh_elt->dev = makedev(major, minor + (i - start) * increment); nm = malloc(len); if (!nm) { err_msg("cannot allocate %d bytes of memory", len); goto out_free; } sprintf(nm, "%s%d", name, i); nh_elt->name = nm; dbg_msg(3, "inserting '%s' into name hash table (major %d, minor %d)", nm, major(nh_elt->dev), minor(nh_elt->dev)); if (hashtable_search(ph_elt->name_htbl, nm)) { err_msg("'%s' is referred twice", buf); free (nm); goto out_free; } if (!hashtable_insert(ph_elt->name_htbl, nm, nh_elt)) { err_msg("cannot insert into name hash table"); free (nm); goto out_free; } } free(name); name = NULL; } return 0; out_free: free(ph_elt); free(nh_elt); free(path); free(name); return -1; }
void CCommandProcessorFragment_OpenGL::SetState(const CCommandBuffer::SState &State) { // blend switch(State.m_BlendMode) { case CCommandBuffer::BLEND_NONE: glDisable(GL_BLEND); break; case CCommandBuffer::BLEND_ALPHA: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case CCommandBuffer::BLEND_ADDITIVE: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; default: dbg_msg("render", "unknown blendmode %d\n", State.m_BlendMode); }; // clip if(State.m_ClipEnable) { glScissor(State.m_ClipX, State.m_ClipY, State.m_ClipW, State.m_ClipH); glEnable(GL_SCISSOR_TEST); } else glDisable(GL_SCISSOR_TEST); // texture glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_3D); if(State.m_Texture >= 0 && State.m_Texture < CCommandBuffer::MAX_TEXTURES) { if(State.m_Dimension == 2 && (m_aTextures[State.m_Texture].m_State&CTexture::STATE_TEX2D)) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_aTextures[State.m_Texture].m_Tex2D); } else if(State.m_Dimension == 3 && (m_aTextures[State.m_Texture].m_State&CTexture::STATE_TEX3D)) { glEnable(GL_TEXTURE_3D); glBindTexture(GL_TEXTURE_3D, m_aTextures[State.m_Texture].m_Tex3D); } else dbg_msg("render", "invalid texture %d %d %d\n", State.m_Texture, State.m_Dimension, m_aTextures[State.m_Texture].m_State); } // wrap mode switch(State.m_WrapModeU) { case IGraphics::WRAP_REPEAT: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); break; case IGraphics::WRAP_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); break; default: dbg_msg("render", "unknown wrapmode %d\n", State.m_WrapModeU); }; switch(State.m_WrapModeV) { case IGraphics::WRAP_REPEAT: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); break; case IGraphics::WRAP_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); break; default: dbg_msg("render", "unknown wrapmode %d\n", State.m_WrapModeV); }; if(State.m_Texture >= 0 && State.m_Texture < CCommandBuffer::MAX_TEXTURES && State.m_Dimension == 3) { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); } // screen mapping glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(State.m_ScreenTL.x, State.m_ScreenBR.x, State.m_ScreenBR.y, State.m_ScreenTL.y, 1.0f, 10.f); }
bool CSqlServer::Connect() { Lock(); if (m_pDriver != NULL && m_pConnection != NULL) { try { // Connect to specific database m_pConnection->setSchema(m_aDatabase); return true; } catch (sql::SQLException &e) { dbg_msg("sql", "MySQL Error: %s", e.what()); } catch (const std::exception& ex) { dbg_msg("sql", "MySQL Error: %s", ex.what()); } catch (const std::string& ex) { dbg_msg("sql", "MySQL Error: %s", ex.c_str()); } catch (...) { dbg_msg("sql", "Unknown Error cause by the MySQL/C++ Connector"); } dbg_msg("sql", "ERROR: SQL connection failed"); UnLock(); return false; } try { m_pDriver = 0; m_pConnection = 0; m_pStatement = 0; sql::ConnectOptionsMap connection_properties; connection_properties["hostName"] = sql::SQLString(m_aIp); connection_properties["port"] = m_Port; connection_properties["userName"] = sql::SQLString(m_aUser); connection_properties["password"] = sql::SQLString(m_aPass); connection_properties["OPT_CONNECT_TIMEOUT"] = 10; connection_properties["OPT_READ_TIMEOUT"] = 10; connection_properties["OPT_WRITE_TIMEOUT"] = 20; connection_properties["OPT_RECONNECT"] = true; connection_properties["OPT_CHARSET_NAME"] = sql::SQLString("utf8mb4"); // Create connection m_pDriver = get_driver_instance(); m_pConnection = m_pDriver->connect(connection_properties); // Create Statement m_pStatement = m_pConnection->createStatement(); if (m_SetUpDB) { char aBuf[128]; // create database str_format(aBuf, sizeof(aBuf), "CREATE DATABASE IF NOT EXISTS %s CHARACTER SET utf8mb4", m_aDatabase); m_pStatement->execute(aBuf); } // Connect to specific database m_pConnection->setSchema(m_aDatabase); dbg_msg("sql", "sql connection established"); return true; } catch (sql::SQLException &e) { dbg_msg("sql", "MySQL Error: %s", e.what()); } catch (const std::exception& ex) { dbg_msg("sql", "MySQL Error: %s", ex.what()); } catch (const std::string& ex) { dbg_msg("sql", "MySQL Error: %s", ex.c_str()); } catch (...) { dbg_msg("sql", "Unknown Error cause by the MySQL/C++ Connector"); } dbg_msg("sql", "ERROR: sql connection failed"); UnLock(); return false; }
void CSqlScore::ShowRankThread(void *pUser) { lock_wait(gs_SqlLock); CSqlScoreData *pData = (CSqlScoreData *)pUser; // Connect to database if(pData->m_pSqlData->Connect()) { try { // check strings char originalName[MAX_NAME_LENGTH]; strcpy(originalName,pData->m_aName); pData->m_pSqlData->ClearString(pData->m_aName); // check sort methode char aBuf[600]; pData->m_pSqlData->m_pStatement->execute("SET @rownum := 0;"); str_format(aBuf, sizeof(aBuf), "SELECT Rank, one_rank.Name, one_rank.Time, UNIX_TIMESTAMP(CURRENT_TIMESTAMP)-UNIX_TIMESTAMP(r.Timestamp) as Ago, UNIX_TIMESTAMP(r.Timestamp) as stamp " "FROM (" "SELECT * FROM (" "SELECT @rownum := @rownum + 1 AS RANK, Name, Time " "FROM (" "SELECT Name, min(Time) as Time " "FROM %s_%s_race " "Group By Name) as all_top_times " "ORDER BY Time ASC) as all_ranks " "WHERE all_ranks.Name = '%s') as one_rank " "LEFT JOIN %s_%s_race as r " "ON one_rank.Name = r.Name && one_rank.Time = r.Time " "ORDER BY Ago ASC " "LIMIT 0,1" ";", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap,pData->m_aName, pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap); pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); if(pData->m_pSqlData->m_pResults->rowsCount() != 1) { str_format(aBuf, sizeof(aBuf), "%s is not ranked", originalName); pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); } else { pData->m_pSqlData->m_pResults->next(); int since = (int)pData->m_pSqlData->m_pResults->getInt("Ago"); char agoString[40]; mem_zero(agoString, sizeof(agoString)); agoTimeToString(since,agoString); float Time = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); int Rank = (int)pData->m_pSqlData->m_pResults->getInt("Rank"); if(g_Config.m_SvHideScore) str_format(aBuf, sizeof(aBuf), "Your time: %d minute(s) %5.2f second(s)", (int)(Time/60), Time-((int)Time/60*60)); else str_format(aBuf, sizeof(aBuf), "%d. %s Time: %d minute(s) %5.2f second(s)", Rank, pData->m_pSqlData->m_pResults->getString("Name").c_str(), (int)(Time/60), Time-((int)Time/60*60), agoString); if(pData->m_pSqlData->m_pResults->getInt("stamp") != 0){ pData->m_pSqlData->GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, pData->m_ClientID); str_format(aBuf, sizeof(aBuf), "Finished: %s ago", agoString); } if(pData->m_Search) strcat(aBuf, pData->m_aRequestingPlayer); pData->m_pSqlData->GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, pData->m_ClientID); } dbg_msg("SQL", "Showing rank done"); // delete results and statement delete pData->m_pSqlData->m_pResults; delete pData->m_pSqlData->m_pStatement; } catch (sql::SQLException &e) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); dbg_msg("SQL", aBuf); dbg_msg("SQL", "ERROR: Could not show rank"); } // disconnect from database pData->m_pSqlData->Disconnect();//TODO:Check if an exception is caught will this still execute ? } delete pData; lock_release(gs_SqlLock); }
int main(void) { dbg_logger_stdout(); char aUserdir[1024] = {0}; char aPixelFile[1024] = {0}; int PngCounter = 0; fs_storage_path("Teeworlds", aUserdir, sizeof(aUserdir)); str_format(aPixelFile, sizeof(aPixelFile), "%s/tmp/pixelstream/video.stream", aUserdir); IOHANDLE PixelStream = io_open(aPixelFile, IOFLAG_READ); long long t = 0; long long tOld = 0; long long tOldAdj = 0; unsigned char *pData = 0; unsigned char *pDataOld = 0; unsigned char *pDataMixed = 0; unsigned char *pTempRow = 0; CThreadData *pThreadData = new CThreadData(); mem_zero(pThreadData, sizeof(CThreadData)); int64 StartTime = time_get(); int64 SpeedTime = time_get(); while(PixelStream) { int Size = 0; int W = 0; int H = 0; int len = io_read(PixelStream, &t, sizeof(t)); io_read(PixelStream, &Size, sizeof(Size)); io_read(PixelStream, &W, sizeof(W)); io_read(PixelStream, &H, sizeof(H)); if (len == 0) break; if (!pData) pData = new unsigned char[Size]; if (!pDataOld) pDataOld = new unsigned char[Size]; if (!pDataMixed) pDataMixed = new unsigned char[Size]; if (!pTempRow) pTempRow = new unsigned char[W * 3]; io_read(PixelStream, pData, Size); if (pThreadData->m_Size == 0) { pThreadData->m_Size = Size; pThreadData->m_H = H; pThreadData->m_W = W; thread_detach(thread_create(RotThread, pThreadData)); } int i = 0; while(1) { if (pThreadData->m_pDataIn[i] == 0) { pThreadData->m_CounterIn++; pThreadData->m_aIndexIn[i] = pThreadData->m_CounterIn; unsigned char *p = new unsigned char[Size]; mem_copy(p, pData, Size); pThreadData->m_pDataIn[i] = p; } i++; if (i == 10) break; if (THREADWAITDELAY) thread_sleep(THREADWAITDELAY); } while(1) { int MinIndex = 0; int MinI= 0; for (int i = 0; i < 10; i++) { if (pThreadData->m_pDataOut[i] != 0 && (MinIndex == 0 || MinIndex > pThreadData->m_aIndexOut[i])) { MinIndex = pThreadData->m_aIndexOut[i]; MinI = i; } } if (MinIndex != 0) { mem_copy(pData, pThreadData->m_pDataOut[MinI], Size); delete []pThreadData->m_pDataOut[MinI]; pThreadData->m_pDataOut[MinI] = 0; break; } if (THREADWAITDELAY) thread_sleep(THREADWAITDELAY); } float tAdj = 0.0f; if (tOld && tOld + tAdj + FRAMETIME < t) { while(tOld && tOld + tAdj + FRAMETIME < t) { PngCounter++; char aBuf[1024]; if (PngCounter < 10) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png0000%i.png", aUserdir, PngCounter); if (PngCounter < 100) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png000%i.png", aUserdir, PngCounter); if (PngCounter < 1000) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png00%i.png", aUserdir, PngCounter); if (PngCounter < 10000) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png0%i.png", aUserdir, PngCounter); if (PngCounter < 100000) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png%i.png", aUserdir, PngCounter); #if THREADCOUNT > 0 CBlendThreadData *apBlendData[THREADCOUNT]; for (int i = 0; i < THREADCOUNT; i++) { apBlendData[i] = new CBlendThreadData(); mem_zero(apBlendData[i], sizeof(CBlendThreadData)); apBlendData[i]->m_pIn1 = pData; apBlendData[i]->m_pIn2 = pDataOld; apBlendData[i]->m_pOut = pDataMixed; apBlendData[i]->m_Size = Size; apBlendData[i]->m_Steps = THREADCOUNT; apBlendData[i]->m_Start = i; apBlendData[i]->m_Mix = 1.0f - (tAdj + FRAMETIMEHALF) / ((float)(t - tOld)); thread_detach(thread_create(BlendThread, apBlendData[i])); } while (1) { bool Done = true; for (int i = 0; i < THREADCOUNT; i++) { if (apBlendData[i]->m_Finished == false) { Done = false; break; } } if (THREADWAITDELAY) thread_sleep(THREADWAITDELAY); if (Done) break; } #else for (int i = 0; i < Size; i++) { pDataMixed[i] = mix(pData[i], pDataOld[i], 1.0f - (tAdj + FRAMETIMEHALF) / ((float)(t - tOld))); } #endif png_t Png; png_init(0,0); png_open_file_write(&Png, aBuf); // ignore_convention png_set_data(&Png, W, H, 8, PNG_TRUECOLOR, (unsigned char *)pDataMixed); // ignore_convention png_close_file(&Png); // ignore_convention if (time_get() - SpeedTime > time_freq()) { dbg_msg("Frame", "%i (Avg: %.2f s)", PngCounter, ((float)(time_get() - StartTime) / (float)time_freq()) / (float)PngCounter); dbg_msg("FPS", "%.f", (float)PngCounter / ((float)(time_get() - StartTime) / (float)time_freq())); SpeedTime = time_get(); } tAdj = tAdj + FRAMETIME; } } else { PngCounter++; char aBuf[1024]; if (PngCounter < 10) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png0000%i.png", aUserdir, PngCounter); if (PngCounter < 100) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png000%i.png", aUserdir, PngCounter); if (PngCounter < 1000) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png00%i.png", aUserdir, PngCounter); if (PngCounter < 10000) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png0%i.png", aUserdir, PngCounter); if (PngCounter < 100000) str_format(aBuf, sizeof(aBuf), "%s/tmp/pixelstream/png%i.png", aUserdir, PngCounter); png_t Png; png_init(0,0); png_open_file_write(&Png, aBuf); // ignore_convention png_set_data(&Png, W, H, 8, PNG_TRUECOLOR, (unsigned char *)pData); // ignore_convention png_close_file(&Png); // ignore_convention if (time_get() - SpeedTime > time_freq()) { dbg_msg("Frame", "%i (Avg: %.2f s)", PngCounter, ((float)(time_get() - StartTime) / (float)time_freq()) / (float)PngCounter); dbg_msg("FPS", "%.f", (float)PngCounter / ((float)(time_get() - StartTime) / (float)time_freq())); SpeedTime = time_get(); } } mem_copy(pDataOld, pData, Size); tOld = t; } delete[] pData; delete[] pDataOld; delete[] pDataMixed; return 0; }
void CGraphics_Threaded::FlushVertices() { if(m_NumVertices == 0) return; int NumVerts = m_NumVertices; m_NumVertices = 0; CCommandBuffer::SCommand_Render Cmd; Cmd.m_State = m_State; if(m_Drawing == DRAWING_QUADS) { if(g_Config.m_GfxQuadAsTriangle) { Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_TRIANGLES; Cmd.m_PrimCount = NumVerts/3; } else { Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_QUADS; Cmd.m_PrimCount = NumVerts/4; } } else if(m_Drawing == DRAWING_LINES) { Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_LINES; Cmd.m_PrimCount = NumVerts/2; } else return; Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); if(Cmd.m_pVertices == 0x0) { // kick command buffer and try again KickCommandBuffer(); Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); if(Cmd.m_pVertices == 0x0) { dbg_msg("graphics", "failed to allocate data for vertices"); return; } } // check if we have enough free memory in the commandbuffer if(!m_pCommandBuffer->AddCommand(Cmd)) { // kick command buffer and try again KickCommandBuffer(); Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); if(Cmd.m_pVertices == 0x0) { dbg_msg("graphics", "failed to allocate data for vertices"); return; } if(!m_pCommandBuffer->AddCommand(Cmd)) { dbg_msg("graphics", "failed to allocate memory for render command"); return; } } mem_copy(Cmd.m_pVertices, m_aVertices, sizeof(CCommandBuffer::SVertex)*NumVerts); }
int UnpackMessageID(int *pID, bool *pSys, struct CUuid *pUuid, CUnpacker *pUnpacker, CMsgPacker *pPacker) { *pID = 0; *pSys = false; mem_zero(pUuid, sizeof(*pUuid)); int MsgID = pUnpacker->GetInt(); if(pUnpacker->Error()) { return UNPACKMESSAGE_ERROR; } *pID = MsgID >> 1; *pSys = MsgID & 1; if(*pID < 0 || *pID >= OFFSET_UUID) { return UNPACKMESSAGE_ERROR; } if(*pID != 0) // NETMSG_EX, NETMSGTYPE_EX { return UNPACKMESSAGE_OK; } *pID = g_UuidManager.UnpackUuid(pUnpacker, pUuid); if(*pID == UUID_INVALID || *pID == UUID_UNKNOWN) { return UNPACKMESSAGE_ERROR; } if(*pSys) { switch(*pID) { case NETMSG_WHATIS: { CUuid Uuid2; int ID2 = g_UuidManager.UnpackUuid(pUnpacker, &Uuid2); if(ID2 == UUID_INVALID) { break; } if(ID2 == UUID_UNKNOWN) { new (pPacker) CMsgPacker(NETMSG_IDONTKNOW); pPacker->AddRaw(&Uuid2, sizeof(Uuid2)); } else { new (pPacker) CMsgPacker(NETMSG_ITIS); pPacker->AddRaw(&Uuid2, sizeof(Uuid2)); pPacker->AddString(g_UuidManager.GetName(ID2), 0); } return UNPACKMESSAGE_ANSWER; } case NETMSG_IDONTKNOW: if(g_Config.m_Debug) { CUuid Uuid2; g_UuidManager.UnpackUuid(pUnpacker, &Uuid2); if(pUnpacker->Error()) break; char aBuf[UUID_MAXSTRSIZE]; FormatUuid(Uuid2, aBuf, sizeof(aBuf)); dbg_msg("uuid", "peer: unknown %s", aBuf); } break; case NETMSG_ITIS: if(g_Config.m_Debug) { CUuid Uuid2; g_UuidManager.UnpackUuid(pUnpacker, &Uuid2); const char *pName = pUnpacker->GetString(CUnpacker::SANITIZE_CC); if(pUnpacker->Error()) break; char aBuf[UUID_MAXSTRSIZE]; FormatUuid(Uuid2, aBuf, sizeof(aBuf)); dbg_msg("uuid", "peer: %s %s", aBuf, pName); } break; } } return UNPACKMESSAGE_OK; }
/** * read_znode - read an indexing node from flash and fill znode. * @c: UBIFS file-system description object * @lnum: LEB of the indexing node to read * @offs: node offset * @len: node length * @znode: znode to read to * * This function reads an indexing node from the flash media and fills znode * with the read data. Returns zero in case of success and a negative error * code in case of failure. The read indexing node is validated and if anything * is wrong with it, this function prints complaint messages and returns * %-EINVAL. */ static int read_znode(struct ubifs_info *c, int lnum, int offs, int len, struct ubifs_znode *znode) { int i, err, type, cmp; struct ubifs_idx_node *idx; idx = kmalloc(c->max_idx_node_sz, GFP_NOFS); if (!idx) return -ENOMEM; err = ubifs_read_node(c, idx, UBIFS_IDX_NODE, len, lnum, offs); if (err < 0) { kfree(idx); return err; } znode->child_cnt = le16_to_cpu(idx->child_cnt); znode->level = le16_to_cpu(idx->level); dbg_tnc("LEB %d:%d, level %d, %d branch", lnum, offs, znode->level, znode->child_cnt); if (znode->child_cnt > c->fanout || znode->level > UBIFS_MAX_LEVELS) { dbg_err("current fanout %d, branch count %d", c->fanout, znode->child_cnt); dbg_err("max levels %d, znode level %d", UBIFS_MAX_LEVELS, znode->level); err = 1; goto out_dump; } for (i = 0; i < znode->child_cnt; i++) { const struct ubifs_branch *br = ubifs_idx_branch(c, idx, i); struct ubifs_zbranch *zbr = &znode->zbranch[i]; key_read(c, &br->key, &zbr->key); zbr->lnum = le32_to_cpu(br->lnum); zbr->offs = le32_to_cpu(br->offs); zbr->len = le32_to_cpu(br->len); zbr->znode = NULL; /* Validate branch */ if (zbr->lnum < c->main_first || zbr->lnum >= c->leb_cnt || zbr->offs < 0 || zbr->offs + zbr->len > c->leb_size || zbr->offs & 7) { dbg_err("bad branch %d", i); err = 2; goto out_dump; } switch (key_type(c, &zbr->key)) { case UBIFS_INO_KEY: case UBIFS_DATA_KEY: case UBIFS_DENT_KEY: case UBIFS_XENT_KEY: break; default: dbg_msg("bad key type at slot %d: %d", i, key_type(c, &zbr->key)); err = 3; goto out_dump; } if (znode->level) continue; type = key_type(c, &zbr->key); if (c->ranges[type].max_len == 0) { if (zbr->len != c->ranges[type].len) { dbg_err("bad target node (type %d) length (%d)", type, zbr->len); dbg_err("have to be %d", c->ranges[type].len); err = 4; goto out_dump; } } else if (zbr->len < c->ranges[type].min_len || zbr->len > c->ranges[type].max_len) { dbg_err("bad target node (type %d) length (%d)", type, zbr->len); dbg_err("have to be in range of %d-%d", c->ranges[type].min_len, c->ranges[type].max_len); err = 5; goto out_dump; } } /* * Ensure that the next key is greater or equivalent to the * previous one. */ for (i = 0; i < znode->child_cnt - 1; i++) { const union ubifs_key *key1, *key2; key1 = &znode->zbranch[i].key; key2 = &znode->zbranch[i + 1].key; cmp = keys_cmp(c, key1, key2); if (cmp > 0) { dbg_err("bad key order (keys %d and %d)", i, i + 1); err = 6; goto out_dump; } else if (cmp == 0 && !is_hash_key(c, key1)) { /* These can only be keys with colliding hash */ dbg_err("keys %d and %d are not hashed but equivalent", i, i + 1); err = 7; goto out_dump; } } kfree(idx); return 0; out_dump: ubifs_err("bad indexing node at LEB %d:%d, error %d", lnum, offs, err); dbg_dump_node(c, idx); kfree(idx); return -EINVAL; }
static void server_process_client_packet(NETCHUNK *packet) { int cid = packet->client_id; NETADDR addr; int sys; int msg = msg_unpack_start(packet->data, packet->data_size, &sys); if(clients[cid].state == SRVCLIENT_STATE_AUTH) { if(sys && msg == NETMSG_INFO) { char version[64]; const char *password; str_copy(version, msg_unpack_string(), 64); if(strcmp(version, mods_net_version()) != 0) { /* OH F**K! wrong version, drop him */ char reason[256]; str_format(reason, sizeof(reason), "wrong version. server is running '%s' and client '%s'.", mods_net_version(), version); netserver_drop(net, cid, reason); return; } str_copy(clients[cid].name, msg_unpack_string(), MAX_NAME_LENGTH); str_copy(clients[cid].clan, msg_unpack_string(), MAX_CLANNAME_LENGTH); password = msg_unpack_string(); if(config.password[0] != 0 && strcmp(config.password, password) != 0) { /* wrong password */ netserver_drop(net, cid, "wrong password"); return; } clients[cid].state = SRVCLIENT_STATE_CONNECTING; server_send_map(cid); } } else { if(sys) { /* system message */ if(msg == NETMSG_REQUEST_MAP_DATA) { int chunk = msg_unpack_int(); int chunk_size = 1024-128; int offset = chunk * chunk_size; int last = 0; /* drop faulty map data requests */ if(chunk < 0 || offset > current_map_size) return; if(offset+chunk_size >= current_map_size) { chunk_size = current_map_size-offset; if(chunk_size < 0) chunk_size = 0; last = 1; } msg_pack_start_system(NETMSG_MAP_DATA, MSGFLAG_VITAL|MSGFLAG_FLUSH); msg_pack_int(last); msg_pack_int(current_map_size); msg_pack_int(chunk_size); msg_pack_raw(¤t_map_data[offset], chunk_size); msg_pack_end(); server_send_msg(cid); if(config.debug) dbg_msg("server", "sending chunk %d with size %d", chunk, chunk_size); } else if(msg == NETMSG_READY) { if(clients[cid].state == SRVCLIENT_STATE_CONNECTING) { netserver_client_addr(net, cid, &addr); dbg_msg("server", "player is ready. cid=%x ip=%d.%d.%d.%d", cid, addr.ip[0], addr.ip[1], addr.ip[2], addr.ip[3] ); clients[cid].state = SRVCLIENT_STATE_READY; mods_connected(cid); } } else if(msg == NETMSG_ENTERGAME) { if(clients[cid].state == SRVCLIENT_STATE_READY) { netserver_client_addr(net, cid, &addr); dbg_msg("server", "player has entered the game. cid=%x ip=%d.%d.%d.%d", cid, addr.ip[0], addr.ip[1], addr.ip[2], addr.ip[3] ); clients[cid].state = SRVCLIENT_STATE_INGAME; mods_client_enter(cid); } } else if(msg == NETMSG_INPUT) { int tick, size, i; CLIENT_INPUT *input; int64 tagtime; clients[cid].last_acked_snapshot = msg_unpack_int(); tick = msg_unpack_int(); size = msg_unpack_int(); /* check for errors */ if(msg_unpack_error() || size/4 > MAX_INPUT_SIZE) return; if(clients[cid].last_acked_snapshot > 0) clients[cid].snap_rate = SRVCLIENT_SNAPRATE_FULL; if(snapstorage_get(&clients[cid].snapshots, clients[cid].last_acked_snapshot, &tagtime, 0, 0) >= 0) clients[cid].latency = (int)(((time_get()-tagtime)*1000)/time_freq()); /* add message to report the input timing */ /* skip packets that are old */ if(tick > clients[cid].last_input_tick) { int time_left = ((server_tick_start_time(tick)-time_get())*1000) / time_freq(); msg_pack_start_system(NETMSG_INPUTTIMING, 0); msg_pack_int(tick); msg_pack_int(time_left); msg_pack_end(); server_send_msg(cid); } clients[cid].last_input_tick = tick; input = &clients[cid].inputs[clients[cid].current_input]; if(tick <= server_tick()) tick = server_tick()+1; input->game_tick = tick; for(i = 0; i < size/4; i++) input->data[i] = msg_unpack_int(); mem_copy(clients[cid].latestinput.data, input->data, MAX_INPUT_SIZE*sizeof(int)); clients[cid].current_input++; clients[cid].current_input %= 200; /* call the mod with the fresh input data */ if(clients[cid].state == SRVCLIENT_STATE_INGAME) mods_client_direct_input(cid, clients[cid].latestinput.data); } else if(msg == NETMSG_RCON_CMD) { const char *cmd = msg_unpack_string(); if(msg_unpack_error() == 0 && clients[cid].authed) { dbg_msg("server", "cid=%d rcon='%s'", cid, cmd); console_execute_line(cmd); } } else if(msg == NETMSG_RCON_AUTH) { const char *pw; msg_unpack_string(); /* login name, not used */ pw = msg_unpack_string(); if(msg_unpack_error() == 0) { if(config.sv_rcon_password[0] == 0) { server_send_rcon_line(cid, "No rcon password set on server. Set sv_rcon_password to enable the remote console."); } else if(strcmp(pw, config.sv_rcon_password) == 0) { msg_pack_start_system(NETMSG_RCON_AUTH_STATUS, MSGFLAG_VITAL); msg_pack_int(1); msg_pack_end(); server_send_msg(cid); clients[cid].authed = 1; server_send_rcon_line(cid, "Authentication successful. Remote console access granted."); dbg_msg("server", "cid=%d authed", cid); } else { server_send_rcon_line(cid, "Wrong password."); } } } else if(msg == NETMSG_PING) { msg_pack_start_system(NETMSG_PING_REPLY, 0); msg_pack_end(); server_send_msg(cid); } else { char hex[] = "0123456789ABCDEF"; char buf[512]; int b; for(b = 0; b < packet->data_size && b < 32; b++) { buf[b*3] = hex[((const unsigned char *)packet->data)[b]>>4]; buf[b*3+1] = hex[((const unsigned char *)packet->data)[b]&0xf]; buf[b*3+2] = ' '; buf[b*3+3] = 0; } dbg_msg("server", "strange message cid=%d msg=%d data_size=%d", cid, msg, packet->data_size); dbg_msg("server", "%s", buf); } } else { /* game message */ if(clients[cid].state >= SRVCLIENT_STATE_READY) mods_message(msg, cid); } }
void Run(int Port, NETADDR Dest) { NETADDR Src = {NETTYPE_IPV4, {0,0,0,0}, static_cast<unsigned short>(Port)}; NETSOCKET Socket = net_udp_create(Src); char aBuffer[1024*2]; int ID = 0; int Delaycounter = 0; while(1) { static int Lastcfg = 0; int n = ((time_get()/time_freq())/m_ConfigInterval) % m_ConfigNumpingconfs; CPingConfig Ping = m_aConfigPings[n]; if(n != Lastcfg) dbg_msg("crapnet", "cfg = %d", n); Lastcfg = n; // handle incomming packets while(1) { // fetch data int DataTrash = 0; NETADDR From; int Bytes = net_udp_recv(Socket, &From, aBuffer, 1024*2); if(Bytes <= 0) break; if((rand()%100) < Ping.m_Loss) // drop the packet { if(m_ConfigLog) dbg_msg("crapnet", "dropped packet"); continue; } // create new packet CPacket *p = (CPacket *)mem_alloc(sizeof(CPacket)+Bytes, 1); if(net_addr_comp(&From, &Dest) == 0) p->m_SendTo = Src; // from the server else { Src = From; // from the client p->m_SendTo = Dest; } // queue packet p->m_pPrev = m_pLast; p->m_pNext = 0; if(m_pLast) m_pLast->m_pNext = p; else { m_pFirst = p; m_pLast = p; } m_pLast = p; // set data in packet p->m_Timestamp = time_get(); p->m_DataSize = Bytes; p->m_ID = ID++; mem_copy(p->m_aData, aBuffer, Bytes); if(ID > 20 && Bytes > 6 && DataTrash) { p->m_aData[6+(rand()%(Bytes-6))] = rand()&255; // modify a byte if((rand()%10) == 0) { p->m_DataSize -= rand()%32; if(p->m_DataSize < 6) p->m_DataSize = 6; } } if(Delaycounter <= 0) { if(Ping.m_Delay) p->m_Timestamp += (time_freq()*1000)/Ping.m_Delay; Delaycounter = Ping.m_DelayFreq; } Delaycounter--; if(m_ConfigLog) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&From, aAddrStr, sizeof(aAddrStr), true); dbg_msg("crapnet", "<< %08d %s (%d)", p->m_ID, aAddrStr, p->m_DataSize); } } // /*while(1) {*/ CPacket *p = 0; CPacket *pNext = m_pFirst; while(1) { p = pNext; if(!p) break; pNext = p->m_pNext; if((time_get()-p->m_Timestamp) > m_CurrentLatency) { char aFlags[] = " "; if(m_ConfigReorder && (rand()%2) == 0 && p->m_pNext) { aFlags[0] = 'R'; p = m_pFirst->m_pNext; } if(p->m_pNext) p->m_pNext->m_pPrev = p->m_pPrev; else m_pLast = p->m_pPrev; if(p->m_pPrev) p->m_pPrev->m_pNext = p->m_pNext; else m_pFirst = p->m_pNext; /*CPacket *cur = first; while(cur) { dbg_assert(cur != p, "p still in list"); cur = cur->next; }*/ // send and remove packet //if((rand()%20) != 0) // heavy packetloss net_udp_send(Socket, &p->m_SendTo, p->m_aData, p->m_DataSize); // update lag double Flux = rand()/(double)RAND_MAX; int MsSpike = Ping.m_Spike; int MsFlux = Ping.m_Flux; int MsPing = Ping.m_Base; m_CurrentLatency = ((time_freq()*MsPing)/1000) + (int64)(((time_freq()*MsFlux)/1000)*Flux); // 50ms if(MsSpike && (p->m_ID%100) == 0) { m_CurrentLatency += (time_freq()*MsSpike)/1000; aFlags[1] = 'S'; } if(m_ConfigLog) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&p->m_SendTo, aAddrStr, sizeof(aAddrStr), true); dbg_msg("crapnet", ">> %08d %s (%d) %s", p->m_ID, aAddrStr, p->m_DataSize, aFlags); } mem_free(p); } } thread_sleep(1); } }
bool CSqlScore::Connect() { try { // Create connection m_pDriver = get_driver_instance(); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "tcp://%s:%d", m_pIp, m_Port); m_pConnection = m_pDriver->connect(aBuf, m_pUser, m_pPass); // Create Statement m_pStatement = m_pConnection->createStatement(); // Create database if not exists str_format(aBuf, sizeof(aBuf), "CREATE DATABASE IF NOT EXISTS %s", m_pDatabase); m_pStatement->execute(aBuf); // Connect to specific database m_pConnection->setSchema(m_pDatabase); dbg_msg("SQL", "SQL connection established"); return true; } catch (sql::SQLException &e) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); dbg_msg("SQL", aBuf); dbg_msg("SQL", "ERROR: SQL connection failed"); return false; } catch (const std::exception& ex) { // ... dbg_msg("SQL", "1 %s",ex.what()); } catch (const std::string& ex) { // ... dbg_msg("SQL", "2 %s",ex.c_str()); } catch( int ) { dbg_msg("SQL", "3 %s"); } catch( float ) { dbg_msg("SQL", "4 %s"); } catch( char[] ) { dbg_msg("SQL", "5 %s"); } catch( char ) { dbg_msg("SQL", "6 %s"); } catch (...) { dbg_msg("SQL", "Unknown Error cause by the MySQL/C++ Connector, my advice compile server_debug and use it"); dbg_msg("SQL", "ERROR: SQL connection failed"); return false; } return false; }
bool CGameControllerEXP::OnEntity(int Index, vec2 Pos) { if(IGameController::OnEntity(Index, Pos)) return true; int lvl = 0; if(Index == ENTITY_SPAWN_BOT_LEVEL_1) lvl = 1; else if(Index == ENTITY_SPAWN_BOT_LEVEL_2) lvl = 2; else if(Index == ENTITY_SPAWN_BOT_LEVEL_3) lvl = 3; if(lvl != 0) { dbg_msg("exp", "bot spawn level %d added (%d)", lvl, m_aNumBotSpawns[lvl-1]); m_aaBotSpawns[lvl-1][m_aNumBotSpawns[lvl-1]].m_Pos = Pos; m_aaBotSpawns[lvl-1][m_aNumBotSpawns[lvl-1]].m_Level = lvl; m_aaBotSpawns[lvl-1][m_aNumBotSpawns[lvl-1]].m_Spawned = false; m_aaBotSpawns[lvl-1][m_aNumBotSpawns[lvl-1]].m_RespawnTimer = (float)Server()->Tick() - 5*Server()->Tick(); m_aNumBotSpawns[lvl-1]++; } if(Index == ENTITY_SPAWN_BOSS) { if(m_Boss.m_Exist) dbg_msg("exp", "there can't be 2 boss entities on one map"); else { dbg_msg("exp", "boss added"); m_Boss.m_Exist = true; m_Boss.m_Spawn.m_Pos = Pos; m_Boss.m_Spawn.m_Level = 4; m_Boss.m_Spawn.m_Spawned = false; m_Boss.m_Spawn.m_RespawnTimer = (float)Server()->Tick() - GameServer()->Tuning()->m_RespawnTimer*Server()->Tick(); } } else if(Index == ENTITY_TURRET_LASER) { if(m_CurTurret < MAX_TURRETS) { dbg_msg("exp", "laser turret added (%d)", m_CurTurret); m_aTurrets[m_CurTurret].m_Used = true; m_aTurrets[m_CurTurret].m_Pos = Pos; m_aTurrets[m_CurTurret].m_Type = TURRET_TYPE_LASER; BuildTurret(m_CurTurret++); } else dbg_msg("exp", "can't create laser turret: too many turrets"); return true; } else if(Index == ENTITY_TURRET_GUN) { if(m_CurTurret < MAX_TURRETS) { dbg_msg("exp", "gun turret added (%d)", m_CurTurret); m_aTurrets[m_CurTurret].m_Used = true; m_aTurrets[m_CurTurret].m_Pos = Pos; m_aTurrets[m_CurTurret].m_Type = TURRET_TYPE_GUN; BuildTurret(m_CurTurret++); } else dbg_msg("exp", "can't create gun turret: too many turrets"); return true; } else if(Index == ENTITY_MINE) { if(m_CurMine < MAX_MINES) { dbg_msg("exp", "mine added (%d)", m_CurMine); m_aMines[m_CurMine].m_Used = true; m_aMines[m_CurMine].m_Pos = vec2(Pos.x, Pos.y+14); BuildMine(m_CurMine++); } else dbg_msg("exp", "can't create mine: too many mines"); return true; } else if(Index == ENTITY_TRAP) { if(m_CurTrap < MAX_TRAPS) { dbg_msg("exp", "trap added (%d)", m_CurTrap); m_aTraps[m_CurTrap].m_Used = true; m_aTraps[m_CurTrap].m_Pos = vec2(Pos.x, Pos.y-14); BuildTrap(m_CurTrap++); } else dbg_msg("exp", "can't create trap: too many traps"); return true; } else if(Index == ENTITY_DOOR_VERTICAL) { if(m_CurDoor < MAX_DOORS) { dbg_msg("exp", "vertical door added (%d)", m_CurDoor); m_aDoors[m_CurDoor].m_Used = true; m_aDoors[m_CurDoor].m_Pos = vec2(Pos.x, Pos.y-16); m_aDoors[m_CurDoor].m_Type = DOOR_TYPE_VERTICAL; BuildDoor(m_CurDoor++); } else dbg_msg("exp", "can't create vertical door: too many doors"); return true; } else if(Index == ENTITY_DOOR_HORIZONTAL) { if(m_CurDoor < MAX_DOORS) { dbg_msg("exp", "horizontal door added (%d)", m_CurDoor); m_aDoors[m_CurDoor].m_Used = true; m_aDoors[m_CurDoor].m_Pos = vec2(Pos.x-16, Pos.y); m_aDoors[m_CurDoor].m_Type = DOOR_TYPE_HORIZONTAL; BuildDoor(m_CurDoor++); } else dbg_msg("exp", "can't create horizontal door: too many doors"); return true; } else if(Index == ENTITY_FLAGSTAND_RED) { if(m_CurFlag < MAX_CHECKPOINTS) { dbg_msg("exp", "checkpoint added (%d)", m_CurFlag); CFlag *f = new CFlag(&GameServer()->m_World, 0, Pos); f->m_Pos = Pos; m_aFlagsCP[m_CurFlag++] = f; g_Config.m_SvScorelimit++; } else dbg_msg("exp", "can't create checkpoint: too many checkpoints"); return true; } else if(Index == ENTITY_FLAGSTAND_BLUE) { dbg_msg("exp", "blue flag added"); CFlag *f = new CFlag(&GameServer()->m_World, 1, Pos); f->m_Pos = Pos; m_FlagEnd = f; return true; } return true; }
void CSqlScore::ShowTimesThread(void *pUser) { lock_wait(gs_SqlLock); CSqlScoreData *pData = (CSqlScoreData *)pUser; // Connect to database if(pData->m_pSqlData->Connect()) { try { char originalName[MAX_NAME_LENGTH]; strcpy(originalName,pData->m_aName); pData->m_pSqlData->ClearString(pData->m_aName); char aBuf[512]; if(pData->m_Search) // last 5 times of a player str_format(aBuf, sizeof(aBuf), "SELECT Time, UNIX_TIMESTAMP(CURRENT_TIMESTAMP)-UNIX_TIMESTAMP(Timestamp) as Ago, UNIX_TIMESTAMP(Timestamp) as Stamp FROM %s_%s_race WHERE Name = '%s' ORDER BY Ago ASC LIMIT %d, 5;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aName, pData->m_Num-1); else // last 5 times of server str_format(aBuf, sizeof(aBuf), "SELECT Name, Time, UNIX_TIMESTAMP(CURRENT_TIMESTAMP)-UNIX_TIMESTAMP(Timestamp) as Ago, UNIX_TIMESTAMP(Timestamp) as Stamp FROM %s_%s_race ORDER BY Ago ASC LIMIT %d, 5;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_Num-1); pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); // show top5 if(pData->m_pSqlData->m_pResults->rowsCount() == 0){ pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "There are no times in the specified range"); goto end; } str_format(aBuf, sizeof(aBuf), "------------ Last Times No %d - %d ------------",pData->m_Num,pData->m_Num + pData->m_pSqlData->m_pResults->rowsCount() - 1); pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); float pTime = 0; int pSince = 0; int pStamp = 0; while(pData->m_pSqlData->m_pResults->next()) { char pAgoString[40] = "\0"; pSince = (int)pData->m_pSqlData->m_pResults->getInt("Ago"); pStamp = (int)pData->m_pSqlData->m_pResults->getInt("Stamp"); pTime = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); agoTimeToString(pSince,pAgoString); if(pData->m_Search) // last 5 times of a player { if(pStamp == 0) // stamp is 00:00:00 cause it's an old entry from old times where there where no stamps yet str_format(aBuf, sizeof(aBuf), "%d min %.2f sec, don't know how long ago", (int)(pTime/60), pTime-((int)pTime/60*60)); else str_format(aBuf, sizeof(aBuf), "%s ago, %d min %.2f sec", pAgoString,(int)(pTime/60), pTime-((int)pTime/60*60)); } else // last 5 times of the server { if(pStamp == 0) // stamp is 00:00:00 cause it's an old entry from old times where there where no stamps yet str_format(aBuf, sizeof(aBuf), "%s, %d m %.2f s, don't know when", pData->m_pSqlData->m_pResults->getString("Name").c_str(), (int)(pTime/60), pTime-((int)pTime/60*60)); else str_format(aBuf, sizeof(aBuf), "%s, %s ago, %d m %.2f s", pData->m_pSqlData->m_pResults->getString("Name").c_str(), pAgoString, (int)(pTime/60), pTime-((int)pTime/60*60)); } pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); } pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "----------------------------------------------------"); dbg_msg("SQL", "Showing times done"); // delete results and statement delete pData->m_pSqlData->m_pResults; delete pData->m_pSqlData->m_pStatement; } catch (sql::SQLException &e) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); dbg_msg("SQL", aBuf); dbg_msg("SQL", "ERROR: Could not show times"); } end: // disconnect from database pData->m_pSqlData->Disconnect(); } delete pData; lock_release(gs_SqlLock); }
/** * parse_devtable - parse the device table. * @tbl_file: device table file name * * This function parses the device table and prepare the hash table which will * later be used by mkfs.ubifs to create the specified files/device nodes. * Returns zero in case of success and a negative error code in case of * failure. */ int parse_devtable(const char *tbl_file) { FILE *f; char *line = NULL; struct stat st; size_t len; dbg_msg(1, "parsing device table file '%s'", tbl_file); path_htbl = create_hashtable(128, &r5_hash, &is_equivalent); if (!path_htbl) return err_msg("cannot create path hash table"); f = fopen(tbl_file, "r"); if (!f) return sys_err_msg("cannot open '%s'", tbl_file); if (fstat(fileno(f), &st) < 0) { sys_err_msg("cannot stat '%s'", tbl_file); goto out_close; } if (st.st_size < 10) { sys_err_msg("'%s' is too short", tbl_file); goto out_close; } /* * The general plan now is to read in one line at a time, check for * leading comment delimiters ('#'), then try and parse the line as a * device table */ while (getline(&line, &len, f) != -1) { /* First trim off any white-space */ len = strlen(line); /* Trim trailing white-space */ while (len > 0 && isspace(line[len - 1])) line[--len] = '\0'; /* Trim leading white-space */ memmove(line, &line[strspn(line, " \n\r\t\v")], len); /* How long are we after trimming? */ len = strlen(line); /* If this is not a comment line, try to interpret it */ if (len && *line != '#') { if (interpret_table_entry(line)) { err_msg("cannot parse '%s'", line); goto out_close; } } free(line); line = NULL; } dbg_msg(1, "finished parsing"); fclose(f); return 0; out_close: fclose(f); free_devtable_info(); return -1; }
/** * mount_ubifs - mount UBIFS file-system. * @c: UBIFS file-system description object * * This function mounts UBIFS file system. Returns zero in case of success and * a negative error code in case of failure. * * Note, the function does not de-allocate resources it it fails half way * through, and the caller has to do this instead. */ static int mount_ubifs(struct ubifs_info *c) { struct super_block *sb = c->vfs_sb; int err, mounted_read_only = (sb->s_flags & MS_RDONLY); long long x; size_t sz; err = init_constants_early(c); if (err) return err; err = ubifs_debugging_init(c); if (err) return err; err = check_volume_empty(c); if (err) goto out_free; if (c->empty && (mounted_read_only || c->ro_media)) { /* * This UBI volume is empty, and read-only, or the file system * is mounted read-only - we cannot format it. */ ubifs_err("can't format empty UBI volume: read-only %s", c->ro_media ? "UBI volume" : "mount"); err = -EROFS; goto out_free; } if (c->ro_media && !mounted_read_only) { ubifs_err("cannot mount read-write - read-only media"); err = -EROFS; goto out_free; } /* * The requirement for the buffer is that it should fit indexing B-tree * height amount of integers. We assume the height if the TNC tree will * never exceed 64. */ err = -ENOMEM; c->bottom_up_buf = kmalloc(BOTTOM_UP_HEIGHT * sizeof(int), GFP_KERNEL); if (!c->bottom_up_buf) goto out_free; c->sbuf = vmalloc(c->leb_size); if (!c->sbuf) goto out_free; /* * We have to check all CRCs, even for data nodes, when we mount the FS * (specifically, when we are replaying). */ c->always_chk_crc = 1; err = ubifs_read_superblock(c); if (err) goto out_free; /* * Make sure the compressor which is set as default in the superblock * or overridden by mount options is actually compiled in. */ if (!ubifs_compr_present(c->default_compr)) { ubifs_err("'compressor \"%s\" is not compiled in", ubifs_compr_name(c->default_compr)); goto out_free; } dbg_failure_mode_registration(c); err = init_constants_sb(c); if (err) goto out_free; sz = ALIGN(c->max_idx_node_sz, c->min_io_size); sz = ALIGN(sz + c->max_idx_node_sz, c->min_io_size); c->cbuf = kmalloc(sz, GFP_NOFS); if (!c->cbuf) { err = -ENOMEM; goto out_free; } sprintf(c->bgt_name, BGT_NAME_PATTERN, c->vi.ubi_num, c->vi.vol_id); err = ubifs_read_master(c); if (err) goto out_master; init_constants_master(c); if ((c->mst_node->flags & cpu_to_le32(UBIFS_MST_DIRTY)) != 0) { ubifs_msg("recovery needed"); c->need_recovery = 1; } err = ubifs_lpt_init(c, 1, !mounted_read_only); if (err) goto out_lpt; err = dbg_check_idx_size(c, c->old_idx_sz); if (err) goto out_lpt; err = ubifs_replay_journal(c); if (err) goto out_journal; err = ubifs_mount_orphans(c, c->need_recovery, mounted_read_only); if (err) goto out_orphans; if (c->need_recovery) { err = ubifs_recover_size(c); if (err) goto out_orphans; } spin_lock(&ubifs_infos_lock); list_add_tail(&c->infos_list, &ubifs_infos); spin_unlock(&ubifs_infos_lock); if (c->need_recovery) { if (mounted_read_only) ubifs_msg("recovery deferred"); else { c->need_recovery = 0; ubifs_msg("recovery completed"); } } err = dbg_check_filesystem(c); if (err) goto out_infos; c->always_chk_crc = 0; ubifs_msg("mounted UBI device %d, volume %d, name \"%s\"", c->vi.ubi_num, c->vi.vol_id, c->vi.name); if (mounted_read_only) ubifs_msg("mounted read-only"); x = (long long)c->main_lebs * c->leb_size; ubifs_msg("file system size: %lld bytes (%lld KiB, %lld MiB, %d " "LEBs)", x, x >> 10, x >> 20, c->main_lebs); x = (long long)c->log_lebs * c->leb_size + c->max_bud_bytes; ubifs_msg("journal size: %lld bytes (%lld KiB, %lld MiB, %d " "LEBs)", x, x >> 10, x >> 20, c->log_lebs + c->max_bud_cnt); ubifs_msg("media format: w%d/r%d (latest is w%d/r%d)", c->fmt_version, c->ro_compat_version, UBIFS_FORMAT_VERSION, UBIFS_RO_COMPAT_VERSION); ubifs_msg("default compressor: %s", ubifs_compr_name(c->default_compr)); ubifs_msg("reserved for root: %llu bytes (%llu KiB)", c->report_rp_size, c->report_rp_size >> 10); dbg_msg("compiled on: " __DATE__ " at " __TIME__); dbg_msg("min. I/O unit size: %d bytes", c->min_io_size); dbg_msg("LEB size: %d bytes (%d KiB)", c->leb_size, c->leb_size >> 10); dbg_msg("data journal heads: %d", c->jhead_cnt - NONDATA_JHEADS_CNT); dbg_msg("UUID: %02X%02X%02X%02X-%02X%02X" "-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", c->uuid[0], c->uuid[1], c->uuid[2], c->uuid[3], c->uuid[4], c->uuid[5], c->uuid[6], c->uuid[7], c->uuid[8], c->uuid[9], c->uuid[10], c->uuid[11], c->uuid[12], c->uuid[13], c->uuid[14], c->uuid[15]); dbg_msg("big_lpt %d", c->big_lpt); dbg_msg("log LEBs: %d (%d - %d)", c->log_lebs, UBIFS_LOG_LNUM, c->log_last); dbg_msg("LPT area LEBs: %d (%d - %d)", c->lpt_lebs, c->lpt_first, c->lpt_last); dbg_msg("orphan area LEBs: %d (%d - %d)", c->orph_lebs, c->orph_first, c->orph_last); dbg_msg("main area LEBs: %d (%d - %d)", c->main_lebs, c->main_first, c->leb_cnt - 1); dbg_msg("index LEBs: %d", c->lst.idx_lebs); dbg_msg("total index bytes: %lld (%lld KiB, %lld MiB)", c->old_idx_sz, c->old_idx_sz >> 10, c->old_idx_sz >> 20); dbg_msg("key hash type: %d", c->key_hash_type); dbg_msg("tree fanout: %d", c->fanout); dbg_msg("reserved GC LEB: %d", c->gc_lnum); dbg_msg("first main LEB: %d", c->main_first); dbg_msg("max. znode size %d", c->max_znode_sz); dbg_msg("max. index node size %d", c->max_idx_node_sz); dbg_msg("node sizes: data %zu, inode %zu, dentry %zu", UBIFS_DATA_NODE_SZ, UBIFS_INO_NODE_SZ, UBIFS_DENT_NODE_SZ); dbg_msg("node sizes: trun %zu, sb %zu, master %zu", UBIFS_TRUN_NODE_SZ, UBIFS_SB_NODE_SZ, UBIFS_MST_NODE_SZ); dbg_msg("node sizes: ref %zu, cmt. start %zu, orph %zu", UBIFS_REF_NODE_SZ, UBIFS_CS_NODE_SZ, UBIFS_ORPH_NODE_SZ); dbg_msg("max. node sizes: data %zu, inode %zu dentry %zu", UBIFS_MAX_DATA_NODE_SZ, UBIFS_MAX_INO_NODE_SZ, UBIFS_MAX_DENT_NODE_SZ); dbg_msg("dead watermark: %d", c->dead_wm); dbg_msg("dark watermark: %d", c->dark_wm); dbg_msg("LEB overhead: %d", c->leb_overhead); x = (long long)c->main_lebs * c->dark_wm; dbg_msg("max. dark space: %lld (%lld KiB, %lld MiB)", x, x >> 10, x >> 20); dbg_msg("maximum bud bytes: %lld (%lld KiB, %lld MiB)", c->max_bud_bytes, c->max_bud_bytes >> 10, c->max_bud_bytes >> 20); dbg_msg("BG commit bud bytes: %lld (%lld KiB, %lld MiB)", c->bg_bud_bytes, c->bg_bud_bytes >> 10, c->bg_bud_bytes >> 20); dbg_msg("current bud bytes %lld (%lld KiB, %lld MiB)", c->bud_bytes, c->bud_bytes >> 10, c->bud_bytes >> 20); dbg_msg("max. seq. number: %llu", c->max_sqnum); dbg_msg("commit number: %llu", c->cmt_no); return 0; out_infos: spin_lock(&ubifs_infos_lock); list_del(&c->infos_list); spin_unlock(&ubifs_infos_lock); out_orphans: free_orphans(c); out_journal: out_lpt: ubifs_lpt_free(c, 0); out_master: kfree(c->mst_node); kfree(c->rcvrd_mst_node); if (c->bgt) kthread_stop(c->bgt); kfree(c->cbuf); out_free: vfree(c->ileb_buf); vfree(c->sbuf); kfree(c->bottom_up_buf); ubifs_debugging_exit(c); return err; }
void CRequest::Run() { if(BeforeInit()) { m_State = HTTP_ERROR; return; } CURL *pHandle = curl_easy_init(); if(!pHandle) { m_State = HTTP_ERROR; return; } if(g_Config.m_DbgCurl) { curl_easy_setopt(pHandle, CURLOPT_VERBOSE, 1L); } char aErr[CURL_ERROR_SIZE]; curl_easy_setopt(pHandle, CURLOPT_ERRORBUFFER, aErr); if(m_CanTimeout) { curl_easy_setopt(pHandle, CURLOPT_CONNECTTIMEOUT_MS, (long)g_Config.m_ClHTTPConnectTimeoutMs); curl_easy_setopt(pHandle, CURLOPT_LOW_SPEED_LIMIT, (long)g_Config.m_ClHTTPLowSpeedLimit); curl_easy_setopt(pHandle, CURLOPT_LOW_SPEED_TIME, (long)g_Config.m_ClHTTPLowSpeedTime); } else { curl_easy_setopt(pHandle, CURLOPT_CONNECTTIMEOUT_MS, 0L); curl_easy_setopt(pHandle, CURLOPT_LOW_SPEED_LIMIT, 0L); curl_easy_setopt(pHandle, CURLOPT_LOW_SPEED_TIME, 0L); } curl_easy_setopt(pHandle, CURLOPT_SHARE, gs_Share); curl_easy_setopt(pHandle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); curl_easy_setopt(pHandle, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(pHandle, CURLOPT_MAXREDIRS, 4L); curl_easy_setopt(pHandle, CURLOPT_FAILONERROR, 1L); curl_easy_setopt(pHandle, CURLOPT_URL, m_aUrl); curl_easy_setopt(pHandle, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(pHandle, CURLOPT_USERAGENT, "DDNet " GAME_RELEASE_VERSION " (" CONF_PLATFORM_STRING "; " CONF_ARCH_STRING ")"); // We only trust our own custom-selected CAs for our own servers. // Other servers can use any CA trusted by the system. if(false || str_comp_nocase_num("maps.ddnet.tw/", m_aUrl, 14) == 0 || str_comp_nocase_num("http://maps.ddnet.tw/", m_aUrl, 21) == 0 || str_comp_nocase_num("https://maps.ddnet.tw/", m_aUrl, 22) == 0 || str_comp_nocase_num("http://info.ddnet.tw/", m_aUrl, 21) == 0 || str_comp_nocase_num("https://info.ddnet.tw/", m_aUrl, 22) == 0 || str_comp_nocase_num("https://update4.ddnet.tw/", m_aUrl, 25) == 0) { curl_easy_setopt(pHandle, CURLOPT_CAINFO, CA_FILE_PATH); } curl_easy_setopt(pHandle, CURLOPT_WRITEDATA, this); curl_easy_setopt(pHandle, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(pHandle, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(pHandle, CURLOPT_PROGRESSDATA, this); curl_easy_setopt(pHandle, CURLOPT_PROGRESSFUNCTION, ProgressCallback); if(AfterInit(pHandle)) { curl_easy_cleanup(pHandle); m_State = HTTP_ERROR; return; } dbg_msg("http", "http %s", m_aUrl); m_State = HTTP_RUNNING; int Ret = curl_easy_perform(pHandle); BeforeCompletion(); if(Ret != CURLE_OK) { dbg_msg("http", "task failed. libcurl error: %s", aErr); m_State = (Ret == CURLE_ABORTED_BY_CALLBACK) ? HTTP_ABORTED : HTTP_ERROR; } else { dbg_msg("http", "task done %s", m_aUrl); m_State = HTTP_DONE; } curl_easy_cleanup(pHandle); OnCompletion(); }
/** * ubi_io_read_ec_hdr - read and check an erase counter header. * @ubi: UBI device description object * @pnum: physical eraseblock to read from * @ec_hdr: a &struct ubi_ec_hdr object where to store the read erase counter * header * @verbose: be verbose if the header is corrupted or was not found * * This function reads erase counter header from physical eraseblock @pnum and * stores it in @ec_hdr. This function also checks CRC checksum of the read * erase counter header. The following codes may be returned: * * o %0 if the CRC checksum is correct and the header was successfully read; * o %UBI_IO_BITFLIPS if the CRC is correct, but bit-flips were detected * and corrected by the flash driver; this is harmless but may indicate that * this eraseblock may become bad soon (but may be not); * o %UBI_IO_BAD_EC_HDR if the erase counter header is corrupted (a CRC error); * o %UBI_IO_PEB_EMPTY if the physical eraseblock is empty; * o a negative error code in case of failure. */ int ubi_io_read_ec_hdr(struct ubi_device *ubi, int pnum, struct ubi_ec_hdr *ec_hdr, int verbose) { int err, read_err = 0; uint32_t crc, magic, hdr_crc; dbg_io("read EC header from PEB %d", pnum); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); err = ubi_io_read(ubi, ec_hdr, pnum, 0, UBI_EC_HDR_SIZE); if (err) { if (err != UBI_IO_BITFLIPS && err != -EBADMSG) return err; /* * We read all the data, but either a correctable bit-flip * occurred, or MTD reported about some data integrity error, * like an ECC error in case of NAND. The former is harmless, * the later may mean that the read data is corrupted. But we * have a CRC check-sum and we will detect this. If the EC * header is still OK, we just report this as there was a * bit-flip. */ read_err = err; } magic = be32_to_cpu(ec_hdr->magic); if (magic != UBI_EC_HDR_MAGIC) { /* * The magic field is wrong. Let's check if we have read all * 0xFF. If yes, this physical eraseblock is assumed to be * empty. * * But if there was a read error, we do not test it for all * 0xFFs. Even if it does contain all 0xFFs, this error * indicates that something is still wrong with this physical * eraseblock and we anyway cannot treat it as empty. */ if (read_err != -EBADMSG && check_pattern(ec_hdr, 0xFF, UBI_EC_HDR_SIZE)) { /* The physical eraseblock is supposedly empty */ /* * The below is just a paranoid check, it has to be * compiled out if paranoid checks are disabled. */ err = paranoid_check_all_ff(ubi, pnum, 0, ubi->peb_size); if (err) return err > 0 ? UBI_IO_BAD_EC_HDR : err; if (verbose) ubi_warn("no EC header found at PEB %d, " "only 0xFF bytes", pnum); else if (UBI_IO_DEBUG) dbg_msg("no EC header found at PEB %d, " "only 0xFF bytes", pnum); return UBI_IO_PEB_EMPTY; } /* * This is not a valid erase counter header, and these are not * 0xFF bytes. Report that the header is corrupted. */ if (verbose) { ubi_warn("bad magic number at PEB %d: %08x instead of " "%08x", pnum, magic, UBI_EC_HDR_MAGIC); ubi_dbg_dump_ec_hdr(ec_hdr); } else if (UBI_IO_DEBUG) dbg_msg("bad magic number at PEB %d: %08x instead of " "%08x", pnum, magic, UBI_EC_HDR_MAGIC); return UBI_IO_BAD_EC_HDR; } crc = crc32(UBI_CRC32_INIT, ec_hdr, UBI_EC_HDR_SIZE_CRC); hdr_crc = be32_to_cpu(ec_hdr->hdr_crc); if (hdr_crc != crc) { if (verbose) { ubi_warn("bad EC header CRC at PEB %d, calculated " "%#08x, read %#08x", pnum, crc, hdr_crc); ubi_dbg_dump_ec_hdr(ec_hdr); } else if (UBI_IO_DEBUG) dbg_msg("bad EC header CRC at PEB %d, calculated " "%#08x, read %#08x", pnum, crc, hdr_crc); return UBI_IO_BAD_EC_HDR; } /* And of course validate what has just been read from the media */ err = validate_ec_hdr(ubi, ec_hdr); if (err) { ubi_err("validation failed for PEB %d", pnum); return -EINVAL; } return read_err ? UBI_IO_BITFLIPS : 0; }
void CCharacter::TickDefered() { // advance the dummy { CWorldCore TempWorld; m_ReckoningCore.Init(&TempWorld, GameServer()->Collision()); m_ReckoningCore.Tick(false); m_ReckoningCore.Move(); m_ReckoningCore.Quantize(); } //lastsentcore vec2 StartPos = m_Core.m_Pos; vec2 StartVel = m_Core.m_Vel; bool StuckBefore = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); m_Core.Move(); bool StuckAfterMove = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); m_Core.Quantize(); bool StuckAfterQuant = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); m_Pos = m_Core.m_Pos; if(!StuckBefore && (StuckAfterMove || StuckAfterQuant)) { dbg_msg("char_core", "STUCK!!! %d %d %d %f %f %f %f %x %x %x %x", StuckBefore, StuckAfterMove, StuckAfterQuant, StartPos.x, StartPos.y, StartVel.x, StartVel.y, *((unsigned *)&StartPos.x), *((unsigned *)&StartPos.y), *((unsigned *)&StartVel.x), *((unsigned *)&StartVel.y)); } int Events = m_Core.m_TriggeredEvents; int Mask = CmaskAllExceptOne(m_pPlayer->GetCID()); if(Events&COREEVENT_GROUND_JUMP) GameServer()->CreateSound(m_Pos, SOUND_PLAYER_JUMP, Mask); if(Events&COREEVENT_HOOK_ATTACH_PLAYER) GameServer()->CreateSound(m_Pos, SOUND_HOOK_ATTACH_PLAYER, CmaskAll()); if(Events&COREEVENT_HOOK_ATTACH_GROUND) GameServer()->CreateSound(m_Pos, SOUND_HOOK_ATTACH_GROUND, Mask); if(Events&COREEVENT_HOOK_HIT_NOHOOK) GameServer()->CreateSound(m_Pos, SOUND_HOOK_NOATTACH, Mask); if(m_pPlayer->GetTeam() == -1) { m_Pos.x = m_Input.m_TargetX; m_Pos.y = m_Input.m_TargetY; } // update the m_SendCore if needed { CNetObj_Character Predicted; CNetObj_Character Current; mem_zero(&Predicted, sizeof(Predicted)); mem_zero(&Current, sizeof(Current)); m_ReckoningCore.Write(&Predicted); m_Core.Write(&Current); // only allow dead reackoning for a top of 3 seconds if(m_ReckoningTick+Server()->TickSpeed()*3 < Server()->Tick() || mem_comp(&Predicted, &Current, sizeof(CNetObj_Character)) != 0) { m_ReckoningTick = Server()->Tick(); m_SendCore = m_Core; m_ReckoningCore = m_Core; } } }
/** * ubi_io_read_vid_hdr - read and check a volume identifier header. * @ubi: UBI device description object * @pnum: physical eraseblock number to read from * @vid_hdr: &struct ubi_vid_hdr object where to store the read volume * identifier header * @verbose: be verbose if the header is corrupted or wasn't found * * This function reads the volume identifier header from physical eraseblock * @pnum and stores it in @vid_hdr. It also checks CRC checksum of the read * volume identifier header. The following codes may be returned: * * o %0 if the CRC checksum is correct and the header was successfully read; * o %UBI_IO_BITFLIPS if the CRC is correct, but bit-flips were detected * and corrected by the flash driver; this is harmless but may indicate that * this eraseblock may become bad soon; * o %UBI_IO_BAD_VID_HRD if the volume identifier header is corrupted (a CRC * error detected); * o %UBI_IO_PEB_FREE if the physical eraseblock is free (i.e., there is no VID * header there); * o a negative error code in case of failure. */ int ubi_io_read_vid_hdr(struct ubi_device *ubi, int pnum, struct ubi_vid_hdr *vid_hdr, int verbose) { int err, read_err = 0; uint32_t crc, magic, hdr_crc; void *p; dbg_io("read VID header from PEB %d", pnum); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); p = (char *)vid_hdr - ubi->vid_hdr_shift; err = ubi_io_read(ubi, p, pnum, ubi->vid_hdr_aloffset, ubi->vid_hdr_alsize); if (err) { if (err != UBI_IO_BITFLIPS && err != -EBADMSG) return err; /* * We read all the data, but either a correctable bit-flip * occurred, or MTD reported about some data integrity error, * like an ECC error in case of NAND. The former is harmless, * the later may mean the read data is corrupted. But we have a * CRC check-sum and we will identify this. If the VID header is * still OK, we just report this as there was a bit-flip. */ read_err = err; } magic = be32_to_cpu(vid_hdr->magic); if (magic != UBI_VID_HDR_MAGIC) { /* * If we have read all 0xFF bytes, the VID header probably does * not exist and the physical eraseblock is assumed to be free. * * But if there was a read error, we do not test the data for * 0xFFs. Even if it does contain all 0xFFs, this error * indicates that something is still wrong with this physical * eraseblock and it cannot be regarded as free. */ if (read_err != -EBADMSG && check_pattern(vid_hdr, 0xFF, UBI_VID_HDR_SIZE)) { /* The physical eraseblock is supposedly free */ /* * The below is just a paranoid check, it has to be * compiled out if paranoid checks are disabled. */ err = paranoid_check_all_ff(ubi, pnum, ubi->leb_start, ubi->leb_size); if (err) return err > 0 ? UBI_IO_BAD_VID_HDR : err; if (verbose) ubi_warn("no VID header found at PEB %d, " "only 0xFF bytes", pnum); else if (UBI_IO_DEBUG) dbg_msg("no VID header found at PEB %d, " "only 0xFF bytes", pnum); return UBI_IO_PEB_FREE; } /* * This is not a valid VID header, and these are not 0xFF * bytes. Report that the header is corrupted. */ if (verbose) { ubi_warn("bad magic number at PEB %d: %08x instead of " "%08x", pnum, magic, UBI_VID_HDR_MAGIC); ubi_dbg_dump_vid_hdr(vid_hdr); } else if (UBI_IO_DEBUG) dbg_msg("bad magic number at PEB %d: %08x instead of " "%08x", pnum, magic, UBI_VID_HDR_MAGIC); return UBI_IO_BAD_VID_HDR; } crc = crc32(UBI_CRC32_INIT, vid_hdr, UBI_VID_HDR_SIZE_CRC); hdr_crc = be32_to_cpu(vid_hdr->hdr_crc); if (hdr_crc != crc) { if (verbose) { ubi_warn("bad CRC at PEB %d, calculated %#08x, " "read %#08x", pnum, crc, hdr_crc); ubi_dbg_dump_vid_hdr(vid_hdr); } else if (UBI_IO_DEBUG) dbg_msg("bad CRC at PEB %d, calculated %#08x, " "read %#08x", pnum, crc, hdr_crc); return UBI_IO_BAD_VID_HDR; } /* Validate the VID header that we have just read */ err = validate_vid_hdr(ubi, vid_hdr); if (err) { ubi_err("validation failed for PEB %d", pnum); return -EINVAL; } return read_err ? UBI_IO_BITFLIPS : 0; }
int snd_load_wv(const char *filename) { SAMPLE *snd; int sid = -1; char error[100]; WavpackContext *context; /* don't waste memory on sound when we are stress testing */ if(config.dbg_stress) return -1; /* no need to load sound when we are running with no sound */ if(!sound_enabled) return 1; file = engine_openfile(filename, IOFLAG_READ); /* TODO: use system.h stuff for this */ if(!file) { dbg_msg("sound/wv", "failed to open %s", filename); return -1; } sid = snd_alloc_id(); if(sid < 0) return -1; snd = &samples[sid]; context = WavpackOpenFileInput(read_data, error); if (context) { int samples = WavpackGetNumSamples(context); int bitspersample = WavpackGetBitsPerSample(context); unsigned int samplerate = WavpackGetSampleRate(context); int channels = WavpackGetNumChannels(context); int *data; int *src; short *dst; int i; snd->channels = channels; snd->rate = samplerate; if(snd->channels > 2) { dbg_msg("sound/wv", "file is not mono or stereo. filename='%s'", filename); return -1; } /* if(snd->rate != 44100) { dbg_msg("sound/wv", "file is %d Hz, not 44100 Hz. filename='%s'", snd->rate, filename); return -1; }*/ if(bitspersample != 16) { dbg_msg("sound/wv", "bps is %d, not 16, filname='%s'", bitspersample, filename); return -1; } data = (int *)mem_alloc(4*samples*channels, 1); WavpackUnpackSamples(context, data, samples); /* TODO: check return value */ src = data; snd->data = (short *)mem_alloc(2*samples*channels, 1); dst = snd->data; for (i = 0; i < samples*channels; i++) *dst++ = (short)*src++; mem_free(data); snd->num_frames = samples; snd->loop_start = -1; snd->loop_end = -1; } else { dbg_msg("sound/wv", "failed to open %s: %s", filename, error); } io_close(file); file = NULL; if(config.debug) dbg_msg("sound/wv", "loaded %s", filename); rate_convert(sid); return sid; }
unsigned CHttpDownloader::GetFileSize(const char *url, unsigned timeOut) { NETSOCKET sock; NETADDR nadd, bindAddr; mem_zero(&nadd, sizeof(nadd)); mem_zero(&bindAddr, sizeof(bindAddr)); bindAddr.type = NETTYPE_IPV4; NETURL NetUrl = CreateUrl(url); if (net_host_lookup(NetUrl.m_aHost, &nadd, NETTYPE_IPV4) != 0) { dbg_msg("HttpDownloader", "Error can't found '%s'...", NetUrl.m_aHost); return false; } nadd.port = 80; sock = net_tcp_create(bindAddr); net_socket_rcv_timeout(sock, timeOut); if (net_tcp_connect(sock, &nadd) != 0) { dbg_msg("HttpDownloader", "Error can't connect with '%s'...", NetUrl.m_aHost); net_tcp_close(sock); return false; } char aBuff[512] = {0}; str_format(aBuff, sizeof(aBuff), "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", NetUrl.m_aSlug, NetUrl.m_aHost); net_tcp_send(sock, aBuff, str_length(aBuff)); std::string NetData; int TotalBytes = 0; int CurrentRecv = 0; int nlCount = 0; char aNetBuff[1024] = {0}; do { CurrentRecv = net_tcp_recv(sock, aNetBuff, sizeof(aNetBuff)); for (int i=0; i<CurrentRecv ; i++) { if (nlCount < 2) { if (aNetBuff[i] == '\r' || aNetBuff[i] == '\n') { ++nlCount; if (NetData.size() > 0) { std::transform(NetData.begin(), NetData.end(), NetData.begin(), ::tolower); if (NetData.find("404 not found") != std::string::npos) { dbg_msg("HttpDownloader", "ERROR 404: '%s' not found...", NetUrl.m_aFile); net_tcp_close(sock); return false; } else if (NetData.find("content-length:") != std::string::npos) { char aFileSize[64]; str_copy(aFileSize, NetData.substr(15).c_str(), sizeof(aFileSize)); str_trim(aFileSize); TotalBytes = atoi(aFileSize); if (TotalBytes <= 0) { dbg_msg("HttpDownloader", "Error getting size of '%s'...", NetUrl.m_aFile); net_tcp_close(sock); return 0; } net_tcp_close(sock); return TotalBytes; } NetData.clear(); } if (aNetBuff[i] == '\r') ++i; continue; } nlCount = 0; NetData += aNetBuff[i]; } else { dbg_msg("HttpDownloader", "Error getting size of '%s'...", NetUrl.m_aFile); net_tcp_close(sock); return 0; } } } while (CurrentRecv > 0); return 0; }
int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr) { int64 Now = time_get(); // check if resend is requested if(pPacket->m_Flags&NET_PACKETFLAG_RESEND) Resend(); // if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL) { int CtrlMsg = pPacket->m_aChunkData[0]; if(CtrlMsg == NET_CTRLMSG_CLOSE) { if(net_addr_comp(&m_PeerAddr, pAddr) == 0) { m_State = NET_CONNSTATE_ERROR; m_RemoteClosed = 1; char Str[128] = {0}; if(pPacket->m_DataSize > 1) { // make sure to sanitize the error string form the other party if(pPacket->m_DataSize < 128) str_copy(Str, (char *)&pPacket->m_aChunkData[1], pPacket->m_DataSize); else str_copy(Str, (char *)&pPacket->m_aChunkData[1], sizeof(Str)); str_sanitize_strong(Str); } if(!m_BlockCloseMsg) { // set the error string SetError(Str); } if(g_Config.m_Debug) dbg_msg("conn", "closed reason='%s'", Str); } return 0; } else { if(State() == NET_CONNSTATE_OFFLINE) { if(CtrlMsg == NET_CTRLMSG_CONNECT) { // send response and init connection Reset(); m_State = NET_CONNSTATE_PENDING; m_PeerAddr = *pAddr; mem_zero(m_ErrorString, sizeof(m_ErrorString)); m_LastSendTime = Now; m_LastRecvTime = Now; m_LastUpdateTime = Now; SendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0); if(g_Config.m_Debug) dbg_msg("connection", "got connection, sending connect+accept"); } } else if(State() == NET_CONNSTATE_CONNECT) { // connection made if(CtrlMsg == NET_CTRLMSG_CONNECTACCEPT) { m_LastRecvTime = Now; SendControl(NET_CTRLMSG_ACCEPT, 0, 0); m_State = NET_CONNSTATE_ONLINE; if(g_Config.m_Debug) dbg_msg("connection", "got connect+accept, sending accept. connection online"); } } } } else { if(State() == NET_CONNSTATE_PENDING) { m_LastRecvTime = Now; m_State = NET_CONNSTATE_ONLINE; if(g_Config.m_Debug) dbg_msg("connection", "connecting online"); } } if(State() == NET_CONNSTATE_ONLINE) { m_LastRecvTime = Now; AckChunks(pPacket->m_Ack); } return 1; }
bool CHttpDownloader::GetToFile(const char *url, const char *dest, unsigned timeOut, unsigned downloadSpeed) { if (!dest || dest[0] == 0) return false; int64 downloadTime = time_get(); unsigned chunkBytes = 0; NETSOCKET sock; NETADDR nadd, bindAddr; mem_zero(&nadd, sizeof(nadd)); mem_zero(&bindAddr, sizeof(bindAddr)); bindAddr.type = NETTYPE_IPV4; NETURL NetUrl = CreateUrl(url); if (net_host_lookup(NetUrl.m_aHost, &nadd, NETTYPE_IPV4) != 0) { dbg_msg("HttpDownloader", "Error can't found '%s'...", NetUrl.m_aHost); return false; } nadd.port = 80; sock = net_tcp_create(bindAddr); if (net_tcp_connect(sock, &nadd) != 0) { dbg_msg("HttpDownloader", "Error can't connect with '%s'...", NetUrl.m_aHost); net_tcp_close(sock); return false; } net_socket_rcv_timeout(sock, timeOut); char aBuff[512] = {0}; str_format(aBuff, sizeof(aBuff), "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", NetUrl.m_aSlug, NetUrl.m_aHost); net_tcp_send(sock, aBuff, str_length(aBuff)); std::string NetData; unsigned TotalRecv = 0; unsigned TotalBytes = 0; int CurrentRecv = 0; unsigned nlCount = 0; char aNetBuff[1024] = {0}; IOHANDLE dstFile = NULL; do { // Limit Speed if (downloadSpeed > 0) { int64 ctime = time_get(); if (ctime - downloadTime <= time_freq()) { if (chunkBytes >= downloadSpeed) { int tdff = (time_freq() - (ctime - downloadTime)) / 1000; thread_sleep(tdff); continue; } } else { chunkBytes = 0; downloadTime = time_get(); } } // CurrentRecv = net_tcp_recv(sock, aNetBuff, sizeof(aNetBuff)); chunkBytes += CurrentRecv; for (int i=0; i<CurrentRecv ; i++) { if (nlCount < 2) { if (aNetBuff[i] == '\r' || aNetBuff[i] == '\n') { ++nlCount; if (NetData.size() > 0) { std::transform(NetData.begin(), NetData.end(), NetData.begin(), ::tolower); if (NetData.find("404 not found") != std::string::npos) { dbg_msg("HttpDownloader", "ERROR 404: '%s' not found...", NetUrl.m_aFile); net_tcp_close(sock); return false; } else if (NetData.find("content-length:") != std::string::npos) { char aFileSize[64]; str_copy(aFileSize, NetData.substr(15).c_str(), sizeof(aFileSize)); str_trim(aFileSize); TotalBytes = atoi(aFileSize); } NetData.clear(); } if (aNetBuff[i] == '\r') ++i; continue; } nlCount = 0; NetData += aNetBuff[i]; } else { if (nlCount == 2) { if (TotalBytes <= 0) { dbg_msg("HttpDownloader", "Error downloading '%s'...", NetUrl.m_aFile); net_tcp_close(sock); return false; } dstFile = io_open(dest, IOFLAG_WRITE); if(!dstFile) { dbg_msg("HttpDownloader", "Error creating '%s'...", dest); net_tcp_close(sock); return false; } ++nlCount; } io_write(dstFile, &aNetBuff[i], 1); TotalRecv++; if (TotalRecv == TotalBytes) break; } } } while (CurrentRecv > 0); net_tcp_close(sock); if (TotalRecv > 0) { io_close(dstFile); return true; } return false; }
/** * ubi_io_read - read data from a physical eraseblock. * @ubi: UBI device description object * @buf: buffer where to store the read data * @pnum: physical eraseblock number to read from * @offset: offset within the physical eraseblock from where to read * @len: how many bytes to read * * This function reads data from offset @offset of physical eraseblock @pnum * and stores the read data in the @buf buffer. The following return codes are * possible: * * o %0 if all the requested data were successfully read; * o %UBI_IO_BITFLIPS if all the requested data were successfully read, but * correctable bit-flips were detected; this is harmless but may indicate * that this eraseblock may become bad soon (but do not have to); * o %-EBADMSG if the MTD subsystem reported about data integrity problems, for * example it can be an ECC error in case of NAND; this most probably means * that the data is corrupted; * o %-EIO if some I/O error occurred; * o other negative error codes in case of other errors. */ int ubi_io_read(const struct ubi_device *ubi, void *buf, int pnum, int offset, int len) { int err, retries = 0; size_t read; loff_t addr; dbg_io("read %d bytes from PEB %d:%d", len, pnum, offset); ubi_assert(pnum >= 0 && pnum < ubi->peb_count); ubi_assert(offset >= 0 && offset + len <= ubi->peb_size); ubi_assert(len > 0); err = paranoid_check_not_bad(ubi, pnum); if (err) return err > 0 ? -EINVAL : err; addr = (loff_t)pnum * ubi->peb_size + offset; retry: err = ubi->mtd->read(ubi->mtd, addr, len, &read, buf); if (err == -EUCLEAN) err = 0; //added by Elvis, for ignore EUCLEAN if (err) { if (err == -EUCLEAN) { /* * -EUCLEAN is reported if there was a bit-flip which * was corrected, so this is harmless. */ ubi_msg("fixable bit-flip detected at PEB %d", pnum); ubi_assert(len == read); return UBI_IO_BITFLIPS; } if (read != len && retries++ < UBI_IO_RETRIES) { dbg_io("error %d while reading %d bytes from PEB %d:%d, " "read only %zd bytes, retry", err, len, pnum, offset, read); yield(); goto retry; } ubi_err("error %d while reading %d bytes from PEB %d:%d, " "read %zd bytes", err, len, pnum, offset, read); ubi_dbg_dump_stack(); /* * The driver should never return -EBADMSG if it failed to read * all the requested data. But some buggy drivers might do * this, so we change it to -EIO. */ if (read != len && err == -EBADMSG) { ubi_assert(0); printk("%s[%d] not here\n", __func__, __LINE__); /* err = -EIO; */ } } else { ubi_assert(len == read); if (ubi_dbg_is_bitflip()) { dbg_msg("bit-flip (emulated)"); err = UBI_IO_BITFLIPS; } } return err; }
void GAMECONTROLLER::tick() { // do info message every 10 minutes if(server_tick()%(50*10*60) == 0) { game.send_chat_target(-1, "-------------------------"); game.send_chat_target(-1, "Buy Mod - 0.1"); game.send_chat_target(-1, "by ©Bobynator and ©KaiTee"); game.send_chat_target(-1, "/cmdlist - see all commands"); game.send_chat_target(-1, "/info - see aim of the game"); game.send_chat_target(-1, "-------------------------"); } // inactivity check if(!game.world.paused) for(int i = 0; i < MAX_CLIENTS; i++) if(game.players[i]) if(server_tick()%server_tickspeed() == 0 && game.players[i]->last_input != -1 && server_tick() - game.players[i]->last_input >= 120 * server_tickspeed()) if(server_tick() - game.players[i]->last_input >= 120 * server_tickspeed()) { game.players[i]->set_team(-1); // set him to spectator game.send_chat_target(i, "Inactivity Check: Are you still there?"); //portal ftw ;D } // event stuff // TODO: write event over stuff smarter! if(slow_tick > 0) slow_tick--; if(slow_tick == 0) { console_execute_line("tune_reset"); slow_tick = -1; game.send_broadcast("EVENT OVER!", -1); } if(speed_tick > 0) speed_tick--; if(speed_tick == 0) { console_execute_line("tune_reset"); speed_tick = -1; game.send_broadcast("EVENT OVER!", -1); } if(x2_tick > 0) x2_tick--; if(x2_tick == 0) { x2_tick = -1; game.send_broadcast("EVENT OVER!", -1); } if(one_hit_tick > 0) one_hit_tick--; if(one_hit_tick == 0) { one_hit_tick = -1; game.send_broadcast("EVENT OVER!", -1); } if(web_tick > 0) web_tick--; if(web_tick == 0) { web_tick = -1; game.send_broadcast("EVENT OVER!", -1); } if(server_tick()%(50*60*60) == 0 && !is_cup) { int Event = 1+(rand()%(5-1+1)); if(Event == 1) slowmotion(5); else if(Event == 2) x2(2); else if(Event == 3) one_hit(1); else if(Event == 4) speedmotion(3); else if(Event == 5) spider_web(4); } // do warmup if(warmup) { warmup--; if(!warmup) startround(); } // do potcount int enter_players = 0; if(is_cup) for(int i = 0; i < MAX_CLIENTS; i++) if(game.players[i]) { if(game.players[i]->enter_game == true) enter_players++; } if(potcount < 1 && is_cup && game_over_tick == -1) { if(server_tick()%(50*6) == 0 && enter_players > 1 && jackpot > 0) { char buf[512]; str_format(buf, sizeof(buf), "Jackpot: %d $", jackpot); game.send_broadcast(buf, -1, true); } if(enter_players == 1) { endround(); } } if(potcount > 0 && is_cup) { potcount--; char buf[512]; str_format(buf, sizeof(buf), "Jackpot: %d $ | Join-Time: %d", jackpot, potcount/50); for(int i = 0; i < MAX_CLIENTS; i++) { if(game.players[i]) { if(game.players[i]->broadcast_count < 1) game.send_broadcast(buf, i, true); } } } if(potcount == 0 && is_cup) { if(enter_players >= 2) { game.send_broadcast("Game Start!", -1); resetgame(); potcount--; char buf[512]; str_format(buf, sizeof(buf), "sv_scorelimit %d", enter_players*5); console_execute_line(buf); // start game round_start_tick = server_tick(); sudden_death = 0; game_over_tick = -1; game.world.paused = false; teamscore[0] = 0; teamscore[1] = 0; unbalanced_tick = -1; force_balanced = false; } else do_potcount(16); } if(game_over_tick != -1) { // game over.. wait for restart if(server_tick() > game_over_tick+server_tickspeed()*10) { cyclemap(); startround(); round_count++; } } // do team-balancing if (is_teamplay() && unbalanced_tick != -1 && server_tick() > unbalanced_tick+config.sv_teambalance_time*server_tickspeed()*60) { dbg_msg("game", "Balancing teams"); int t[2] = {0,0}; int tscore[2] = {0,0}; for(int i = 0; i < MAX_CLIENTS; i++) { if(game.players[i] && game.players[i]->team != -1) { t[game.players[i]->team]++; tscore[game.players[i]->team]+=game.players[i]->score; } } // are teams unbalanced? if(abs(t[0]-t[1]) >= 2) { int m = (t[0] > t[1]) ? 0 : 1; int num_balance = abs(t[0]-t[1]) / 2; do { PLAYER *p = 0; int pd = tscore[m]; for(int i = 0; i < MAX_CLIENTS; i++) { if(!game.players[i]) continue; // remember the player who would cause lowest score-difference if(game.players[i]->team == m && (!p || abs((tscore[m^1]+game.players[i]->score) - (tscore[m]-game.players[i]->score)) < pd)) { p = game.players[i]; pd = abs((tscore[m^1]+p->score) - (tscore[m]-p->score)); } } // move the player to other team without losing his score // TODO: change in player::set_team needed: player won't lose score on team-change int score_before = p->score; p->set_team(m^1); p->score = score_before; p->respawn(); p->force_balanced = true; } while (--num_balance); force_balanced = true; } unbalanced_tick = -1; } // update browse info int prog = -1; if(config.sv_timelimit > 0) prog = max(prog, (server_tick()-round_start_tick) * 100 / (config.sv_timelimit*server_tickspeed()*60)); if(config.sv_scorelimit) { if(is_teamplay()) { prog = max(prog, (teamscore[0]*100)/config.sv_scorelimit); prog = max(prog, (teamscore[1]*100)/config.sv_scorelimit); } else { for(int i = 0; i < MAX_CLIENTS; i++) { if(game.players[i]) prog = max(prog, (game.players[i]->score*100)/config.sv_scorelimit); } } } if(warmup) prog = -1; server_setbrowseinfo(gametype, prog); }