Ejemplo n.º 1
1
Archivo: log.cpp Proyecto: Fred50/acr
bool initlogging(const char *identity, int facility_, int consolethres, int filethres, int syslogthres, bool logtimestamp)
{
    facility = facility_ & 7;
    timestamp = logtimestamp;
    if(consolethres >= 0) consolethreshold = min(consolethres, (int)ACLOG_NUM);
    if(filethres >= 0) filethreshold = min(filethres, (int)ACLOG_NUM);
    if(syslogthres >= 0) syslogthreshold = min(syslogthres, (int)ACLOG_NUM);
    if(ident != identity)
        copystring(ident, identity);
    formatstring(ident_full)("ACR[%s]", identity);
    if(syslogthreshold < ACLOG_NUM)
    {
#ifdef AC_USE_SYSLOG
        openlog(ident_full, LOG_NDELAY, facilities[facility]);
#else
        if((logsock = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM)) == ENET_SOCKET_NULL || enet_address_set_host(&logdest, "localhost") < 0) syslogthreshold = ACLOG_NUM;
#endif
    }
    static int lognum = 0;
    formatstring(filepath)("serverlog_%s_%s.part%d.txt", timestring(true), identity, ++lognum);
    if(fp) { fclose(fp); fp = NULL; }
    if(filethreshold < ACLOG_NUM)
    {
        fp = fopen(filepath, "w");
        if(!fp) printf("failed to open \"%s\" for writing\n", filepath);
    }
    defformatstring(msg)("logging started: console(%s), file(%s", levelname[consolethreshold], levelname[fp ? filethreshold : ACLOG_NUM]);
    if(fp) concatformatstring(msg, ", \"%s\"", filepath);
    concatformatstring(msg, "), syslog(%s", levelname[syslogthreshold]);
    if(syslogthreshold < ACLOG_NUM) concatformatstring(msg, ", \"%s\", local%d", ident_full, facility);
    concatformatstring(msg, "), timestamp(%s)", timestamp ? "ENABLED" : "DISABLED");
    enabled = consolethreshold < ACLOG_NUM || fp || syslogthreshold < ACLOG_NUM;
    if(enabled) printf("%s\n", msg);
    return enabled;
}
Ejemplo n.º 2
0
    void export_ents(const char *fname) {
        string tmp;
        copystring(tmp, curr_map_id);
        tmp[strlen(curr_map_id) - 7] = '\0';

        defformatstring(buf)("%smedia%c%s%c%s", homedir, PATHDIV, tmp,
            PATHDIV, fname);

        lua::push_external("entities_save_all");
        lua_call(lua::L, 0, 1);
        const char *data = lua_tostring(lua::L, -1);
        lua_pop(lua::L, 1);
        if (fileexists(buf, "r")) {
            defformatstring(buff)("%s-%d.bak", buf, (int)time(0));
            tools::fcopy(buf, buff);
        }

        FILE *f = fopen(buf, "w");
        if  (!f) {
            logger::log(logger::ERROR, "Cannot open file %s for writing.\n",
                buf);
            return;
        }
        fputs(data, f);
        fclose(f);
    }
Ejemplo n.º 3
0
 void renderent(entity &e)
 {
     /* FIXME: if the item list change, this hack will be messed */

     defformatstring(widn)("modmdlpickup%d", e.type-3);
     defformatstring(mdlname)("pickups/%s", identexists(widn)?getalias(widn):

     entmdlnames[e.type-I_CLIPS+(m_lss(gamemode, mutators) && e.type==I_GRENADE ? 5:0)]);

     float z = (float)(1+sinf(lastmillis/100.0f+e.x+e.y)/20), yaw = lastmillis/10.0f;
     rendermodel(mdlname, ANIM_MAPMODEL|(e.spawned ? 0 : ANIM_TRANSLUCENT)|ANIM_LOOP|ANIM_DYNALLOC, 0, 0, vec(e.x, e.y, z+S(e.x, e.y)->floor+e.attr1), yaw, 0);
 }
