Ejemplo n.º 1
0
/*
   Log

   Writes a message to the previously opened log file.

   Passed in a format string and variable number of parameters,
   in the format used by printf.
*/
void Log(char *format, ... ) 
{
	char dtbuf[30];
	va_list arglist;
    struct tm *today;
    time_t now;

	time(&now);
    today = localtime(&now);

	if( Julian != today->tm_yday+1 ) {
		LogClose();
		LogOpen( FileName );
	}

	if (logfp==NULL) return;

	sprintf(dtbuf,"%02d/%02d/%04d %02d:%02d:%02d",today->tm_mon+1,today->tm_mday,
		today->tm_year+1900,today->tm_hour,today->tm_min,today->tm_sec);
	fprintf(logfp, "%5lu  %s ",LineNum++,dtbuf);
	va_start ( arglist, format );
	vfprintf (logfp, format, arglist );
	//if (format[strlen(format)-1]<' ')
		//format[strlen(format)-1] = 0;
	fprintf(logfp,"\r\n");
	fflush ( logfp );
}
Ejemplo n.º 2
0
/*
 * openlog() replacement for systems without <syslog.h>, like Windows
 */
void
LogOpenLog(const char *ident, int option, int facility)
{
	size_t length;
	char *filename;

	length = strlen(ident) + 5;
	if ((filename = malloc(length)) != NULL) {
		LogSetProgramName(ident);
		(void) snprintf(filename, length, "%s.log", ident);
		(void) LogOpen(filename);
		free(filename);
	}
}
Ejemplo n.º 3
0
short ValidateFile( char *filetocheck )
{
	//struct	stat	fileStat;
	long	hnd;

	if ( IsURL( filetocheck ) ){
		return 1;
	} else {
		hnd = LogOpen( filetocheck, NULL );
	}
	//err = stat( filetocheck, &fileStat );

	if ( hnd ){
		LogClose( hnd, filetocheck );
		return 1;
	}
	return 0;
}
Ejemplo n.º 4
0
int
main(int argc, char **argv)
{
	serverOptions(argc, argv);

	switch (server_quit) {
	case 1:
		/* Slow quit	-q */
		exit(pidKill(pid_file, SIGQUIT) != 0);

	case 2:
		/* Quit now	-q -q */
		exit(pidKill(pid_file, SIGTERM) != 0);
	default:
		/* Restart	-q -q -q
		 * Restart-If	-q -q -q -q
		 */
		if (pidKill(pid_file, SIGTERM) && 3 < server_quit) {
			fprintf(stderr, "no previous instance running: %s (%d)\n", strerror(errno), errno);
			return EXIT_FAILURE;
		}

		sleep(2);
	}

	if (daemon_mode) {
		if (daemon(1, 1)) {
			fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno));
			return EX_SOFTWARE;
		}

		if (atexit(atExitCleanUp)) {
			fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno));
			return EX_SOFTWARE;
		}

		openlog("dnsd", LOG_PID|LOG_NDELAY, LOG_DAEMON);
	} else {
		LogOpen("(standard error)");
	}

	return serverMain();
}
Ejemplo n.º 5
0
// Start the job, locking down the program while it runs
void JobStart() {
    sectionitem section;

    // Change the stage
    if (Job.stage != JobStageBefore) return; // Can only start when before
    Job.stage = JobStageRunning;

    // Record the time now as when the job starts
    Job.time = GetTickCount();

    // Save tasks text from the tasks box to the registry
    Job.tasks = WindowTextGet(Handle.tasks);
    RegistryWrite(REGISTRYKEY, REGISTRYPATH, REGISTRYNAME, Job.tasks);

    // Delete the log file from last time and open a new one
    string s = LogPath(L"Backup");
    DiskDeleteFile(s);
    Job.log = LogOpen(s, L"Errors");

    // Start a new thread that will perform all the tasks
    BeginThread(Tasks); // Have the thread run the Tasks() function
}
Ejemplo n.º 6
0
// Simple, generic window init //
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int iCmdShow)
{
	WNDCLASS wc;

	MSG msg;
	bool Quit = FALSE;
	DWORD       dwExStyle;                      // Window Extended Style
	DWORD       dwStyle;                        // Window Style

	// register window class
	wc.style = CS_OWNDC;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = L"BMFontGL";
	RegisterClass(&wc);

	dwExStyle = WS_EX_APPWINDOW;   // Window Extended Style    
	dwStyle = WS_OVERLAPPEDWINDOW | WS_THICKFRAME;                    // Windows Style
	RECT WindowRect;                                                 // Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left = (long)0;                                         // Set Left Value To 0
	WindowRect.right = (long)WinWidth;                                 // Set Right Value To Requested Width
	WindowRect.top = (long)0;                                          // Set Top Value To 0
	WindowRect.bottom = (long)WinHeight;                               // Set Bottom Value To Requested Height
	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);      // Adjust Window To True Requested Size


	// Create The Window
	if (!(hWnd = CreateWindowEx(dwExStyle,							// Extended Style For The Window
		L"BMFontGL",							// Class Name
		L"OpenGL BMFont Sample Implementation",						// Window Title
		dwStyle |							// Defined Window Style
		WS_CLIPSIBLINGS |					// Required Window Style
		WS_CLIPCHILDREN,					// Required Window Style
		CW_USEDEFAULT, 0,   				// Window Position
		WindowRect.right - WindowRect.left,	// Calculate Window Width
		WindowRect.bottom - WindowRect.top,	// Calculate Window Height
		NULL,								// No Parent Window
		NULL,								// No Menu
		hInstance,							// Instance
		NULL)))								// Dont Pass Anything To WM_CREATE
	{
		// Reset The Display
		MessageBox(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	//********** Program Initializations *************
	//Enable Logging
	LogOpen("glfonttest.log");
	// enable OpenGL for the window
	CreateGLContext();
	//Basic Window Init
	WRLOG("Starting Program");
	ShowWindow(hWnd, SW_SHOW);                                         // Show The Window
	SetForegroundWindow(hWnd);									    // Slightly Higher Priority
	SetFocus(hWnd);													// Sets Keyboard Focus To The Window
	ReSizeGLScene(WinWidth, WinHeight);										    // Set Up Our Perspective GL Screen
	//Get the Supported OpenGl Version
	CheckGLVersionSupport();
	//Fill in the Window Rect;
	GetClientRect(hWnd, &MyWindow);
	//Set the OpenGl View
	ViewOrtho(WinWidth, WinHeight);

	//Load and Initialize the Fonts
	wrlog("Starting to parse fonts.");

	Lucida = new BMFont(WinWidth, WinHeight);
	if (!Lucida->LoadFont("lucida.fnt"))
	{
		MessageBox(NULL, L"Error, font file not found, exiting", L"File Not Found", MB_ICONERROR | MB_OK);
		Quit = TRUE;
		//PostQuitMessage(-1);
	}
	LOG_DEBUG("Font Loaded Sucessfully");

	Snap = new BMFont(WinWidth, WinHeight);
	if (!Snap->LoadFont("snap.fnt"))
	{
		MessageBox(NULL, L"Error, font file not found, exiting", L"File Not Found", MB_ICONERROR | MB_OK);
		Quit = TRUE;
		//PostQuitMessage(-1);
	}
	LOG_DEBUG("Font Loaded Sucessfully");

	Times = new BMFont(WinWidth, WinHeight);
	if (!Times->LoadFont("times.fnt"))
	{
		MessageBox(NULL, L"Error, font file not found, exiting", L"File Not Found", MB_ICONERROR | MB_OK);
		Quit = TRUE;
		// PostQuitMessage(-1);
	}
	LOG_DEBUG("Font Loaded Sucessfully");

	// ********** Program Main Loop **********

	while (!Quit) {

		// check for messages
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {

			// handle or dispatch messages
			if (msg.message == WM_QUIT) {
				Quit = TRUE;
			}
			else {
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}

		}
		else {

			// ********** OpenGL drawing code, very simple, just to show off the font. **********

			glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
			glClear(GL_COLOR_BUFFER_BIT);

			// setup texture mapping
			glEnable(GL_TEXTURE_2D);

			glLoadIdentity();
			Times->SetAlign(BMFont::AlignCenter);
			Times->SetScale(1.5f);
			Times->SetColor(250, 251, 252, 255);
			Times->Print(0, 280, "A different font, centered. Kerning: To Ti");

			/*
			Lucida->setColor(250,250,55,254);
			Lucida->PrintCenter(240,"This is another font.");

			Snap->setColor(255,255,255,255);
			Snap->setScale(1.0f);
			Snap->Print(0, 0, "This is standard printing.");
			*/
			Snap->SetColor(RGB_WHITE);
			Snap->SetAngle(0);
			Snap->SetScale(2.0f);
			Snap->SetAlign(BMFont::AlignNear);
			Snap->Print(40.0, 180, "Scaling makes it Big!");

			Snap->SetColor(RGB_WHITE);
			Snap->SetScale(1.0f);
			Snap->SetAngle(90);
			Snap->Print(130.0, 100, "The next line is right here.");
			Snap->SetAngle(0);
			Snap->Print(130.0, 350, "Another long line here.");
			/*
			Snap->setScale(1.0f);
			Snap->Print(2, Snap->getHeight()*4, "Or it can make it smaller!");
			Snap->setScale(1.0f);
			Snap->setColor(25,155,255,255);
			Snap->PrintCenter(320, "Centered printing: To Ti");
		   */
			Times->Render();
			Snap->Render();
			GlSwap();
		}
	}

	// ********** Cleanup and exit gracefully. **********
	// shutdown OpenGL
	delete Lucida;
	delete Snap;
	delete Times;
	DeleteGLContext();
	LogClose();
	// destroy the window 
	DestroyWindow(hWnd);

	return (int)msg.wParam;
}
Ejemplo n.º 7
0
// This now supports gzip or bzip2 to compress with.
long CompressLogFiles( char **logfiles, long n, int type, int deletelog )
{
	long	count,  dataread, dataout, perc;
	char	newlogname[512],
			*logFN;
	long	failed = 1;

	for( count=0; count<n ; count++){
		logFN = logfiles[count];

		if ( strstr( logFN, ".gz" ) && type==0 )
			continue;
		if ( !IsURL(logFN) )
		{
			void *fp;
			void *outfp;
			char *ram, *p;
			long blocksize = 1024*32;

			StopAll( 0 );

			if ( ram = (char*)malloc( blocksize ) ){
				__int64 dataleft, length;

				if ( fp=(void*)LogOpen( logFN, &length ) ){
					int ret;

					sprintf( newlogname, "%s.gz", logFN );

					switch( type ){
						default:
						case COMPRESS_GZIP :
							sprintf( newlogname, "%s.gz", logFN );
							if ( p = strstr( newlogname, ".bz2" ) )
								mystrcpy( p, ".gz" );
							outfp = gzopen( newlogname, "wb6" );
							break;
#ifdef  _BZLIB_H
						// bzip2 is about 15X slower for 1/2 the size files, level6 is the best time-vs-size level roughly
						case COMPRESS_BZIP2 :
							sprintf( newlogname, "%s.bz2", logFN );
							if ( p = strstr( newlogname, ".gz" ) )
								mystrcpy( p, ".bz2" );
							outfp = BZ2_bzopen( newlogname, "wb6" );
							break;
#endif
					}

					dataout = 0;
					if ( outfp ){
						dataleft = length;
						dataread = 1;
						while( dataread>0 && !IsStopped() ){
							//OutDebugs( "dataleft = %d", dataleft );
							perc = (long)(100*((length-dataleft)/(float)length));
							//sprintf( msgtext, "Compressing %s ...", 100*((length-dataleft)/length) );
							ShowProgress( perc, FALSE, NULL );
							StatusSetID( IDS_COMPRESSING, perc, dataout/1024 );

							dataread = LogRead( fp, logFN, ram, blocksize );

							if ( dataread>0 )
							{
								dataleft -= dataread;
	
								if ( type == COMPRESS_GZIP )	dataout+=gzwrite( outfp, ram , dataread );
#ifdef _BZLIB_H
								if ( type == COMPRESS_BZIP2 )	dataout+=BZ2_bzwrite( outfp, ram , dataread );
#endif
							}
						}
						if ( type == COMPRESS_GZIP )	gzclose( outfp );
#ifdef _BZLIB_H
						if ( type == COMPRESS_BZIP2 )	BZ2_bzclose( outfp );
#endif
						if ( !IsStopped() ){
							__int64 newsize;
							FILE *newfp;
							failed = 0;
							if ( (newfp = fopen( newlogname, "ab+" )) ) {
								newsize = GetFPLength( newfp );

								if ( type == COMPRESS_BZIP2 ){
									long value;
									value = 0;
									fwrite( &value, 1, 4, newfp );
									value = (long)length;
									fwrite( &value, 1, 4, newfp );
								}
								fclose(newfp);
							}
							StatusSetID( IDS_COMPRESSDONE, dataout/1024, newsize/1024, 100*newsize/dataout );
						} else
							StatusSet( "Stopped" );

					}
					ret = LogClose( (long)fp, logFN );
					if ( deletelog && !failed){
						remove( logFN );
					}
				}
				free( ram );
			}
		}
	}
	return failed;
}
Ejemplo n.º 8
0
BOOL DBI1::fInit()
{
#if defined(INSTRUMENTED)
    if (fWrite)
        log = LogOpen();
    if (log)
        LogNoteEvent(log, "DBI", 0, letypeBegin, 0);
#endif
    CB cbDbiStream = MSFGetCbStream(ppdb1->pmsf, snDbi);

    if (cbDbiStream > 0) {
        CB cbdbihdr = sizeof(dbihdr);
        OFF off = 0;
        if (!MSFReadStream2(ppdb1->pmsf, snDbi, 0, &(dbihdr), &cbdbihdr)) {
            ppdb1->setReadError();
            return FALSE;
        }
        off += sizeof(dbihdr);

        dassert(cbDbiStream == cbdbihdr + dbihdr.cbGpModi + dbihdr.cbSC +
            dbihdr.cbSecMap + dbihdr.cbFileInfo);

        if (fWrite && (ppdb1->pdbStream.impv == PDB1::impvVC4)) {
            // can't incremental link a vc4 format pdb, we have introduced
            // new scheme to track refcounts on promoted global syms - return
            // a format error here so that we force a full link and rewrite of
            // all of the mods streams
            // sps 8/14/95
            if (fCreate)
                // ok we are rewritting this as a vc 4.1 dbi
                ppdb1->pdbStream.impv = PDB1::impv;
            else {
                ppdb1->setLastError(EC_FORMAT, 0);
                return FALSE;
            }
        }

        // read in the gpmodi substream
        if (dbihdr.cbGpModi > 0) {
            expect(fAlign(dbihdr.cbGpModi));
            // load gpmodi
            PB pb;

            if (ppdb1->pdbStream.impv == PDB1::impvVC2) {
                // read in v2 modi into temp table and do initial alloc of
                // bufGpmodi which will hold the converted v4 modi
                Buffer bufGpV2modi;
                PB pbV2;

                if (!bufGpmodi.SetInitAlloc(dbihdr.cbGpModi) ||
                    !bufGpV2modi.Reserve(dbihdr.cbGpModi, &pbV2)) {
                    ppdb1->setOOMError();
                    return FALSE;
                }
                else if (!MSFReadStream2(ppdb1->pmsf, snDbi, off, pbV2, &(dbihdr.cbGpModi))) {
                    ppdb1->setReadError();
                    return FALSE;
                }

                // pass thru v2 modi table and copy/convert into v4 modi table
                for (PB pbEnd = bufGpV2modi.End(), pbV2EndRec = ((MODI*)pbV2)->pbV2End();
                    pbV2 < pbEnd;
                    pbV2 = pbV2EndRec, pbV2EndRec = ((MODI*)pbV2)->pbV2End())
                {
                    CB cb;
                    DWORD dwDummy = 0;
#pragma warning(disable:4101)
                    MODI *pmodiDummy = 0;

                    // copy up to the missing dwCharacteristics field
                    bufGpmodi.Append(pbV2,
                        cb = sizeof(pmodiDummy->pmod) + sizeof(pmodiDummy->sc.isect) +
                        sizeof(pmodiDummy->sc.off) + sizeof(pmodiDummy->sc.cb));
                    // insert the missing dwCharacteristics field
                    bufGpmodi.Append((PB)&dwDummy,  sizeof(pmodiDummy->sc.dwCharacteristics));
                    pbV2 += cb;
                    // copy the rest of the record
                    bufGpmodi.Append(pbV2, pbV2EndRec - pbV2);
                }

                pb = bufGpmodi.Start();
                off += dbihdr.cbGpModi;
                dbihdr.cbGpModi = bufGpmodi.Size();
            }
            else {
                if (!bufGpmodi.Reserve(dbihdr.cbGpModi, &pb)) {
                    ppdb1->setOOMError();
                    return FALSE;
                }
                else if (!MSFReadStream2(ppdb1->pmsf, snDbi, off, pb, &(dbihdr.cbGpModi))) {
                    ppdb1->setReadError();
                    return FALSE;
                }
                off += dbihdr.cbGpModi;
            }


            // build rgpmodi
            for (PB pbEnd = bufGpmodi.End(); pb < pbEnd;
                 pb = ((MODI*)pb)->pbEnd(), imodMac++)
            {
                expect(fAlign(pb));
                MODI* pmodi = (MODI*)pb;
                pmodi->pmod = 0;
                pmodi->fWritten = FALSE;
                pmodi->ifileMac = 0;
                pmodi->mpifileichFile = 0;
                if (!bufRgpmodi.Append((PB)&pmodi, sizeof pmodi)) {
                    ppdb1->setOOMError();
                    return FALSE;
                }
                expect(fAlign(&(rgpmodi[imodMac])));
                assert(rgpmodi[imodMac] == pmodi);
            }
        }

        // read in the Section Contribution substream
        if (dbihdr.cbSC > 0) {
            expect(fAlign(dbihdr.cbSC));

            if (ppdb1->pdbStream.impv == PDB1::impvVC2) {
                // Convert VC++ 2.0 SC entries to VC++ 4.0 format

                unsigned csc = dbihdr.cbSC / sizeof(SC20);

                CB cb = csc * sizeof(SC);

                if (!bufSC.Reserve(cb)) {
                    ppdb1->setOOMError();
                    return FALSE;
                }

                pscEnd = (SC *) bufSC.Start();

                cb = sizeof(SC20);
                while (csc--) {

                    SC20 sc20;
                    if (!MSFReadStream2(ppdb1->pmsf, snDbi, off, &sc20, &cb)) {
                        ppdb1->setReadError();
                        return FALSE;
                    }

                    pscEnd->isect = sc20.isect;
                    pscEnd->off = sc20.off;
                    pscEnd->cb = sc20.cb;
                    pscEnd->dwCharacteristics = 0;
                    pscEnd->imod = sc20.imod;

                    off += sizeof(SC20);
                    pscEnd++;
                }
            } else {
                if (!bufSC.Reserve(dbihdr.cbSC)) {
                    ppdb1->setOOMError();
                    return FALSE;
                }
                if (!MSFReadStream2(ppdb1->pmsf, snDbi, off, bufSC.Start(), &(dbihdr.cbSC))) {
                    ppdb1->setReadError();
                    return FALSE;
                }
                off += dbihdr.cbSC;
                pscEnd = (SC*)(bufSC.End());
            }
        }

        // read in the Section Map substream only if we are not writing
        if (dbihdr.cbSecMap && !fWrite) {
            expect(fAlign(dbihdr.cbSecMap));
            if (!bufSecMap.Reserve(dbihdr.cbSecMap)) {
                ppdb1->setOOMError();
                return FALSE;
            }
            else if (!MSFReadStream2(ppdb1->pmsf, snDbi, off, bufSecMap.Start(), &(dbihdr.cbSecMap))) {
                ppdb1->setReadError();
                return FALSE;
            }
        }
        off += dbihdr.cbSecMap;

        if (dbihdr.cbFileInfo > 0) {
            expect(fAlign(dbihdr.cbFileInfo));
            Buffer bufFileInfo;
            if (!bufFileInfo.Reserve(dbihdr.cbFileInfo)) {
                ppdb1->setOOMError();
                return FALSE;
            }
            else if (!MSFReadStream2(ppdb1->pmsf, snDbi, off, bufFileInfo.Start(), &dbihdr.cbFileInfo)) {
                ppdb1->setReadError();
                return FALSE;
            }
            off += dbihdr.cbFileInfo;
            reloadFileInfo(bufFileInfo.Start());
        }
    }

    // for now we will completely delete old Mod info from previous builds on
    // a dbi creation.  later we may want to perform this instead of trying to
    // perform any garbage collection.

#pragma message ("todo - temporary clear dbi on create")
    if (fCreate && !clearDBI())
        return FALSE;

    if (fWrite) {
        // open the global and public symbol tables
        GSI* pgsigs_;
        GSI* pgsips_;

        if (!OpenGlobals(&pgsigs_) || !OpenPublics(&pgsips_))
            return FALSE;

        pgsiGS = (GSI1*) pgsigs_;
        pgsiPS = (PSGSI1*) pgsips_;

        // just allocate the seg descriptor counters
        OMFSegMap omfsegmap = {0, 0};
        expect(fAlign(sizeof(omfsegmap)));
        if (!bufSecMap.Append((PB)&omfsegmap, sizeof(omfsegmap))) {
            ppdb1->setOOMError();
            return FALSE;
        }
    }

    return TRUE;
}
Ejemplo n.º 9
0
extern "C" HRESULT EngineRun(
    __in HINSTANCE hInstance,
    __in_z_opt LPCWSTR wzCommandLine,
    __in int nCmdShow,
    __out DWORD* pdwExitCode
    )
{
    HRESULT hr = S_OK;
    BOOL fComInitialized = FALSE;
    BOOL fLogInitialized = FALSE;
    BOOL fRegInitialized = FALSE;
    BOOL fWiuInitialized = FALSE;
    BOOL fXmlInitialized = FALSE;
    OSVERSIONINFOEXW ovix = { };
    LPWSTR sczExePath = NULL;
    BOOL fRunNormal = FALSE;
    BOOL fRestart = FALSE;

    BURN_ENGINE_STATE engineState = { };

    hr = InitializeEngineState(&engineState);
    ExitOnFailure(hr, "Failed to initialize engine state.");

    engineState.command.nCmdShow = nCmdShow;

    // Ensure that log contains approriate level of information
#ifdef _DEBUG
    LogSetLevel(REPORT_DEBUG, FALSE);
#else
    LogSetLevel(REPORT_VERBOSE, FALSE); // FALSE means don't write an additional text line to the log saying the level changed
#endif

    // initialize platform layer
    PlatformInitialize();

    // initialize COM
    hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
    ExitOnFailure(hr, "Failed to initialize COM.");
    fComInitialized = TRUE;

    // Initialize dutil.
    LogInitialize(::GetModuleHandleW(NULL));
    fLogInitialized = TRUE;

    hr = RegInitialize();
    ExitOnFailure(hr, "Failed to initialize Regutil.");
    fRegInitialized = TRUE;

    hr = WiuInitialize();
    ExitOnFailure(hr, "Failed to initialize Wiutil.");
    fWiuInitialized = TRUE;

    hr = XmlInitialize();
    ExitOnFailure(hr, "Failed to initialize XML util.");
    fXmlInitialized = TRUE;

    ovix.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
    if (!::GetVersionExW((LPOSVERSIONINFOW)&ovix))
    {
        ExitWithLastError(hr, "Failed to get OS info.");
    }

    PathForCurrentProcess(&sczExePath, NULL); // Ignore failure.
    LogId(REPORT_STANDARD, MSG_BURN_INFO, szVerMajorMinorBuild, ovix.dwMajorVersion, ovix.dwMinorVersion, ovix.dwBuildNumber, ovix.wServicePackMajor, sczExePath, wzCommandLine ? wzCommandLine : L"");
    ReleaseNullStr(sczExePath);

    // initialize core
    hr = CoreInitialize(wzCommandLine, &engineState);
    ExitOnFailure(hr, "Failed to initialize core.");

    // select run mode
    switch (engineState.mode)
    {
    case BURN_MODE_NORMAL:
        fRunNormal = TRUE;

        hr = RunNormal(hInstance, &engineState);
        ExitOnFailure(hr, "Failed to run per-user mode.");
        break;

    case BURN_MODE_ELEVATED:
        hr = RunElevated(hInstance, wzCommandLine, &engineState);
        ExitOnFailure(hr, "Failed to run per-machine mode.");
        break;

    case BURN_MODE_EMBEDDED:
        fRunNormal = TRUE;

        hr = RunEmbedded(hInstance, &engineState);
        ExitOnFailure(hr, "Failed to run embedded mode.");
        break;

    case BURN_MODE_RUNONCE:
        hr = RunRunOnce(wzCommandLine, nCmdShow);
        ExitOnFailure(hr, "Failed to run RunOnce mode.");
        break;

    default:
        hr = E_UNEXPECTED;
        ExitOnFailure(hr, "Invalid run mode.");
    }

    // set exit code and remember if we are supposed to restart.
    *pdwExitCode = engineState.userExperience.dwExitCode;
    fRestart = engineState.fRestart;

LExit:
    ReleaseStr(sczExePath);

    // If anything went wrong but the log was never open, try to open a "failure" log
    // and that will dump anything captured in the log memory buffer to the log.
    if (FAILED(hr) && BURN_LOGGING_STATE_CLOSED == engineState.log.state)
    {
        LogOpen(NULL, L"Setup", L"_Failed", L"txt", FALSE, FALSE, NULL);
    }

    UserExperienceRemove(&engineState.userExperience);

    CacheRemoveWorkingFolder(engineState.registration.sczId);

    // If this is a related bundle (but not an update) suppress restart and return the standard restart error code.
    if (fRestart && BOOTSTRAPPER_RELATION_NONE != engineState.command.relationType && BOOTSTRAPPER_RELATION_UPDATE != engineState.command.relationType)
    {
        LogId(REPORT_STANDARD, MSG_RESTART_ABORTED, LoggingRelationTypeToString(engineState.command.relationType));

        fRestart = FALSE;
        hr = HRESULT_FROM_WIN32(ERROR_SUCCESS_REBOOT_REQUIRED);
    }

    UninitializeEngineState(&engineState);

    if (fXmlInitialized)
    {
        XmlUninitialize();
    }

    if (fWiuInitialized)
    {
        WiuUninitialize();
    }

    if (fRegInitialized)
    {
        RegUninitialize();
    }

    if (fComInitialized)
    {
        ::CoUninitialize();
    }

    if (fRunNormal)
    {
        LogId(REPORT_STANDARD, MSG_EXITING, FAILED(hr) ? (int)hr : *pdwExitCode, LoggingBoolToString(fRestart));

        if (fRestart)
        {
            LogId(REPORT_STANDARD, MSG_RESTARTING);
        }
    }

    if (fLogInitialized)
    {
        LogClose(FALSE);
    }

    if (fRestart)
    {
        Restart();
    }

    if (fLogInitialized)
    {
        LogUninitialize(FALSE);
    }

    return hr;
}
Ejemplo n.º 10
0
int
main(int argc, char **argv)
{
	int ch, argi;

	while ((ch = getopt(argc, argv, options)) != -1) {
		switch (ch) {
		case '1':
			first_match_only = 1;
			break;

		case 'f':
			follow_flag = 1;
			break;

		case 'F':
			report_from = optarg;
			if (*report_from == '\0')
				report_from = NULL;
			break;

		case 'v':
			debug++;
			break;

		case 'd':
			db_path = optarg;
			break;

		case 'D':
			db_delete = 1;
			break;

		case 'r':
			report_to = optarg;
			break;

		case 'R':
			db_reset = 1;
			break;

		case 's':
			smtp_host = optarg;
			break;

		case 'y':
			assumed_year = strtol(optarg, NULL, 10);
			break;

		case 'z':
			assumed_tz = strtol(optarg, NULL, 10);
			break;

		default:
			(void) printf(usage);
			return EX_USAGE;
		}
	}

	if (argc <= optind || (follow_flag && optind+2 < argc)) {
		(void) printf(usage);
		return EX_USAGE;
	}

	if (1 < debug)
		LogOpen(NULL);

	if (db_path == NULL) {
		(void) snprintf(db_user, sizeof (db_user), DB_PATH_FMT, getuid());
		db_path = db_user;
	}

	if (db_delete)
		(void) unlink(db_path);

	init_today();

	if (atexit(at_exit_cleanup) || init_db(db_path) || init_rules(argv[optind]))
		return EX_SOFTWARE;

	if ((report = TextSplit(report_to, ", ", 0)) == NULL)
		return EX_SOFTWARE;

	if (optind+1 == argc) {
		follow_flag = 0;
		process_file("-");
	} else {
		for (argi = optind+1; argi < argc; argi++)
			process_file(argv[argi]);
	}

	return EXIT_SUCCESS;
}
Ejemplo n.º 11
0
extern "C" HRESULT LoggingOpen(
    __in BURN_LOGGING* pLog,
    __in BURN_VARIABLES* pVariables,
    __in BOOTSTRAPPER_DISPLAY display,
    __in_z LPCWSTR wzBundleName
    )
{
    HRESULT hr = S_OK;
    LPWSTR sczLoggingBaseFolder = NULL;

    // Check if the logging policy is set and configure the logging appropriately.
    CheckLoggingPolicy(&pLog->dwAttributes);

    if (pLog->dwAttributes & BURN_LOGGING_ATTRIBUTE_VERBOSE || pLog->dwAttributes & BURN_LOGGING_ATTRIBUTE_EXTRADEBUG)
    {
        if (pLog->dwAttributes & BURN_LOGGING_ATTRIBUTE_EXTRADEBUG)
        {
            LogSetLevel(REPORT_DEBUG, FALSE);
        }
        else if (pLog->dwAttributes & BURN_LOGGING_ATTRIBUTE_VERBOSE)
        {
            LogSetLevel(REPORT_VERBOSE, FALSE);
        }

        if ((!pLog->sczPath || !*pLog->sczPath) && (!pLog->sczPrefix || !*pLog->sczPrefix))
        {
            PathCreateTimeBasedTempFile(NULL, L"Setup", NULL, L"log", &pLog->sczPath, NULL);
        }
    }

    // Open the log approriately.
    if (pLog->sczPath && *pLog->sczPath)
    {
        DWORD cRetry = 0;

        hr = DirGetCurrent(&sczLoggingBaseFolder);
        ExitOnFailure(hr, "Failed to get current directory.");

        // Try pretty hard to open the log file when appending.
        do
        {
            if (0 < cRetry)
            {
                ::Sleep(LOG_OPEN_RETRY_WAIT);
            }

            hr = LogOpen(sczLoggingBaseFolder, pLog->sczPath, NULL, NULL, pLog->dwAttributes & BURN_LOGGING_ATTRIBUTE_APPEND, FALSE, &pLog->sczPath);
            if (pLog->dwAttributes & BURN_LOGGING_ATTRIBUTE_APPEND && HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION) == hr)
            {
                ++cRetry;
            }
        } while (cRetry > 0 && cRetry <= LOG_OPEN_RETRY_COUNT);

        if (FAILED(hr))
        {
            // Log is not open, so note that.
            LogDisable();
            pLog->state = BURN_LOGGING_STATE_DISABLED;

            if (pLog->dwAttributes & BURN_LOGGING_ATTRIBUTE_APPEND)
            {
                // If appending, ignore the failure and continue.
                hr = S_OK;
            }
            else // specifically tried to create a log file so show an error if appropriate and bail.
            {
                HRESULT hrOriginal = hr;

                hr = HRESULT_FROM_WIN32(ERROR_INSTALL_LOG_FAILURE);
                SplashScreenDisplayError(display, wzBundleName, hr);

                ExitOnFailure1(hrOriginal, "Failed to open log: %ls", pLog->sczPath);
            }
        }
        else
        {
            pLog->state = BURN_LOGGING_STATE_OPEN;
        }
    }
    else if (pLog->sczPrefix && *pLog->sczPrefix)
    {
        hr = GetNonSessionSpecificTempFolder(&sczLoggingBaseFolder);
        ExitOnFailure(hr, "Failed to get non-session specific TEMP folder.");

        // Best effort to open default logging.
        hr = LogOpen(sczLoggingBaseFolder, pLog->sczPrefix, NULL, pLog->sczExtension, FALSE, FALSE, &pLog->sczPath);
        if (FAILED(hr))
        {
            LogDisable();
            pLog->state = BURN_LOGGING_STATE_DISABLED;

            hr = S_OK;
        }
        else
        {
            pLog->state = BURN_LOGGING_STATE_OPEN;
        }
    }
    else // no logging enabled.
    {
        LogDisable();
        pLog->state = BURN_LOGGING_STATE_DISABLED;
    }

    // If the log was opened, write the header info and update the prefix and extension to match
    // the log name so future logs are opened with the same pattern.
    if (BURN_LOGGING_STATE_OPEN == pLog->state)
    {
        LPCWSTR wzExtension = PathExtension(pLog->sczPath);
        if (wzExtension && *wzExtension)
        {
            hr = StrAllocString(&pLog->sczPrefix, pLog->sczPath, wzExtension - pLog->sczPath);
            ExitOnFailure(hr, "Failed to copy log path to prefix.");

            hr = StrAllocString(&pLog->sczExtension, wzExtension + 1, 0);
            ExitOnFailure(hr, "Failed to copy log extension to extension.");
        }
        else
        {
            hr = StrAllocString(&pLog->sczPrefix, pLog->sczPath, 0);
            ExitOnFailure(hr, "Failed to copy full log path to prefix.");
        }

        if (pLog->sczPathVariable && *pLog->sczPathVariable)
        {
            VariableSetString(pVariables, pLog->sczPathVariable, pLog->sczPath, FALSE); // Ignore failure.
        }
    }

LExit:
    ReleaseStr(sczLoggingBaseFolder);

    return hr;
}
int main(int argc, char** argv)
{
    const char *transFilePath = TIO_DEFAULT_TRANSLATION_FILE_PATH;
    unsigned refreshDelay = 0;   /* in seconds, 0 = disabled */
    const char *logFilePath = 0;
    /* 
     * syslog isn't installed on the target so it's disabled in this program
     * by requiring an argument to -o|--log.
     */ 
    int logToSyslog = 0;
    unsigned short sioPort = 0;  /* 0 means use Unix socket */
    unsigned short tioPort = 0;
    int daemonFlag = 0;
    int verboseFlag = 0;
    unsigned short mapSize = MAX_MSG_MAP_SIZE;

    /* allocate memory for progName since basename() modifies it */
    const size_t nameLen = strlen(argv[0]) + 1;
    char arg0[nameLen];
    memcpy(arg0, argv[0], nameLen);
    progName = basename(arg0);

    while (1) {
        static struct option longOptions[] = {
            { "daemon",     no_argument,       0, 'd' },
            { "file",       required_argument, 0, 'f' },
            { "map-size",   optional_argument, 0, 'm' },
            { "refresh",    optional_argument, 0, 'r' },
            { "sio_port",   optional_argument, 0, 's' },
            { "tio_port",   optional_argument, 0, 't' },
            { "verbose",    no_argument,       0, 'v' },
            { "help",       no_argument,       0, 'h' },
            { 0,            0, 0,  0  }
        };
        int c = getopt_long(argc, argv, "df:m:r::s::t::vh?", longOptions, 0);

        if (c == -1) {
            break;  // no more options to process
        }

        switch (c) {
        case 'd':
            daemonFlag = 1;
            break;

        case 'f':
            transFilePath = optarg;
            break;

        case 'm':
            mapSize = (optarg == 0) ? MAX_MSG_MAP_SIZE : atoi(optarg);
            break;

        case 'r':
            refreshDelay = (optarg == 0) ? DEFAULT_REFRESH_DELAY : atoi(optarg);
            break;

        case 's':
            sioPort = (optarg == 0) ? SIO_DEFAULT_AGENT_PORT : atoi(optarg);
            break;

        case 't':
            tioPort = (optarg == 0) ? TIO_DEFAULT_AGENT_PORT : atoi(optarg);
            break;

        case 'v':
            verboseFlag = 1;
            break;

        case 'h':
        case '?':
        default:
            tioDumpHelp();
            exit(1);
        }
    }

    /* set up logging to syslog or file; will be STDERR not told otherwise */
    LogOpen(progName, logToSyslog, logFilePath, verboseFlag);

    /* keep STDIO going for now */
    if (daemonFlag) {
        if (daemon(0, 1) != 0) {
            dieWithSystemMessage("daemon() failed");
        }
    }

    tioAgent(transFilePath, refreshDelay, tioPort, TIO_AGENT_UNIX_SOCKET,
        sioPort, SIO_AGENT_UNIX_SOCKET, mapSize);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 13
0
// 990525 RS, get the log's raw filesize and log type
__int64 GetLogFileType( char *filename, long *type, long *date1, long *date2, LogSubFormat* logSubFormat/*=0*/ )
{
	DEF_ASSERT(type);

	// If its a URL or some external link, then dont get the info since its too slow
	// accept it as is.
	if ( strstr( filename, "ftp://" ) ||
		 strstr( filename, "http://" ) ||
		 IsFileaFolder( filename ) ||
		 IsURLShortCut( filename )
		){
		if ( date1 && date2 )
			*date1 = *date2 = *type = 0;
		return 0;
	}

	time_t logDays;
	__int64 fileSize;
	CQV5Database::Type v5DBType;

	if( CQV5Database::isV5Database( filename, &logDays, &fileSize, &v5DBType ) )
	{
		*type=LOGFORMAT_V5DATABASE;

		if( date1 )
		{
			*date1=logDays;
		}

		if( logSubFormat )
		{
			*logSubFormat=v5DBType==CQV5Database::Web ? LOGSUBFORMAT_V5DATABASE_WEB : LOGSUBFORMAT_V5DATABASE_STREAMING;
		}

		return fileSize;
	}

	if( logSubFormat )
	{
		*logSubFormat=LOGSUBFORMAT_UNKNOWN;
	}

	long fp=LogOpen( filename, &fileSize );

	if ( fp )
	{
		HitDataRec		Line;
		memset( &Line, 0, sizeof( HitDataRec ) );
		LogGetFormat( fp , &Line, filename );
		LogClose( fp, filename );

		if ( date1 && date2 )
		{
			struct tm		logDate;
			
			*date1 = *date2 = 0;
			if ( Line.date ){
				StringToDaysDate( Line.date, &logDate, 0);
				StringToDaysTime( Line.time, &logDate);
				Date2Days( &logDate, &logDays );
				*date1 = logDays;
			}
			if ( Line.vhost ){
				if ( Line.vhost[0] != '-' )
					logType |= FWA_VHOST_LOG_MASK;					
			}

		}
		*type = logType;
		logType = LOGFORMAT_UNKNOWN;
		return fileSize;
	}
	return -1;
}