static AFile* NewAFile (IFile* IF, FILE* F) /* Create a new AFile, push it onto the stack, add the path of the file to * the path search list, and finally return a pointer to the new AFile struct. */ { StrBuf Path = AUTO_STRBUF_INITIALIZER; /* Allocate a AFile structure */ AFile* AF = (AFile*) xmalloc (sizeof (AFile)); /* Initialize the fields */ AF->Line = 0; AF->F = F; AF->Input = IF; /* Increment the usage counter of the corresponding IFile. If this * is the first use, set the file data and output debug info if * requested. */ if (IF->Usage++ == 0) { /* Get file size and modification time. There a race condition here, * since we cannot use fileno() (non standard identifier in standard * header file), and therefore not fstat. When using stat with the * file name, there's a risk that the file was deleted and recreated * while it was open. Since mtime and size are only used to check * if a file has changed in the debugger, we will ignore this problem * here. */ struct stat Buf; if (FileStat (IF->Name, &Buf) != 0) { /* Error */ Fatal ("Cannot stat `%s': %s", IF->Name, strerror (errno)); } IF->Size = (unsigned long) Buf.st_size; IF->MTime = (unsigned long) Buf.st_mtime; /* Set the debug data */ g_fileinfo (IF->Name, IF->Size, IF->MTime); } /* Insert the new structure into the AFile collection */ CollAppend (&AFiles, AF); /* Get the path of this file and add it as an extra search path. * To avoid file search overhead, we will add one path only once. * This is checked by the PushSearchPath function. */ SB_CopyBuf (&Path, IF->Name, FindName (IF->Name) - IF->Name); SB_Terminate (&Path); AF->SearchPath = PushSearchPath (UsrIncSearchPath, SB_GetConstBuf (&Path)); SB_Done (&Path); /* Return the new struct */ return AF; }
/* test if a file exists and is a regular file * AppInputTest tests if a file exists and is a regular file * (e.g. not a directory) * If not an error message is printed. * returns * 0 if file is OK, 1 if an error message is printed. */ int AppInputTest( const char *inputFile) /* the input file */ { /* Check input file */ switch(FileStat(inputFile)) { case 1: Error("input file '%s' is not a (regular) file",inputFile); return 1; case 2: Error("input file '%s' does not exist",inputFile); return 1; } return 0; }
char * MakeKaraokeFile(void) { char buff[500],*pt; int id=0,ln; sprintf(buff,"%-s/Music/",getenv("HOME")); ln = strlen(buff); pt = buff+ln; while(1) { sprintf(pt,"Karaoke_%-4.4d.mp3",id); // printf("%s\n",buff); if (!FileStat(buff)) break; id++; } ln = strlen(buff); pt = (char *)malloc(ln+1); strcpy(pt,buff); return pt; }
static int CloneOption( const char *name) { ATTRIBUTES a; if (FileStat(name) != 2) { return RetError(1,"file '%s' exists, give new (non-existing) name",name); } if (DefaultCloneAttr(&a)) return 1; a.cloneCreation = TRUE; switch(MakeCloneMenu(&a, name)) { case 0: return 1; case 1: return CreateMap(name, &a); case 2: fprintf(stderr,"No map created\n"); return 0; } POSTCOND(FALSE); return 1; }
FileSourceZip::FileSourceZip(const std::string &zipPath) : FileSource(zipPath), m_archive(0) { mz_zip_archive *zip = reinterpret_cast<mz_zip_archive*>(std::calloc(1, sizeof(mz_zip_archive))); if (!mz_zip_reader_init_file(zip, zipPath.c_str(), 0)) { printf("FileSourceZip: unable to open '%s'\n", zipPath.c_str()); std::free(zip); return; } mz_zip_archive_file_stat zipStat; Uint32 numFiles = mz_zip_reader_get_num_files(zip); for (Uint32 i = 0; i < numFiles; i++) { if (mz_zip_reader_file_stat(zip, i, &zipStat)) { bool is_dir = mz_zip_reader_is_file_a_directory(zip, i); if (!mz_zip_reader_is_file_encrypted(zip, i)) AddFile(zipStat.m_filename, FileStat(i, zipStat.m_uncomp_size, MakeFileInfo(zipStat.m_filename, is_dir ? FileInfo::FT_DIR : FileInfo::FT_FILE))); } } m_archive = reinterpret_cast<void*>(zip); }
static int SetOption( const char **names, int nrNames, const ATTRIBUTES *opt) { ATTRIBUTES a; MAP **maps; int i; if (DefaultCloneAttr(&a)) return 1; if (FileStat(names[0]) == 2) { /* non-existing */ MergeOptAttr(&a, opt); if (nrNames > 1) return RetError(1,"-s: only one new map or multiple existing maps allowed"); if (a.nrRows == MV_UINT4 || a.nrCols == MV_UINT4) return RetError(1,"-s: -R and/or -C not specified"); return CreateMap(names[0], &a); } else { /* set all */ if (opt->nrRows != MV_UINT4 || opt->nrCols != MV_UINT4) return RetError(1,"-s: can not change number of rows or columns of an existing map"); if (opt->valueScale != VS_UNDEFINED) return RetError(1,"-s: can not change data type of an existing map"); maps = OpenCopyOrSetMaps(&a,FALSE,names,nrNames); if (maps == NULL) return 1; for(i=0; i < nrNames; i++) SetAndCloseMap(maps[i], opt); Free(maps); return 0; } }
static abyss_bool ServerDefaultHandlerFunc(TSession * const sessionP) { struct _TServer * const srvP = ConnServer(sessionP->conn)->srvP; char *p; char z[4096]; TFileStat fs; unsigned int i; abyss_bool endingslash=FALSE; if (!RequestValidURIPath(sessionP)) { ResponseStatus(sessionP, 400); return TRUE; } /* Must check for * (asterisk uri) in the future */ if (sessionP->request_info.method == m_options) { ResponseAddField(sessionP, "Allow", "GET, HEAD"); ResponseContentLength(sessionP, 0); ResponseStatus(sessionP, 200); return TRUE; } if ((sessionP->request_info.method != m_get) && (sessionP->request_info.method != m_head)) { ResponseAddField(sessionP, "Allow", "GET, HEAD"); ResponseStatus(sessionP, 405); return TRUE; } strcpy(z, srvP->filespath); strcat(z, sessionP->request_info.uri); p = z + strlen(z) - 1; if (*p == '/') { endingslash = TRUE; *p = '\0'; } #ifdef WIN32 p = z; while (*p) { if ((*p) == '/') *p= '\\'; ++p; } #endif /* WIN32 */ if (!FileStat(z, &fs)) { ResponseStatusErrno(sessionP); return TRUE; } if (fs.st_mode & S_IFDIR) { /* Redirect to the same directory but with the ending slash ** to avoid problems with some browsers (IE for examples) when ** they generate relative urls */ if (!endingslash) { strcpy(z, sessionP->request_info.uri); p = z+strlen(z); *p = '/'; *(p+1) = '\0'; ResponseAddField(sessionP, "Location", z); ResponseStatus(sessionP, 302); ResponseWrite(sessionP); return TRUE; } *p = DIRECTORY_SEPARATOR[0]; ++p; i = srvP->defaultfilenames.size; while (i-- > 0) { *p = '\0'; strcat(z, (srvP->defaultfilenames.item[i])); if (FileStat(z, &fs)) { if (!(fs.st_mode & S_IFDIR)) return ServerFileHandler(sessionP, z, fs.st_mtime, srvP->mimeTypeP); } } *(p-1) = '\0'; if (!FileStat(z, &fs)) { ResponseStatusErrno(sessionP); return TRUE; } return ServerDirectoryHandler(sessionP, z, fs.st_mtime, srvP->mimeTypeP); } else return ServerFileHandler(sessionP, z, fs.st_mtime, srvP->mimeTypeP); }
abyss_bool ConfReadServerFile(const char * const filename, TServer * const serverP) { struct _TServer * const srvP = serverP->srvP; BIHandler * const handlerP = srvP->builtinHandlerP; TFile * fileP; char z[512]; char * p; unsigned int lineNum; TFileStat fs; if (!FileOpen(&fileP, filename, O_RDONLY)) return FALSE; lineNum = 0; while (ConfReadLine(fileP, z, 512)) { ++lineNum; p = z; if (ConfNextToken(&p)) { const char * const option = ConfGetToken(&p); if (option) { ConfNextToken(&p); if (xmlrpc_strcaseeq(option, "port")) { int32_t n; if (ConfReadInt(p, &n, 1, 65535)) srvP->port = n; else TraceExit("Invalid port '%s'", p); } else if (xmlrpc_strcaseeq(option, "serverroot")) { bool success; chdirx(p, &success); if (!success) TraceExit("Invalid server root '%s'",p); } else if (xmlrpc_strcaseeq(option, "path")) { if (FileStat(p, &fs)) if (fs.st_mode & S_IFDIR) { HandlerSetFilesPath(handlerP, p); continue; } TraceExit("Invalid path '%s'", p); } else if (xmlrpc_strcaseeq(option, "default")) { const char * filename; while ((filename = ConfGetToken(&p))) { HandlerAddDefaultFN(handlerP, filename); if (!ConfNextToken(&p)) break; } } else if (xmlrpc_strcaseeq(option, "keepalive")) { int32_t n; if (ConfReadInt(p, &n, 1, 65535)) srvP->keepalivemaxconn = n; else TraceExit("Invalid KeepAlive value '%s'", p); } else if (xmlrpc_strcaseeq(option, "timeout")) { int32_t n; if (ConfReadInt(p, &n, 1, 3600)) { srvP->keepalivetimeout = n; /* Must see what to do with that */ srvP->timeout = n; } else TraceExit("Invalid TimeOut value '%s'", p); } else if (xmlrpc_strcaseeq(option, "mimetypes")) { MIMEType * mimeTypeP; readMIMETypesFile(p, &mimeTypeP); if (!mimeTypeP) TraceExit("Can't read MIME Types file '%s'", p); else HandlerSetMimeType(handlerP, mimeTypeP); } else if (xmlrpc_strcaseeq(option,"logfile")) { srvP->logfilename = strdup(p); } else if (xmlrpc_strcaseeq(option,"user")) { parseUser(p, srvP); } else if (xmlrpc_strcaseeq(option, "pidfile")) { parsePidfile(p, srvP); } else if (xmlrpc_strcaseeq(option, "advertiseserver")) { if (!ConfReadBool(p, &srvP->advertise)) TraceExit("Invalid boolean value " "for AdvertiseServer option"); } else TraceExit("Invalid option '%s' at line %u", option, lineNum); } } } FileClose(fileP); return TRUE; }
int NewInputFile (const char* Name) /* Open a new input file. Returns true if the file could be successfully opened ** and false otherwise. */ { int RetCode = 0; /* Return code. Assume an error. */ char* PathName = 0; FILE* F; struct stat Buf; StrBuf NameBuf; /* No need to initialize */ StrBuf Path = AUTO_STRBUF_INITIALIZER; unsigned FileIdx; CharSource* S; /* If this is the main file, just try to open it. If it's an include file, ** search for it using the include path list. */ if (FCount == 0) { /* Main file */ F = fopen (Name, "r"); if (F == 0) { Fatal ("Cannot open input file '%s': %s", Name, strerror (errno)); } } else { /* We are on include level. Search for the file in the include ** directories. */ PathName = SearchFile (IncSearchPath, Name); if (PathName == 0 || (F = fopen (PathName, "r")) == 0) { /* Not found or cannot open, print an error and bail out */ Error ("Cannot open include file '%s': %s", Name, strerror (errno)); goto ExitPoint; } /* Use the path name from now on */ Name = PathName; } /* Stat the file and remember the values. There's a race condition here, ** since we cannot use fileno() (non-standard identifier in standard ** header file), and therefore not fstat. When using stat with the ** file name, there's a risk that the file was deleted and recreated ** while it was open. Since mtime and size are only used to check ** if a file has changed in the debugger, we will ignore this problem ** here. */ if (FileStat (Name, &Buf) != 0) { Fatal ("Cannot stat input file '%s': %s", Name, strerror (errno)); } /* Add the file to the input file table and remember the index */ FileIdx = AddFile (SB_InitFromString (&NameBuf, Name), (FCount == 0)? FT_MAIN : FT_INCLUDE, Buf.st_size, (unsigned long) Buf.st_mtime); /* Create a new input source variable and initialize it */ S = xmalloc (sizeof (*S)); S->Func = &IFFunc; S->V.File.F = F; S->V.File.Pos.Line = 0; S->V.File.Pos.Col = 0; S->V.File.Pos.Name = FileIdx; SB_Init (&S->V.File.Line); /* Push the path for this file onto the include search lists */ SB_CopyBuf (&Path, Name, FindName (Name) - Name); SB_Terminate (&Path); S->V.File.IncSearchPath = PushSearchPath (IncSearchPath, SB_GetConstBuf (&Path)); S->V.File.BinSearchPath = PushSearchPath (BinSearchPath, SB_GetConstBuf (&Path)); SB_Done (&Path); /* Count active input files */ ++FCount; /* Use this input source */ UseCharSource (S); /* File successfully opened */ RetCode = 1; ExitPoint: /* Free an allocated name buffer */ xfree (PathName); /* Return the success code */ return RetCode; }
void ObjAdd (const char* Name) /* Add an object file to the library */ { struct stat StatBuf; const char* Module; ObjHeader H; ObjData* O; /* Open the object file */ FILE* Obj = fopen (Name, "rb"); if (Obj == 0) { Error ("Could not open `%s': %s", Name, strerror (errno)); } /* Get the modification time of the object file. There a race condition * here, since we cannot use fileno() (non standard identifier in standard * header file), and therefore not fstat. When using stat with the * file name, there's a risk that the file was deleted and recreated * while it was open. Since mtime and size are only used to check * if a file has changed in the debugger, we will ignore this problem * here. */ if (FileStat (Name, &StatBuf) != 0) { Error ("Cannot stat object file `%s': %s", Name, strerror (errno)); } /* Read and check the header */ ObjReadHeader (Obj, &H, Name); /* Make a module name from the file name */ Module = GetModule (Name); /* Check if we already have a module with this name */ O = FindObjData (Module); if (O == 0) { /* Not found, create a new entry */ O = NewObjData (); } else { /* Found - check the file modification times of the internal copy * and the external one. */ if (difftime ((time_t)O->MTime, StatBuf.st_mtime) > 0.0) { Warning ("Replacing module `%s' by older version in library `%s'", O->Name, LibName); } /* Free data */ ClearObjData (O); } /* Initialize the object module data structure */ O->Name = xstrdup (Module); O->Flags = OBJ_HAVEDATA; O->MTime = StatBuf.st_mtime; O->Start = 0; /* Determine the file size. Note: Race condition here */ fseek (Obj, 0, SEEK_END); O->Size = ftell (Obj); /* Read the basic data from the object file */ ObjReadData (Obj, O); /* Copy the complete object data to the library file and update the * starting offset */ fseek (Obj, 0, SEEK_SET); O->Start = LibCopyTo (Obj, O->Size); /* Done, close the file (we read it only, so no error check) */ fclose (Obj); }
int MakeAudioCuts( CONVDATA *cn) { int pid,status,id,Qty; char Folder[500]; Dlink *L; MEDIAINFO *Mif; CONVDATA Cn; char *mpt; float opos,cpos,pos,duration,Mesec; Cn= *cn; Mif = GetMediaInfo(Cn.infile); Mesec= Mif->TotSec; free(Mif); if ((pid=fork())==0) { char command[10000],File[500],options[5000],Qstr[100]; void *Thds; sprintf(Folder,"%-s/%-d",getenv("HOME"),getpid()); if(FileStat(Folder)) kgCleanDir(Folder); mkdir(Folder,0700); if(pipe(Jpipe) < 0) exit(0); if(pipe(Jstat) < 0) exit(0); sprintf(GrabFileName,"Making : %-s\n",Cn.outfile); MonPipe = Jpipe[0]; if( fork()==0) { close(Jpipe[1]); close(Jstat[0]); RunMonitorJoin(NULL); exit(0); } close(Jpipe[0]); close(Jstat[1]); L = Cn.Cutlist; Resetlink(L); id=0; sprintf(options,"!c01" "Making audio cuts Pl. be patient...\n"); write(Jpipe[1],options,strlen(options)); // Thds = OpenThreads(0); cpos =0; opos =0; while( (mpt=(char *)Getrecord(L))!= NULL) { sscanf(mpt,"%f%f",&pos,&duration); if((pos - opos)> 0.001) { sprintf(command,"kgffmpeg -i \"%s\" -vn -aq 2 -ac 2 -ar 44100 " "-acodec pcm_s32le -y -ss %f -to %f %s/M%-4.4d.wav ", Cn.infile, opos, pos ,Folder,id); id++; runfunction(command,ProcessSkip,kgffmpeg); } opos = pos+duration; } if(opos< Mesec) { sprintf(command,"kgffmpeg -i \"%s\" -vn -aq 2 -ac 2 -ar 44100 " "-acodec pcm_s32le -y -ss %f %s/M%-4.4d.wav ", Cn.infile, opos, Folder,id); opos = pos; id++; runfunction(command,ProcessSkip,kgffmpeg); // printf("%s\n",command); } if(id==0) exit(0); sprintf(options,"Joining...%d\n",id); write(Jpipe[1],options,strlen(options)); sprintf(options,"Per: %f\n",0.0); write(Jpipe[1],options,strlen(options)); joinwav(Folder,id); { Esec= Cn.EndSec; sprintf(options,"Esec: %lf\n",Cn.EndSec); write(Jpipe[1],options,strlen(options)); sprintf(options,"Converting to Output...\n"); write(Jpipe[1],options,strlen(options)); Qstr[0]='\0'; if(kgSearchString(Cn.outfile,(char *)".aac")>=0) { sprintf(Qstr," -c:a libfdk_aac "); } if(kgSearchString(Cn.outfile,(char *)".mp3")>=0) { sprintf(Qstr," -c:a libmp3lame -aq 0 "); } sprintf(command,"kgffmpeg -i %-s/out.wav " " -ac 2 %s -y \"%-s\" ", Folder ,Qstr,Cn.outfile); // printf("%s\n",command); runfunction(command,ProcessToAudioPipe,kgffmpeg); kgCleanDir(Folder); strcpy(options,"Joinded Audio Files\n"); write(Jpipe[1],options,strlen(options)); close(Jpipe[1]); exit(0); } } else { waitpid(pid,&status,0); sprintf(Folder,"%-s/%-d",getenv("HOME"),pid); if(FileStat(Folder)) kgCleanDir(Folder); } }
//Print errors to log file bool __fastcall PrintError( const size_t ErrorType, const wchar_t *Message, const SSIZE_T ErrorCode, const wchar_t *FileName, const size_t Line) { //Print Error: Enable/Disable. if (!Parameter.PrintError || //PrintError parameter check Message == nullptr || CheckEmptyBuffer(Message, wcsnlen_s(Message, ORIGINAL_PACKET_MAXSIZE) * sizeof(wchar_t)) || //Message check FileName != nullptr && CheckEmptyBuffer(FileName, wcsnlen_s(FileName, ORIGINAL_PACKET_MAXSIZE) * sizeof(wchar_t))) //FileName check return false; //Get current date and time. std::shared_ptr<tm> TimeStructure(new tm()); memset(TimeStructure.get(), 0, sizeof(tm)); auto TimeValues = time(nullptr); #if defined(PLATFORM_WIN) if (localtime_s(TimeStructure.get(), &TimeValues) > 0) #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) if (localtime_r(&TimeValues, TimeStructure.get()) == nullptr) #endif return false; //Print Start Time at first printing. time_t InnerStartTime = 0; if (StartTime > 0) { InnerStartTime = StartTime; StartTime = 0; } //Print to screen. #if defined(PLATFORM_WIN) if (GlobalRunningStatus.Console) #elif defined(PLATFORM_LINUX) if (!GlobalRunningStatus.Daemon) #endif { //Print start time before print errors. if (InnerStartTime > 0) { std::shared_ptr<tm> TimeStructureTemp(new tm()); memset(TimeStructureTemp.get(), 0, sizeof(tm)); #if defined(PLATFORM_WIN) if (localtime_s(TimeStructureTemp.get(), &InnerStartTime) > 0) #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) if (localtime_r(&InnerStartTime, TimeStructureTemp.get()) == nullptr) #endif return false; wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Log opened at this moment.\n", TimeStructureTemp->tm_year + 1900, TimeStructureTemp->tm_mon + 1, TimeStructureTemp->tm_mday, TimeStructureTemp->tm_hour, TimeStructureTemp->tm_min, TimeStructureTemp->tm_sec); } //Print errors. switch (ErrorType) { //System Error case LOG_ERROR_SYSTEM: { if (ErrorCode == 0) { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); } else { #if defined(PLATFORM_WIN) //About System Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx. if (ErrorCode == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, ERROR_FAILED_SERVICE_CONTROLLER_CONNECT(The service process could not connect to the service controller).\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); else #endif wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode); } }break; //Parameter Error case LOG_ERROR_PARAMETER: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Parameter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str()); else wprintf_s(L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) wprintf_s(L", error code is %d", (int)ErrorCode); wprintf_s(L".\n"); }break; //IPFilter Error case LOG_ERROR_IPFILTER: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> IPFilter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str()); else wprintf_s(L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) wprintf_s(L", error code is %d", (int)ErrorCode); wprintf_s(L".\n"); }break; //Hosts Error case LOG_ERROR_HOSTS: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Hosts Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str()); else wprintf_s(L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) wprintf_s(L", error code is %d", (int)ErrorCode); wprintf_s(L".\n"); }break; //Network Error //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. case LOG_ERROR_NETWORK: { if (ErrorCode == 0) wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); #if defined(PLATFORM_WIN) else if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable. return true; #endif else wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode); }break; //WinPcap Error #if defined(ENABLE_PCAP) case LOG_ERROR_PCAP: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Pcap Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; #endif //DNSCurve Error #if defined(ENABLE_LIBSODIUM) case LOG_ERROR_DNSCURVE: { #if defined(PLATFORM_WIN) if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable. return true; else #endif wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> DNSCurve Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; #endif //Notice case LOG_MESSAGE_NOTICE: { wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Notice: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; default: { return false; } } } //Check whole file size. std::unique_lock<std::mutex> ErrLogMutex(ErrorLogLock); #if defined(PLATFORM_WIN) std::shared_ptr<WIN32_FILE_ATTRIBUTE_DATA> File_WIN32_FILE_ATTRIBUTE_DATA(new WIN32_FILE_ATTRIBUTE_DATA()); memset(File_WIN32_FILE_ATTRIBUTE_DATA.get(), 0, sizeof(WIN32_FILE_ATTRIBUTE_DATA)); if (GetFileAttributesExW(GlobalRunningStatus.Path_ErrorLog->c_str(), GetFileExInfoStandard, File_WIN32_FILE_ATTRIBUTE_DATA.get()) != FALSE) { std::shared_ptr<LARGE_INTEGER> ErrorFileSize(new LARGE_INTEGER()); memset(ErrorFileSize.get(), 0, sizeof(LARGE_INTEGER)); ErrorFileSize->HighPart = File_WIN32_FILE_ATTRIBUTE_DATA->nFileSizeHigh; ErrorFileSize->LowPart = File_WIN32_FILE_ATTRIBUTE_DATA->nFileSizeLow; if (ErrorFileSize->QuadPart > 0 && (size_t)ErrorFileSize->QuadPart >= Parameter.LogMaxSize && DeleteFileW(GlobalRunningStatus.Path_ErrorLog->c_str()) != 0) PrintError(LOG_ERROR_SYSTEM, L"Old Error Log file was deleted", 0, nullptr, 0); } File_WIN32_FILE_ATTRIBUTE_DATA.reset(); #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) std::shared_ptr<struct stat> FileStat(new struct stat()); memset(FileStat.get(), 0, sizeof(struct stat)); if (stat(GlobalRunningStatus.sPath_ErrorLog->c_str(), FileStat.get()) == EXIT_SUCCESS && FileStat->st_size >= (off_t)Parameter.LogMaxSize && remove(GlobalRunningStatus.sPath_ErrorLog->c_str()) == EXIT_SUCCESS) PrintError(LOG_ERROR_SYSTEM, L"Old Error Log file was deleted", 0, nullptr, 0); FileStat.reset(); #endif //Main print #if defined(PLATFORM_WIN) FILE *Output = nullptr; if (_wfopen_s(&Output, GlobalRunningStatus.Path_ErrorLog->c_str(), L"a,ccs=UTF-8") == EXIT_SUCCESS && Output != nullptr) #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) auto Output = fopen(GlobalRunningStatus.sPath_ErrorLog->c_str(), "a"); if (Output != nullptr) #endif { //Print start time before print errors. if (InnerStartTime > 0) { std::shared_ptr<tm> TimeStructureTemp(new tm()); memset(TimeStructureTemp.get(), 0, sizeof(tm)); #if defined(PLATFORM_WIN) if (localtime_s(TimeStructureTemp.get(), &InnerStartTime) > 0) #elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX)) if (localtime_r(&InnerStartTime, TimeStructureTemp.get()) == nullptr) #endif { fclose(Output); return false; } fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Log opened at this moment.\n", TimeStructureTemp->tm_year + 1900, TimeStructureTemp->tm_mon + 1, TimeStructureTemp->tm_mday, TimeStructureTemp->tm_hour, TimeStructureTemp->tm_min, TimeStructureTemp->tm_sec); } //Print errors. switch (ErrorType) { //System Error case LOG_ERROR_SYSTEM: { if (ErrorCode == 0) { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); } else { #if defined(PLATFORM_WIN) //About System Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx. if (ErrorCode == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, ERROR_FAILED_SERVICE_CONTROLLER_CONNECT(The service process could not connect to the service controller).\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); else #endif fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode); } }break; //Parameter Error case LOG_ERROR_PARAMETER: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Parameter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); else fwprintf_s(Output, L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) fwprintf_s(Output, L", error code is %d", (int)ErrorCode); fwprintf_s(Output, L".\n"); }break; //IPFilter Error case LOG_ERROR_IPFILTER: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> IPFilter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); else fwprintf_s(Output, L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) fwprintf_s(Output, L", error code is %d", (int)ErrorCode); fwprintf_s(Output, L".\n"); }break; //Hosts Error case LOG_ERROR_HOSTS: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Hosts Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); if (FileName != nullptr) { //Delete double backslash. std::wstring sFileName(FileName); while (sFileName.find(L"\\\\") != std::wstring::npos) sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\")); //Write to file if (Line > 0) fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str()); else fwprintf_s(Output, L" in %ls", sFileName.c_str()); } //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. if (ErrorCode > 0) fwprintf_s(Output, L", error code is %d", (int)ErrorCode); fwprintf_s(Output, L".\n"); }break; //Network Error //About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx. case LOG_ERROR_NETWORK: { if (ErrorCode == 0) fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); #if defined(PLATFORM_WIN) else if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable. break; #endif else fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode); }break; //WinPcap Error #if defined(ENABLE_PCAP) case LOG_ERROR_PCAP: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> WinPcap Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; #endif //DNSCurve Error #if defined(ENABLE_LIBSODIUM) case LOG_ERROR_DNSCURVE: { #if defined(PLATFORM_WIN) if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable. break; else #endif fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> DNSCurve Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; #endif //Notice case LOG_MESSAGE_NOTICE: { fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Notice: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message); }break; default: { fclose(Output); return false; } } //Close file. fclose(Output); return true; } return false; }
void Compositor::content_request(std::string request) { std::string::size_type extPos; std::string ext; std::string baseFile; uint extGroup = 0; // setup our extention mapping const std::vector<Renderable> extMap = { {}, {"html", "md"}, {"htm", "md"} }; if (request[0] != '/') request.insert(0, "/"); // check for file ext extPos = request.rfind("."); if (extPos == std::string::npos) { // no extention, check to see if is a directory // check dir // check for index // do file map } // map file to pre render format baseFile = request.substr(0, extPos); ext = request.substr(extPos + 1); for (uint i = 0; i < extMap.size(); ++i) { if (extMap[i].to == ext) { extGroup = i; } if (extGroup) { break; } } // if we have a render group check both files if (extGroup) { // get the file details FileStat rendered = (FileStat(this->webRoot + baseFile + "." + extMap[extGroup].to)); FileStat data = (FileStat(this->dataRoot + baseFile + "." + extMap[extGroup].from)); log_message("Testing for file: " + rendered.path); log_message("Testing for file: " + data.path); this->file_check(rendered); this->file_check(data); // check change times if (rendered.modified && rendered.modified >= data.modified) { // serve the exisiting log_message("serving " + rendered.path); this->serve_existing(rendered.path); } else if (data.modified) { // render and serve std::string render; this->read_file(data.path, render); // TODO: make this easier to extend render types, adding scss atleast would be nice // TODO: how could i account for a context to render mstch also? render = this->render_md(render); log_message("serving: " + data.path); if (render != "") { this->context_emplace("content", render); this->renderedPage = this->render_mstch(this->pageTemplate, this->pageContext); this->write_file(rendered.path, this->renderedPage); this->serve_existing(rendered.path, &this->renderedPage); }// else TODO: there was prolly an error in the syntax of the md file } // if we get here neither file should exist // just returning should force a 404 due to default values } else { // no ext group check for an existing file FileStat rendered(this->webRoot + baseFile); if (this->file_check(rendered)) { this->serve_existing(rendered.path); } // else file should not exist, return to force 404 } }