Ejemplo n.º 4
0
Archivo: log.cpp Proyecto: R2ZER0/selp
bool logline(int level, const char *msg, ...)
{
    if(!enabled) return false;
    if(level < 0 || level >= ACLOG_NUM) return false;
    defvformatstring(sf, msg, msg);
    filtertext(sf, sf, 2);
    const char *ts = timestamp ? timestring(true, "%b %d %H:%M:%S ") : "", *ld = levelprefix[level];
    char *p, *l = sf;
    do
    { // break into single lines first
        if((p = strchr(l, '\n'))) *p = '\0';
        if(consolethreshold <= level) printf("%s%s%s\n", ts, ld, l);
        if(fp && filethreshold <= level) fprintf(fp, "%s%s%s\n", ts, ld, l);
        if(syslogthreshold <= level)
#ifdef AC_USE_SYSLOG
            syslog(levels[level], "%s", l);
#else
        {
            defformatstring(text)("<%d>%s: %s", (16 + facility) * 8 + levels[level], ident, l); // no TIMESTAMP, no hostname: syslog will add this
            ENetBuffer buf;
            buf.data = text;
            buf.dataLength = strlen(text);
            enet_socket_send(logsock, &logdest, &buf, 1);
        }
#endif
        l = p + 1;
    }
    while(p);
    if(consolethreshold <= level) fflush(stdout);
    if(fp && filethreshold <= level) fflush(fp);
    return consolethreshold <= level;
}
Ejemplo n.º 5
0
void audiomanager::musicpreload(int id)
{
    if(nosound) return;
    stopsound();
    if(musicvol && (id>=M_FLAGGRAB && id<=M_LASTMINUTE2))
    {
        char *name = musics[id];
        conoutf("preloading music #%d : %s", id, name);
        if(gamemusic->open(name))
        {
            defformatstring(whendone)("musicvol %d", musicvol);
            musicdonecmd = newstring(whendone);
            //conoutf("when done: %s", musicdonecmd);
            const int preloadfadetime = 3;
            gamemusic->fadein(lastmillis, preloadfadetime);
            gamemusic->fadeout(lastmillis+2*preloadfadetime, preloadfadetime);
            if(!gamemusic->playback(false))
            {
                conoutf("could not play music: %s", name);
                return;
            }
            setmusicvol(1); // not 0 !
        }
        else conoutf("could not open music: %s", name);
    }
    else setmusicvol(musicvol); // call "musicpreload -1" to ensure musicdonecmd runs - but it should w/o that
}
Ejemplo n.º 6
0
void fatal(const char *s, ...)    // failure exit
{
    if(++errors <= 2) // print up to one extra recursive error
    {
        defvformatbigstring(msg, s, s);
        if(logfile) logoutf("%s", msg);
        #ifndef WIN32
        fprintf(stderr, "%s\n", msg);
        #endif
        if(errors <= 1) // avoid recursion
        {
            if(SDL_WasInit(SDL_INIT_VIDEO))
            {
                showcursor(true);
                SDL_WM_GrabInput(SDL_GRAB_OFF);
                cleargamma();
            }
            #ifdef WIN32
            defformatstring(cap, "%s: Error", VERSION_NAME);
            MessageBox(NULL, msg, cap, MB_OK|MB_SYSTEMMODAL);
            #endif
            SDL_Quit();
        }
    }
    exit(EXIT_FAILURE);
}
    void ControlNPC::connect(DynamicEntity* de)
    {
        if(!de) fatal("Controler::Character : no valid Dynamic Entity. Exit!");
        dynent = de;

///TODO: set name ActionInstance
		defformatstring(s)("%p", this);
        copystring(dynent->name, s);

///TODO: set and send basic infos like name, model ...

//        filtertext(dynent->name, lib.librarydescr, false, MAXNAMELEN);
        game::addmsg(SV_SWITCHNAME, "rs", dynent->name);

        dynent->controltype = CONTROL_NPC;
        dynent->lastupdate = lastmillis;

///TODO: spawn behaviour in edit and normal mode
        //first spawn, no actions defined in Actionlib
//        if(editmode)
//        {
            dynent->o = vec(game::player1->o);
            droptofloor(dynent->o, 0, 0);
            vec sp = vec(0,0,0);
            vecfromyawpitch(game::player1->yaw, 0, 50, 0, sp);
            dynent->o.add(sp);
            dynent->o.z += dynent->eyeheight;

            game::addmsg(SV_TRYSPAWN, "rc", dynent);
//        }
		Instance::init();
        isinit = true;
    }
Ejemplo n.º 8
0
 void listquests(bool completed, g3d_gui &g)
 {
     for(rpgquest *q = quests; q; q = q->next) if(q->completed==completed)
     {
         defformatstring(info)("%s: %s", q->npc, q->questline);
         g.text(info, 0xAAAAAA, "info");
     }
 }
Ejemplo n.º 9
0
 bool is_ready() {
     defformatstring(path, "%s%s", homedir, SERVER_READYFILE);
     if (fileexists(path, "r")) {
         tools::fdel(path);
         return true;
     }
     else return false;
 }
Ejemplo n.º 10
0
void setcaption(const char *text)
{
    static string caption = "";
    defformatstring(newcaption)("%s v%s-%s %d bit (%s)%s%s", versionname, versionstring, CUR_PLATFORM, CUR_ARCH, versionrelease, text ? ": " : "", text ? text : "");
    if(strcmp(caption, newcaption))
    {
        copystring(caption, newcaption);
        SDL_WM_SetCaption(caption, NULL);
    }
}
Ejemplo n.º 11
0
    void trigger_received_entity() {
        num_received_entities++;

        if (num_expected_entities > 0) {
            float val = clamp(float(num_received_entities) / float(num_expected_entities), 0.0f, 1.0f);
            if (loading) {
                defformatstring(buf)("received entity %d ...", num_received_entities);
                renderprogress(val, buf);
            }
        }
    }
Ejemplo n.º 12
0
bool listdir(const char *dir, const char *ext, vector<char *> &files)
{
    int extsize = ext ? (int)strlen(ext)+1 : 0;
    #if defined(WIN32)
    defformatstring(pathname)("%s\\*.%s", dir, ext ? ext : "*");
    WIN32_FIND_DATA FindFileData;
    HANDLE Find = FindFirstFile(path(pathname), &FindFileData);
    if(Find != INVALID_HANDLE_VALUE)
    {
        do {
            if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
                files.add(newstring(FindFileData.cFileName, (int)strlen(FindFileData.cFileName) - extsize));
        } while(FindNextFile(Find, &FindFileData));
        FindClose(Find);
        return true;
    }
    #else
    string pathname;
    copystring(pathname, dir);
    DIR *d = opendir(path(pathname));
    if(d)
    {
        struct dirent *de, b;
        while(!readdir_r(d, &b, &de) && de != NULL)
        {
            bool isreg = false;
        #ifdef _DIRENT_HAVE_D_TYPE
            if(de->d_type == DT_REG) isreg = true;
            else if(de->d_type == DT_UNKNOWN)
        #endif
            {
                struct stat s;
                int dl = (int)strlen(pathname);
                concatformatstring(pathname, "/%s", de->d_name);
                isreg = !lstat(pathname, &s) && S_ISREG(s.st_mode);
                pathname[dl] = '\0';
            }
            if(isreg)
            {
                if(!ext) files.add(newstring(de->d_name));
                else
                {
                    int namelength = (int)strlen(de->d_name) - extsize;
                    if(namelength > 0 && de->d_name[namelength] == '.' && strncmp(de->d_name+namelength+1, ext, extsize-1)==0)
                        files.add(newstring(de->d_name, namelength));
                }
            }
        }
        closedir(d);
        return true;
    }
    #endif
    else return false;
}
Ejemplo n.º 13
0
void setcaption(const char *text, const char *text2)
{
    static string prevtext = "", prevtext2 = "";
    if(strcmp(text, prevtext) || strcmp(text2, prevtext2))
    {
        copystring(prevtext, text);
        copystring(prevtext2, text2);
        defformatstring(caption)("%s v%s-%s%d (%s)%s%s%s%s", versionname, versionstring, versionplatname, versionarch, versionrelease, text[0] ? ": " : "", text, text2[0] ? " - " : "", text2);
        SDL_WM_SetCaption(caption, NULL);
    }
}
Ejemplo n.º 14
0
void mapcfgname()
{
    const char *mname = game::getclientmap();
    if(!*mname) mname = "untitled";

    string pakname, mapname, mcfgname;
    getmapfilenames(mname, NULL, pakname, mapname, mcfgname);
    defformatstring(cfgname)("packages/%s/%s.cfg", pakname, mcfgname);
    path(cfgname);
    result(cfgname);
}
Ejemplo n.º 15
0
void mapcfgname()
{
    const char *mname = game::getclientmap();
    if(!*mname) mname = "untitled";

    string pakname, mapname, mcfgname;
    getmapfilenames(mname, NULL, pakname, mapname, mcfgname);
    defformatstring(cfgname)("packages/%s/%s.js", pakname, mcfgname); // INTENSITY: Switched to .js TODO: More files
    path(cfgname);
    result(cfgname);
}
Ejemplo n.º 16
0
void setcaption(const char *text, const char *text2)
{
    static string prevtext = "", prevtext2 = "";
    if(strcmp(text, prevtext) || strcmp(text2, prevtext2))
    {
        copystring(prevtext, text);
        copystring(prevtext2, text2);
        defformatstring(caption, "%s v%s-%s%d [%s] (%s)%s%s%s%s", VERSION_NAME, VERSION_STRING, versionplatname, versionarch, versionbranch, VERSION_RELEASE, text[0] ? ": " : "", text, text2[0] ? " - " : "", text2);
        SDL_WM_SetCaption(caption, NULL);
    }
}
Ejemplo n.º 17
0
    void run(const char *map) {
        if (started) {
            conoutf("Stopping old server instance ..");
            stop();
        }
        conoutf("Starting server, please wait ..");
#ifndef WIN32
        if (!fork()) {
            const char *a0 = "bin_unix/server_" BINARY_OS_STR "_"
                BINARY_ARCH_STR;

            defformatstring(a1, "-g%s", logger::names[logger::current_level]);
            defformatstring(a2, "-l%s", server_log_file);
            defformatstring(a3, "-mmap/%s.tar.gz", map);

            execl(a0, a0, a1, a2, a3, "-shutdown-if-idle",
                "-shutdown-if-empty", (char*)NULL);
            exit(0);
        }
#else
#ifdef WIN64
        const char *exe = "bin_win64\\server_" BINARY_OS_STR "_"
            BINARY_ARCH_STR ".exe";
#else
        const char *exe = "bin_win32\\server_" BINARY_OS_STR "_"
            BINARY_ARCH_STR ".exe";
#endif
        char buf[4096];
        char *cptr = buf;

        defformatstring(a1, "-g%s", logger::names[logger::current_level]);
        defformatstring(a2, "-l%s", server_log_file);
        defformatstring(a3, "-mmap/%s.tar.gz", map);
        const char a4[] = "-shutdown-if-idle";
        const char a5[] = "-shutdown-if-empty";

        size_t len = strlen(a1);
        memcpy(cptr, a1, len); cptr += len; *(cptr++) = ' ';
        len = strlen(a2);
        memcpy(cptr, a2, len); cptr += len; *(cptr++) = ' ';
        len = strlen(a3);
        memcpy(cptr, a3, len); cptr += len; *(cptr++) = ' ';
        len = sizeof(a4) - 1;
        memcpy(cptr, a4, len); cptr += len; *(cptr++) = ' ';
        len = sizeof(a5) - 1;
        memcpy(cptr, a5, len); cptr += len; *cptr = '\0';

        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        ZeroMemory(&si, sizeof(pi));

        CreateProcess(exe, buf, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
#endif

        started = true;
    }
Ejemplo n.º 18
0
void loadcaustics(bool force)
{
    static bool needcaustics = false;
    if(force) needcaustics = true;
    if(!caustics || !needcaustics) return;
    useshaderbyname("caustics");
    if(caustictex[0]) return;
    loopi(NUMCAUSTICS)
    {
        defformatstring(name, "<grey><noswizzle>media/texture/mat_water/caustic/caust%.2d.png", i);
        caustictex[i] = textureload(name);
    }
}
Ejemplo n.º 19
0
void listfilesrecursive(const char *dir, vector<char *> &files, int level)
{
    if(level > 8) return; // 8 levels is insane enough...
    vector<char *> dirs, thisdir;
    listsubdirs(dir, dirs, stringsort);
    loopv(dirs)
    {
        if(dirs[i][0] != '.')  // ignore "." and ".." (and also other directories starting with '.', like it is unix-convention - and doesn't hurt on windows)
        {
            defformatstring(name)("%s/%s", dir, dirs[i]);
            listfilesrecursive(name, files, level + 1);
        }
        delstring(dirs[i]);
    }
    listfiles(dir, NULL, thisdir);
    loopv(thisdir)
    {
        defformatstring(name)("%s/%s", dir, thisdir[i]);
        files.add(newstring(name));
        delstring(thisdir[i]);
    }
}
Ejemplo n.º 20
0
	void trigger_event(std::string eventname, std::string args[], size_t num_args)
	{
		for(std::multimap<std::string, char *>::iterator it = event_dict.begin();it != event_dict.end();++it)
		{
			if(it->first == eventname)
			{
				for(size_t i = 0;i < num_args;++i)
				{
					std::string arg = args[i];

					// fixme: hack
					defformatstring(hack)("arg%d = \"%s\"", i, args[i].c_str());
					executeret(hack);
				}

				defformatstring(hack2)("args = %d", num_args);
				executeret(hack2);

				executeret(it->second);
			}
		}
	}
Ejemplo n.º 21
0
    const char *get_mapfile_path(const char *rpath) {
        string aloc;
        copystring(aloc, curr_map_id);
        aloc[strlen(curr_map_id) - 7] = '\0';

        defformatstring(buf)("media%c%s%c%s", PATHDIV, aloc, PATHDIV, rpath);
        formatstring(mapfile_path)("%s%s", homedir, buf);

        if (fileexists(mapfile_path, "r")) {
            return mapfile_path;
        }
        copystring(mapfile_path, buf);
        return mapfile_path;
    }
Ejemplo n.º 22
0
void item::init(const char *base, bool world)
{
	if(world) rpgscript::config->setref( (rpgitem *) this, true);
	else rpgscript::config->setref(this, true);

	this->base = game::queryhashpool(base);
	game::loadingitem = this;

	defformatstring(file, "%s/%s.cfg", game::datapath("items"), base);
	rpgexecfile(file);

	game::loadingitem = NULL;
	game::loadinguse = NULL;

	rpgscript::config->setnull(true);
}
Ejemplo n.º 23
0
char *makerelpath(const char *dir, const char *file, const char *prefix, const char *cmd)
{
    static string tmp;
    if(prefix) copystring(tmp, prefix);
    else tmp[0] = '\0';
    if(file[0]=='<')
    {
        const char *end = strrchr(file, '>');
        if(end)
        {
            size_t len = strlen(tmp);
            copystring(&tmp[len], file, min(sizeof(tmp)-len, size_t(end+2-file)));
            file = end+1;
        }
    }
    if(cmd) concatstring(tmp, cmd);
    defformatstring(pname)("%s/%s", dir, file);
    concatstring(tmp, pname);
    return tmp;
}
Ejemplo n.º 24
0
bool listsubdir(const char *dir, vector<char *> &subdirs)
{
    #if defined(WIN32)
    defformatstring(pathname)("%s\\*", dir);
    WIN32_FIND_DATA FindFileData;
    HANDLE Find = FindFirstFile(path(pathname), &FindFileData);
    if(Find != INVALID_HANDLE_VALUE)
    {
        do {
            if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && FindFileData.cFileName[0] != '.') subdirs.add(newstring(FindFileData.cFileName));
        } while(FindNextFile(Find, &FindFileData));
        FindClose(Find);
        return true;
    }
    #else
    string pathname;
    copystring(pathname, dir);
    DIR *d = opendir(path(pathname));
    if(d)
    {
        struct dirent *de, b;
        while(!readdir_r(d, &b, &de) && de != NULL)
        {
        #ifdef _DIRENT_HAVE_D_TYPE
            if(de->d_type == DT_DIR && de->d_name[0] != '.') subdirs.add(newstring(de->d_name));
            else if(de->d_type == DT_UNKNOWN && de->d_name[0] != '.')
        #endif
            {
                struct stat s;
                int dl = (int)strlen(pathname);
                concatformatstring(pathname, "/%s", de->d_name);
                if(!lstat(pathname, &s) && S_ISDIR(s.st_mode) && de->d_name[0] != '.') subdirs.add(newstring(de->d_name));
                pathname[dl] = '\0';
            }
        }
        closedir(d);
        return true;
    }
    #endif
    else return false;
}
Ejemplo n.º 25
0
char *getfiledesc(const char *dir, const char *name, const char *ext)
{
    if(!browsefiledesc || !dir || !name || !ext) return NULL;
    defformatstring(fn)("%s/%s.%s", dir, name, ext);
    path(fn);
    string text;
    if(!strcmp(ext, "dmo"))
    {
        stream *f = opengzfile(fn, "rb");
        if(!f) return NULL;
        demoheader hdr;
        if(f->read(&hdr, sizeof(demoheader))!=sizeof(demoheader) || memcmp(hdr.magic, DEMO_MAGIC, sizeof(hdr.magic))) { delete f; return NULL; }
        delete f;
        lilswap(&hdr.version, 1);
        lilswap(&hdr.protocol, 1);
        const char *tag = "(incompatible file) ";
        if(hdr.version == DEMO_VERSION)
        {
            if(hdr.protocol == PROTOCOL_VERSION) tag = "";
            else if(hdr.protocol == -PROTOCOL_VERSION) tag = "(recorded on modded server) ";
        }
        formatstring(text)("%s%s", tag, hdr.desc);
        text[DHDR_DESCCHARS - 1] = '\0';
        return newstring(text);
    }
    else if(!strcmp(ext, "cgz"))
    {
        stream *f = opengzfile(fn, "rb");
        if(!f) return NULL;
        header hdr;
        if(f->read(&hdr, sizeof(header))!=sizeof(header) || (strncmp(hdr.head, "CUBE", 4) && strncmp(hdr.head, "ACMP",4) && strncmp(hdr.head, "ACRM",4))) { delete f; return NULL; }
        delete f;
        lilswap(&hdr.version, 1);
        // hdr.maprevision, hdr.maptitle ... hdr.version, hdr.headersize,
        formatstring(text)("%s%s", (hdr.version>MAPVERSION) ? "(incompatible file) " : "", hdr.maptitle);
        text[DHDR_DESCCHARS - 1] = '\0';
        return newstring(text);
    }
    return NULL;
}
Ejemplo n.º 26
0
 mitemmaploadmanual(gmenu *parent, const char *filename, const char *altfontname, char *text, char *action, char *hoveraction, color *bgcolor, const char *desc = NULL) : mitemmanual(parent, text, action, NULL,        NULL,    NULL), filename(filename)
 {
     image = NULL;
     copystring(maptitle, filename ? filename : "-n/a-");
     if(filename)
     {
         // see worldio.cpp:setnames()
         string pakname, mapname, cgzpath;
         const char *slash = strpbrk(filename, "/\\");
         if(slash)
         {
             copystring(pakname, filename, slash-filename+1);
             copystring(mapname, slash+1);
         }
         else
         {
             copystring(pakname, "maps");
             copystring(mapname, filename);
         }
         formatstring(cgzpath)("packages/%s", pakname);
         char *d = getfiledesc(cgzpath, mapname, "cgz");
         if( d ) { formatstring(maptitle)("%s", d[0] ? d : "-n/a-"); }
         else
         {
             copystring(pakname, "maps/official");
             formatstring(cgzpath)("packages/%s", pakname);
             char *d = getfiledesc("packages/maps/official", mapname, "cgz");
             if( d ) { formatstring(maptitle)("%s", d[0] ? d : "-n/a-"); }
             else formatstring(maptitle)("-n/a-:%s", mapname);
         }
         defformatstring(p2p)("%s/preview/%s.jpg", cgzpath, mapname);
         silent_texture_load = true;
         image = textureload(p2p, 3);
         if(image==notexture) image = textureload("packages/misc/nopreview.jpg", 3);
         silent_texture_load = false;
     }
     else { formatstring(maptitle)("-n/a-:%s", filename); image = textureload("packages/misc/nopreview.png", 3); }
     copystring(mapstats, "");
 }
Ejemplo n.º 27
0
bool listdir(const char *dir, const char *ext, vector<char *> &files)
{
    int extsize = ext ? (int)strlen(ext)+1 : 0;
    #if defined(WIN32)
    defformatstring(pathname)("%s\\*.%s", dir, ext ? ext : "*");
    WIN32_FIND_DATA FindFileData;
    HANDLE Find = FindFirstFile(path(pathname), &FindFileData);
    if(Find != INVALID_HANDLE_VALUE)
    {
        do {
            files.add(newstring(FindFileData.cFileName, (int)strlen(FindFileData.cFileName) - extsize));
        } while(FindNextFile(Find, &FindFileData));
        FindClose(Find);
        return true;
    }
    #else
    string pathname;
    copystring(pathname, dir);
    DIR *d = opendir(path(pathname));
    if(d)
    {
        struct dirent *de;
        while((de = readdir(d)) != NULL)
        {
            if(!ext) files.add(newstring(de->d_name));
            else
            {
                int namelength = (int)strlen(de->d_name) - extsize;
                if(namelength > 0 && de->d_name[namelength] == '.' && strncmp(de->d_name+namelength+1, ext, extsize-1)==0)
                    files.add(newstring(de->d_name, namelength));
            }
        }
        closedir(d);
        return true;
    }
    #endif
    else return false;
}
Ejemplo n.º 28
0
static PyObject *sendEditMap(PyObject *self, PyObject *args)
{
	int cn;
	uchar *data;
	int len;
	server::clientinfo *ci;
	if(!PyArg_ParseTuple(args, "is#", &cn, &data, &len))
		return 0;
	ci = server::getinfo(cn);
	if(!ci)
	{
		PyErr_SetString(PyExc_ValueError, "Invalid cn specified");
		return 0;
	}
	if(ci->state.aitype != AI_NONE)
	{
		PyErr_SetString(PyExc_ValueError, "Cannot send map to AI client");
		return 0;
	}

	//uchar *data;

	//memcpy (data,cdata,len);

	//char *tempfilename;
	defformatstring(tempfilename)("sendmap_%d", lastmillis);

	stream *datafile = opentempfile(tempfilename, "w+b");
    if(!datafile) { sendf(cn, 1, "ris", N_SERVMSG, "failed to open temporary file when preparing to send"); return Py_None; }
    datafile->write(data, len);

	sendfile(cn, 2, datafile, "ri", N_SENDMAP);

	if(datafile) DELETEP(datafile);
	return Py_None;
}
Ejemplo n.º 29
0
/// Basic and really simplistic routine to fix malformatted .json files
/// It will replace the old version of your file on success and create a backup of the old one (called <filename>_backup.json)
/// Currently it fixes: double commata, missing " for non-numeric strings
int JSON_Fix(const char *filename)
{
    string s;
    copystring(s, filename);
    const char *found = findfile(path(s), "");
    char *buf = loadfile(found, NULL);
    if(!buf) return -1;
    JSON_Minify(buf);

    size_t len = strlen(buf);

    char *newbuf = new char[len + 1];

    size_t pos = 0; //current position in the newbuf
    for(size_t i = 0; i < len; i++)
    {
        if(buf[i] == ',')
        {
                if(!i) i++;                     //buf starts with a commata
                else if(buf[i + 1] == ',') i++; //two subsequent commata
                else
                {
                    newbuf[pos] = buf[i];
                    pos++;
                }
        }
        else if(isalpha(buf[i]))
        {
            if(!i) //todo worst case: is it an array or object?
                return 0;
            else if(buf[i - 1] != '\"') {
                newbuf[pos] = '\"'; pos++;
            } //string was missing a leading "
            newbuf[pos] = buf[i];
            pos++;
        }
        else
        {
            if(i && isalpha(i - 1)) {
                newbuf[pos] = '\"'; pos++;
            } //string was missing a trailing "
            newbuf[pos] = buf[i];
            pos++;
        }
    }

    JSON *j = JSON_Parse(newbuf);
    if(j)
    {
        conoutf("%s was malformatted but has been fixed automatically. \nThe original file has been overwritten, but backuped", found);
        //cutextension .. getextension
        defformatstring(backupname, "%s_backup", found);
        if(!rename(found, backupname)) j->save(found);
        delete j;
        delete[] buf;
        delete[] newbuf;
        return 1;
    }

    delete[] buf;
    delete[] newbuf;
    return 0;
}
Ejemplo n.º 30
0
/// Internal: Render the number nicely from the given item into a string.
static char *print_number(JSON *item)
{
	defformatstring(val, "%g", item->valuefloat);
	return newstring(val);
}