void main(int argc, char* argv[])
{
	bool verbose=false;
	WORD deviceno=0;
	int i;
	
	HCLL_Template clt;
	clt.setOptionPrefix("-");
	clt.addOption("-debug", 0);	// Debug
	clt.addOption("-h", 0);		// Help
	clt.addOption("-v", 0);		// Be verbose
	clt.addOption("-nt", 0);	// Do not print program title
	clt.addOption("-t", 0);	    // Print program title
	clt.addOption("-d", 1);		// Dump banks to batfile
	clt.addOption("-dist", 1);	// Dump banks to batfile (distribution), Use filename only, not full path
	clt.addOption("-distm", 1);	// Dump banks to batfile (distribution), Use filename only, not full path, adds mediaplayer
//	clt.addOption("-bank0", 0);	// Include bank 0 when creating batfile
	clt.addOption("-c", 1);		// Clear one bank
	clt.addOption("-C", 0);		// Clear all banks
//	clt.addOption("-CA", 0);	// Clear all banks, including bank 0 (Default MIDI bank)
	clt.addOption("-n", 1);		// Set device number (for multiple devices)
	clt.addOption("-i", 0);		// Print a lot of info
	clt.addOption("-l", 0);		// List active soundfont names
	clt.addOption("-L", 0);		// List active soundfont names, including path names
	clt.addOption("-fx", 3);	// Load effect <type> <variation> <value>
	clt.addOption("-ea", 0);	// List all Synthesizer emulations
	clt.addOption("-es", 1);	// Set Synthesizer emulation
	clt.addOption("-ec", 0);	// List current Synthesizer emulation
	clt.addOption("-p", 1);		// list preset names for <bank>
	clt.addOption("-wl", 3);	// Load <wavefile> into <preset> in <bank>
	clt.addOption("-wc", 2);	// Clear wavefile loaded in <preset> in <bank>
	clt.addOption("-pl", 5);	// Load <sourcepreset> from <sourcebank> in <soundfont> into <destpreset> in <destbank>
	clt.addOption("-pc", 2);	// Clear <preset> in <bank>
	
	HCLL_CommandLine cl;
	cl.setTemplate(clt);
	HCLL_Result cl_res;
	cl_res=cl.parse(argc, argv);
	if (cl_res!=HCLL_RESULT_OK)
	{
		cout<<"Parse error: ";

		switch (cl_res)
		{
		case HCLL_RESULT_ERROR_TOO_FEW_OPTION_PARAMS :
			cout<<"too few parameters to the '"<<cl.getLastOptionParsed()<<"' option\n";
			break;
		case HCLL_RESULT_ERROR_UNRECOGNIZED_OPTION:
			cout<<"unrecognized option '"<<cl.getLastOptionParsed()<<"'\n";;
			break;
		default:
			cout<<"unknown error\n";
			break;
		};
		printf("SF2LOAD v2.2 (c) 1998-1999 Thomas Hammer  [email protected]\n");
		printf("                 http://listen.to/HammerSound\n");
		printf("\n");
		cout<<"usage:  SF2LOAD  [<options>] [<bank number> <soundfont name>] \n\n";
		cout<<"        SF2LOAD -h for help\n";
		return;
	}

	if (!cl.optionExists("-nt"))
	{
		printf("SF2LOAD v2.2 (c) 1998-1999 Thomas Hammer  [email protected]\n");
		printf("                 http://listen.to/HammerSound\n");
		printf("\n");
	};

	if (cl.optionExists("-v"))
	{
		verbose=true;
		cout <<"Verbose mode on\n";
	}

	if (cl.optionExists("-debug"))
	{
		if (verbose)
			cout<<"debug mode on\n";
		cl.dump();
		cout<<"Path: '"<<argv[0]<<"'"<<endl;
	}

	if (   ((cl.getNumOptions()==0) && (cl.getNumProgParams()==1))
		|| ((cl.getNumProgParams()==2) || (cl.getNumProgParams()>3))
		)
	{
		cout<<"usage:  SF2LOAD  [<option>] [<bank number> <soundfont name>] \n";
		cout<<"        SF2LOAD -h for help\n";
		return;
	}

	if (cl.optionExists("-h")) 
	{
		cout<<"usage:  SF2LOAD  [<option>] [<bank number> <soundfont filename>] \n\n";
		cout<<"-h                Help"<<endl;
		cout<<"-d <filename>     Create a bat-file for loading all soundfonts currently"<<endl;
		cout<<"                  in memory. Use full pathnames."<<endl;
		cout<<"-dist <filename>  Create a bat-file for loading all soundfonts currently"<<endl;
		cout<<"                  in memory. Use filenames only (suitable for distribution)"<<endl;
		cout<<"-distm <filename> Create a bat-file (filename.bat) for loading all soundfonts"<<endl;
		cout<<"                  in memory. Use filenames only and include a line to"<<endl;
		cout<<"                  play the MIDI file (filename.mid) using mediaplayer"<<endl;
//		cout<<"-bank0            Include bank 0 (Default MIDI bank) when creating bat-files"<<endl;
		cout<<"-c <bank>         Clear the specified soundbank (remove it from memory)"<<endl;
		cout<<"-C                Clear all soundbanks currently in memory"<<endl;
//		cout<<"-CA               Clear all soundbanks currently in memory (incl. bank 0)"<<endl;
		cout<<"-n <device>       Set SoundFont device number (for users with multiple devices)"<<endl;
		cout<<"-l                List all soundfonts currently in memory"<<endl;
		cout<<"-L                List all soundfonts currently in memory (with filenames)"<<endl;
		cout<<"-p <bankno>       List all (melodic) presets in bank"<<endl;
		cout<<"-wl <wavefile> <bank> <preset>"<<endl;
		cout<<"                  Load a wavefile (*.wav) into a preset in a bank."<<endl;
		cout<<"-wc <bank> <preset> Clear a waveform previously loaded into a preset in a bank"<<endl;
		cout<<"-pl <soundfont> <sourcebank> <sourcepreset> <destbank> <destpreset>"<<endl;
		cout<<"                  Load a preset from a soundfont into a preset in a bank"<<endl;
		cout<<"-pc <bank> <preset> Clear a preset in a bank"<<endl;
		cout<<"-ea               List all synthesizer emulations"<<endl;
		cout<<"-es <no>          Set synthesizer emulation"<<endl;
		cout<<"-ec               List current synthesizer emulation"<<endl;
		cout<<"-i                Print information about the SoundFont device"<<endl;
		cout<<"-v                Enable verbose mode"<<endl;
		cout<<"-nt               Do not print the program title"<<endl;
		cout<<"-t                Print the program title"<<endl;
		return;
	}


	if (cl.optionExists("-n"))
	{
		deviceno=cl.getOptionParam("-n",0).getInt();
		if (verbose)
			cout<<"deviceno set to "<<deviceno<<endl;
	}

	// Open the SoundFont Manager

	OSC_SFManager sfm;
	OSC_ERR res;

	res = sfm.Init();
	if (res!=OSC_ERR_OK)
	{
		cout<<"Error initializing the SoundFont Manager : "<<sfm.GetLastSFManErrorText()<<endl;
		cout<<"Make sure you have installed the SoundFont Manager, and that you use the latest drivers"<<endl;
		cout<<"for your SoundFont device"<<endl;
		return;
	}
	else
		if (verbose)
			cout<<"SoundFont Manager Initialized OK"<<endl;

	res = sfm.Open(deviceno);
	if (res!=OSC_ERR_OK)
	{
		cout<<"Error trying to open SoundFont device number "<<deviceno
			<<". "<<sfm.GetLastSFManErrorText()<<endl;
		return;
	};

//// -c
	if (cl.optionExists("-c"))
	{
		long bankno = cl.getOptionParam("-c",0).getInt();
		if (verbose)
			cout<<"Clearing SoundBank "<<bankno<<endl;
		if ( (bankno<0) || (bankno>127) )
		{
			cout<<"Error: Bank number out of range. The banknumber specified is "<<bankno<<", it should be in the range [0..127]\n";
		}
		else 
		{
			if (sfm.IsMIDIBankUsed(bankno)==-1)
				cout<<"Error: Bank number "<<bankno<<" is not in use and can not be cleared"<<endl;
			else if (sfm.IsMIDIBankUsed(bankno) != bankno)
				cout<<"Error: Bank number "<<bankno<<" is owned by bank "<<sfm.IsMIDIBankUsed(bankno)
				<<" and can not be cleared"<<endl;
			else
			{
				if ( (res=sfm.ClearLoadedBank(bankno)) != OSC_ERR_OK)
					cout<<"Error: Couldn't clear bank number "<<bankno<<". "<<sfm.GetLastSFManErrorText()<<endl;
				else
					if (verbose)
						cout<<"Bank number "<<bankno<<" has been cleared successfully\n";
			};
		};
	};

//// -es
	if (cl.optionExists("-es"))
	{
		// This function will set the current synthesizer emulation, but this 
		// only lasts until the device is closed (at the end of sf2load)
		// so it's really not much point in using it... :-(
		if (verbose)
			cout<<"Setting current Synthesizer Emulation..."<<endl;
		int index = cl.getOptionParam("-es",0).getInt();
		if ( (res=sfm.SelectSynthEmulation(index)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't set Synthesizer Emulation. "<<sfm.GetLastSFManErrorText()<<endl;
		else
			if (verbose)
				cout<<"Current Synthesizer Emulation has been set to "<<index<<endl;
	}

//// -ea
	if (cl.optionExists("-ea"))
	{
		if (verbose)
			cout<<"Listing all Synthesizer Emulations..."<<endl;
		OSC_StringArray list;
		if ( (res=sfm.GetAllSynthEmulations(list)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't list Synthesizer Emulations. "<<sfm.GetLastSFManErrorText()<<endl;
		else
		{
			int n=0;
			for (OSC_StringArray::iterator i = list.begin(); i!=list.end(); i++)
			{
				cout<<n++<<" "<<*i<<endl;
			}
		};
	}

//// -ec
	if (cl.optionExists("-ec"))
	{
		if (verbose)
			cout<<"Listing current Synthesizer Emulation..."<<endl;
		std::string name;
		int index;
		if ( (res=sfm.GetSynthEmulation(index, name)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't list Synthesizer Emulation. "<<sfm.GetLastSFManErrorText()<<endl;
		else
		{
			cout<<index<<" "<<name<<endl;
		};
	}

//// -wl
	if (cl.optionExists("-wl"))
	{
		std::string filename = cl.getOptionParam("-wl",0).getString();
		int bank = cl.getOptionParam("-wl",1).getInt();
		int preset = cl.getOptionParam("-wl",2).getInt();
		if (verbose)
			cout<<"Loading waveform '"<<filename<<"' into bank "<<bank<<", preset "<<preset<<endl;

		if ( (res=sfm.LoadWaveform(bank, preset, filename)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't load waveform. "<<sfm.GetLastSFManErrorText()<<endl;
	}

//// -wc
	if (cl.optionExists("-wc"))
	{
		int bank = cl.getOptionParam("-wc",0).getInt();
		int preset = cl.getOptionParam("-wc",1).getInt();
		if (verbose)
			cout<<"Clearing waveform from bank "<<bank<<", preset "<<preset<<endl;

		if ( (res=sfm.ClearLoadedWaveform(bank, preset)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't clear waveform. "<<sfm.GetLastSFManErrorText()<<endl;
	}

//// -pl
	if (cl.optionExists("-pl"))
	{
		std::string filename = cl.getOptionParam("-pl",0).getString();
		int sourcebank = cl.getOptionParam("-pl",1).getInt();
		int sourcepreset = cl.getOptionParam("-pl",2).getInt();
		int destbank = cl.getOptionParam("-pl",3).getInt();
		int destpreset = cl.getOptionParam("-pl",4).getInt();
		if (verbose)
			cout<<"Loading from soundfont '"<<filename<<"', bank "<<sourcebank<<", preset "<<sourcepreset
				<<", into bank "<<destbank<<", preset "<<destpreset<<endl;

		if ( (res=sfm.LoadPreset(sourcebank, sourcepreset, destbank, destpreset, filename)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't load preset. "<<sfm.GetLastSFManErrorText()<<endl;
	}

//// -pc
	if (cl.optionExists("-pc"))
	{
		int bank = cl.getOptionParam("-pc",0).getInt();
		int preset = cl.getOptionParam("-pc",1).getInt();
		if (verbose)
			cout<<"Clearing preset from bank "<<bank<<", preset "<<preset<<endl;

		if ( (res=sfm.ClearLoadedPreset(bank, preset)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't clear preset. "<<sfm.GetLastSFManErrorText()<<endl;
	}

//// -C
	if (cl.optionExists("-C"))
	{
		if (verbose)
			cout<<"Clearing all SoundBanks...";
		if ( (res=sfm.ClearAllLoadedBanks()) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't clear banks. "<<sfm.GetLastSFManErrorText()<<endl;
		else
			if (verbose)
				cout<<"All Soundbanks have been cleared successfully\n";
	}

/*
//// -CA
	if (cl.optionExists("-CA"))
	{
		if (verbose)
			cout<<"Clearing all SoundBanks (including bank 0)...";
		if ( (res=sfm.ClearAllLoadedBanks(true)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't clear banks. "<<sfm.GetLastSFManErrorText()<<endl;
		else
			if (verbose)
				cout<<"All Soundbanks have been cleared successfully\n";
	}
*/

//// -l | -L
	if (cl.optionExists("-l") || cl.optionExists("-L"))
	{
		if (verbose)
			cout<<"Listing SoundBanks\n";
		string name;
		string filename;

		for (i=0; i<128; i++)
		{
			if (sfm.IsMIDIBankUsed(i)==i)
			{
				if ( (res=sfm.GetLoadedBankDescriptor(i, name)) != OSC_ERR_OK)
					break;
				else
				{
					cout<<"[";
					if (i<100)
						cout<<" ";
					if (i<10)
						cout<<" ";
					cout<<i<<"] "<<name;
					if (cl.optionExists("-L"))
					{
						if ( (sfm.GetLoadedBankPathname(i, filename)) != OSC_ERR_OK)
							;
						else
							cout<<" ("<<filename<<")";
					}
					cout<<endl;
				};
			}
		};
		if (res!=OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't get bank name (bank "<<i<<"). "<<sfm.GetLastSFManErrorText()<<endl;
	};

//// -i
	if (cl.optionExists("-i"))
	{
		int numdevices = sfm.GetNumDevs();
		if (numdevices==0)
			cout<<"There are no SoundFont devices installed on this computer\n";
		else if (numdevices==1)
			cout<<"There is 1 SoundFont device installed on this computer\n";
		else
			cout<<"There are "<<numdevices<<" SoundFont devices installed on this computer\n";

		CSFCapsObject caps;
		int olddev;
		bool wasOpen = sfm.IsDeviceOpen();
		if (wasOpen)
		{
			olddev = sfm.GetCurrentOpenDevice();
			sfm.Close();
		}

		for (i=0; i<sfm.GetNumDevs(); i++)
		{
			cout<<"   ["<<i<<"] ";
			if (sfm.IsDeviceFree(i))
				cout<<"(free) ";
			else
				cout<<"(busy) ";
			if ( (res=sfm.Open(i)) != OSC_ERR_OK)
			{
				cout<<endl<<"Error: Couldn't open device "<<i<<". "<<sfm.GetLastSFManErrorText()<<endl;
				break;
			}
			if ( (res=sfm.GetDevCaps(&caps)) != OSC_ERR_OK)
			{
				cout<<endl<<"Error: Couldn't get device capabilities. "<<sfm.GetLastSFManErrorText()<<endl;
				break;
			};
			cout <<caps.m_DevName<<endl;
			sfm.Close();
		};

		if (wasOpen)
			if ( (res=sfm.Open(olddev)) != OSC_ERR_OK)
			{
				cout<<endl<<"Error: Couldn't open device "<<i<<". "<<sfm.GetLastSFManErrorText()<<endl;
			}

		if ( (res=sfm.GetDevCaps(&caps)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't get device capabilities. "<<sfm.GetLastSFManErrorText()<<endl;
		else
		{
			cout<<"The following information is for device "<<deviceno<<endl;
			cout<<"   Device name: "<<caps.m_DevName<<"    "
				<<"Device Manager: "<<caps.m_DevMgrName<<" ("<<caps.m_DevMgrEntry<<")"<<endl;

			if (caps.m_DevCaps & SFMANCAP_DYNAMIC_MEM_CAP)
				cout<<"   The device uses System Ram to store samples. ";
			else
				cout<<"   The device uses Dedicated Ram to store samples. ";

			int max, avail;
			sfm.QueryStaticSampleMemorySize(max, avail);
			cout<<std::setiosflags(ios::fixed)<<std::setprecision(1)
				<<"Available: "<<(double)avail/(1024.0*1024.0)<<"MB, "
				<<"Max: "<<(double)max/(1024.0*1024.0)<<"MB"<<endl;

			if (caps.m_DevCaps & SFMANCAP_SOFTWARE_SYNTH_CAP)
				cout<<"   The device has a Software Synth engine"<<endl;
			else
				cout<<"   The device has a Hardware Synth engine"<<endl;

			// rom id, rom version
			// synth emulations
		};
	};


//// -d, -dist, -distm
	// Create bat-file
	if (cl.optionExists("-d") || cl.optionExists("-dist") || cl.optionExists("-distm"))
	{	
		if (verbose)
			cout<<"Bat file creation\n";
		
		FILE *file;
		string batfilename;
		string midifilename;
		if (cl.optionExists("-d"))
			batfilename=cl.getOptionParam("-d",0).getString();
		else if (cl.optionExists("-dist"))
			batfilename=cl.getOptionParam("-dist",0).getString();
		else
			batfilename=cl.getOptionParam("-distm",0).getString();
		midifilename=batfilename;

		char fname[_MAX_FNAME];
		char ext[_MAX_EXT];
		char drive[_MAX_DRIVE];
		char dir[_MAX_DIR];
		char tmp[_MAX_PATH];
		_splitpath(batfilename.c_str(), drive, dir, fname, ext);
		_makepath(tmp, drive, dir, fname, ".bat");
		batfilename=string(tmp);
		_makepath(tmp, drive, dir, fname, ".mid");
		midifilename=string(tmp);


		file=fopen(batfilename.c_str(), "wt");
		if (file==NULL)
		{
			cout<<"Error: Couldn't open file '"<<batfilename.c_str()<<"' for writing";
		}
		else
		{
		
			if (verbose)
			{
				printf("Creating SF2LOAD compatible .bat file (%s) with the folowing soundfonts :\n", batfilename.c_str());
			};

			time_t ltime;
			_tzset();
			char timestr[128];
			time( &ltime );
			sprintf(timestr,"%s", ctime( &ltime ));
			timestr[24]=0;
	//		timestr[23]=0;
	//		if (strlen(timestr)>2)
	//			timestr[strlen(timestr)-3];

			fprintf(file,"@ECHO OFF\n");
			fprintf(file, "REM This bat file was created at %s by SF2LOAD v2.2\n", timestr);
			fprintf(file, "REM      SF2LOAD is (c) 1998-1999 Thomas Hammer  [email protected]\n");
			fprintf(file, "REM                 http://listen.to/HammerSound\n");
			fprintf(file,"\n");
			fprintf(file, "sf2load -t\n");
			fprintf(file,"\n");
			fprintf(file,"ECHO Clearing all User Banks\n");
			if (cl.optionExists("-bank0"))
				fprintf(file, "sf2load -nt -CA\n");
			else
				fprintf(file, "sf2load -nt -C\n");
			fprintf(file,"\n");
			fprintf(file,"ECHO \xff\n");

			// Load soundfonts
			fprintf(file,"ECHO Loading SoundFonts\n");

			string filename;
			int start;
//			start = cl.optionExists("-bank0") ? 0 : 1;
			start = 1;
			for (i=start; i<=127; i++)
			{
				if (sfm.IsMIDIBankUsed(i)==i)
				{
					if ( (res=sfm.GetLoadedBankPathname(i, filename)) != OSC_ERR_OK)
						break;

					if (cl.optionExists("-dist") || cl.optionExists("-distm")) // use filename only
					{
					   char fname[_MAX_FNAME];
					   char ext[_MAX_EXT];
					   _splitpath(filename.c_str(), NULL, NULL, fname, ext);
					   filename=string(fname)+string(ext);
					}
					fprintf(file, "sf2load -nt %3d \"%s\"\n", i, filename.c_str());
				}
				if (verbose)
					cout<<i<<"  "<<filename<<endl;
			};

			if (res==OSC_ERR_OK)
			{
				fprintf(file,"ECHO \xff\n");
				cout<<"Created-bat file '"<<batfilename<<"'"<<endl;

				if (cl.optionExists("-distm")) 
				{
		//			string midifilename=cl.getOptionParam("-distm",1).getString();
					fprintf(file,"ECHO Starting MediaPlayer for playing MIDI file %s\n", midifilename.c_str());
					fprintf(file,"start mplayer.exe %s\n", midifilename.c_str());
					fprintf(file,"ECHO \xff\n");
				};
			}

			fclose(file);
			
			if (res!=OSC_ERR_OK)
			{
				cout<<"Error creating .bat file. "<<sfm.GetLastSFManErrorText()<<endl;
			}
		};
	}

	if (cl.optionExists("-p"))
	{
		// print all preset names for <bank>
		int bank = cl.getOptionParam("-p",0).getInt();
		if (sfm.IsMIDIBankUsed(bank)!=bank)
			cout<<"<empty bank>"<<endl;
		else
		{
			std::string bankname;
			sfm.GetLoadedBankDescriptor(bank, bankname);
	//		cout<<"Melodic Presets for SoundFont: [";
			cout<<bankname<<endl<<endl;

			std::string presetname;
			for (int i=0; i<128; i++)
			{
				sfm.GetLoadedPresetDescriptor(bank, i, presetname);
				if (!presetname.empty())
				{
					cout<<"[";
					if (i<100)
						cout<<" ";
					if (i<10)
						cout<<" ";
					cout<<i<<"] "<<presetname<<endl;
				};
			}
		};
	}

	if (cl.getNumProgParams()==3)
	{
		if (verbose)
			cout<<"Loading SoundFont\n";
		//  we're supposed to load a bank

		// append .sf2 if needed
	   char fname[_MAX_FNAME];
	   char ext[_MAX_EXT];
	   string path=cl.getProgParam(2).getString();
	   _splitpath(path.c_str(), NULL, NULL, fname, ext);
	   if (ext[0]==0)
		   path+=string(".sf2");

		// make full path
		char fullpath[_MAX_PATH];
		if ( _fullpath( fullpath, path.c_str(), _MAX_PATH ) == NULL )
			cout<<"Error: Invalid SoundFont filename '"<<cl.getProgParam(2).getString()<<"'"<<endl;

		// load soundfont
		if ( (res=sfm.LoadBank(cl.getProgParam(1).getInt(), fullpath)) != OSC_ERR_OK)
				cout<<"Error: Couldn't load bank "<<cl.getProgParam(1).getInt()<<". "<<sfm.GetLastSFManErrorText()<<endl;
		else
			printf("[%3d]  %s\n", cl.getProgParam(1).getInt(), fullpath);

	};

	// Close the SoundFont Manager

	if ( (res=sfm.Close()) != OSC_ERR_OK)
		cout<<endl<<"Error: Couldn't close device. "<<sfm.GetLastSFManErrorText()<<endl;
	else
		if (verbose)
			cout<<"Device closed\n";
};
Beispiel #2
0
Timezone::Timezone() : _offset(0),_dstOffset(3600000) {
#if defined(_WIN32)
	/// GET LOCAL INFOS

	_tzset();

	//// LOAD default values ////////////////////////

	DYNAMIC_TIME_ZONE_INFORMATION	timezoneInfo;
	DWORD result = GetDynamicTimeZoneInformation(&timezoneInfo);
	_offset=(-(Int32)timezoneInfo.Bias*60000);
	if (result != TIME_ZONE_ID_UNKNOWN)
		_dstOffset = (-(Int32)timezoneInfo.DaylightBias*60000);
	_dstOffset += _offset;

	fillDefaultTransitionRule(timezoneInfo.DaylightDate,_offset,_dstOffset,true,_StartDST);
	fillDefaultTransitionRule(timezoneInfo.StandardDate,_offset,_dstOffset,false,_EndDST);

	int size(sizeof(timezoneInfo.TimeZoneKeyName));
	_name.resize(size);
	if ((size = WideCharToMultiByte(CP_ACP, 0, timezoneInfo.TimeZoneKeyName, -1, (char*)_name.data(), _name.size(), NULL, NULL)) > 0) {
		_name.resize(size-1);

		static const map<string, const char*> WindowToTZID ({
			{ "AUS Central Standard Time", "Australia/Darwin" },
			{ "AUS Eastern Standard Time", "Australia/Sydney" },
			{ "Afghanistan Standard Time", "Asia/Kabul" },
			{ "Alaskan Standard Time", "America/Anchorage" },
			{ "Arab Standard Time", "Asia/Riyadh" },
			{ "Arabian Standard Time", "Asia/Dubai" },
			{ "Arabic Standard Time", "Asia/Baghdad" },
			{ "Argentina Standard Time", "America/Buenos_Aires" },
			{ "Atlantic Standard Time", "America/Halifax" },
			{ "Azerbaijan Standard Time", "Asia/Baku" },
			{ "Azores Standard Time", "Atlantic/Azores" },
			{ "Bahia Standard Time", "America/Bahia" },
			{ "Bangladesh Standard Time", "Asia/Dhaka" },
			{ "Canada Central Standard Time", "America/Regina" },
			{ "Cape Verde Standard Time", "Atlantic/Cape_Verde" },
			{ "Caucasus Standard Time", "Asia/Yerevan" },
			{ "Cen. Australia Standard Time", "Australia/Adelaide" },
			{ "Central America Standard Time", "America/Guatemala" },
			{ "Central Asia Standard Time", "Asia/Almaty" },
			{ "Central Brazilian Standard Time", "America/Cuiaba" },
			{ "Central Europe Standard Time", "Europe/Budapest" },
			{ "Central European Standard Time", "Europe/Warsaw" },
			{ "Central Pacific Standard Time", "Pacific/Guadalcanal" },
			{ "Central Standard Time", "America/Chicago" },
			{ "China Standard Time", "Asia/Shanghai" },
			{ "Dateline Standard Time", "Etc/GMT+12" },
			{ "E. Africa Standard Time", "Africa/Nairobi" },
			{ "E. Australia Standard Time", "Australia/Brisbane" },
			{ "E. Europe Standard Time", "Asia/Nicosia" },
			{ "E. South America Standard Time", "America/Sao_Paulo" },
			{ "Eastern Standard Time", "America/New_York" },
			{ "Egypt Standard Time", "Africa/Cairo" },
			{ "Ekaterinburg Standard Time", "Asia/Yekaterinburg" },
			{ "FLE Standard Time", "Europe/Kiev" },
			{ "Fiji Standard Time", "Pacific/Fiji" },
			{ "GMT Standard Time", "Europe/London" },
			{ "GTB Standard Time", "Europe/Bucharest" },
			{ "Georgian Standard Time", "Asia/Tbilisi" },
			{ "Greenland Standard Time", "America/Godthab" },
			{ "Greenwich Standard Time", "Atlantic/Reykjavik" },
			{ "Hawaiian Standard Time", "Pacific/Honolulu" },
			{ "India Standard Time", "Asia/Calcutta" },
			{ "Iran Standard Time", "Asia/Tehran" },
			{ "Israel Standard Time", "Asia/Jerusalem" },
			{ "Jordan Standard Time", "Asia/Amman" },
			{ "Kaliningrad Standard Time", "Europe/Kaliningrad" },
			{ "Korea Standard Time", "Asia/Seoul" },
			{ "Libya Standard Time", "Africa/Tripoli" },
			{ "Magadan Standard Time", "Asia/Magadan" },
			{ "Mauritius Standard Time", "Indian/Mauritius" },
			{ "Mauritius Standard Time", "Indian/Reunion" },
			{ "Middle East Standard Time", "Asia/Beirut" },
			{ "Montevideo Standard Time", "America/Montevideo" },
			{ "Morocco Standard Time", "Africa/Casablanca" },
			{ "Mountain Standard Time", "America/Denver" },
			{ "Myanmar Standard Time", "Asia/Rangoon" },
			{ "N. Central Asia Standard Time", "Asia/Novosibirsk" },
			{ "Namibia Standard Time", "Africa/Windhoek" },
			{ "Nepal Standard Time", "Asia/Katmandu" },
			{ "New Zealand Standard Time", "Pacific/Auckland" },
			{ "Newfoundland Standard Time", "America/St_Johns" },
			{ "North Asia East Standard Time", "Asia/Irkutsk" },
			{ "North Asia Standard Time", "Asia/Krasnoyarsk" },
			{ "Pacific SA Standard Time", "America/Santiago" },
			{ "Pacific Standard Time", "America/Los_Angeles" },
			{ "Pakistan Standard Time", "Asia/Karachi" },
			{ "Paraguay Standard Time", "America/Asuncion" },
			{ "Romance Standard Time", "Europe/Paris" },
			{ "Russian Standard Time", "Europe/Moscow" },
			{ "SA Eastern Standard Time", "America/Cayenne" },
			{ "SA Pacific Standard Time", "America/Bogota" },
			{ "SA Western Standard Time", "America/La_Paz" },
			{ "SE Asia Standard Time", "Asia/Bangkok" },
			{ "Samoa Standard Time", "Pacific/Apia" },
			{ "Singapore Standard Time", "Asia/Singapore" },
			{ "South Africa Standard Time", "Africa/Johannesburg" },
			{ "Sri Lanka Standard Time", "Asia/Colombo" },
			{ "Syria Standard Time", "Asia/Damascus" },
			{ "Taipei Standard Time", "Asia/Taipei" },
			{ "Tasmania Standard Time", "Australia/Hobart" },
			{ "Tokyo Standard Time", "Asia/Tokyo" },
			{ "Tonga Standard Time", "Pacific/Tongatapu" },
			{ "Turkey Standard Time", "Europe/Istanbul" },
			{ "US Eastern Standard Time", "America/Indianapolis" },
			{ "US Mountain Standard Time", "America/Phoenix" },
			{ "UTC",	"Etc/GMT" },
			{ "UTC+12", "Etc/GMT-12" },
			{ "UTC-02", "Etc/GMT+2" },
			{ "UTC-11", "Etc/GMT+11" },
			{ "Ulaanbaatar Standard Time", "Asia/Ulaanbaatar" },
			{ "Venezuela Standard Time", "America/Caracas" },
			{ "Vladivostok Standard Time", "Asia/Vladivostok" },
			{ "W. Australia Standard Time", "Australia/Perth" },
			{ "W. Central Africa Standard Time", "Africa/Lagos" },
			{ "W. Europe Standard Time", "Europe/Berlin" },
			{ "West Asia Standard Time", "Asia/Tashkent" },
			{ "West Pacific Standard Time", "Pacific/Port_Moresby" },
			{ "Yakutsk Standard Time", "Asia/Yakutsk" },
		});


		auto& it = WindowToTZID.find(_name);
		if (it != WindowToTZID.end())
			_name.assign(it->second);
	} else
		_name.clear();
#else
   tzset();
   #if defined(_OS_BSD) // timezone not available on BSD
      std::time_t now = std::time(NULL);
      struct std::tm t;
      gmtime_r(&now, &t);
      _offset = now - std::mktime(&t);
   #else
      _offset = (-(Int32)timezone*1000);
   #endif
   _name.assign(tzname[0]);
   _dstOffset += _offset;
#endif


   if (_name.empty())
	   return; // no more TZ information available


	//// LOAD TZ database ////////////////////////
    string path;
   if(Util::Environment().getString("TZDIR",path)) {
	   FileSystem::MakeDirectory(path).append(_name);
	   if(readTZDatabase(path))
		   return;
   }

#if !defined(_WIN32)

    path.assign("/usr/lib/zoneinfo/").append(_name);
	if(readTZDatabase(path))
		return;

	path.assign("/usr/share/zoneinfo/").append(_name);
	if(readTZDatabase(path))
		return;

#endif

	if (FileSystem::GetCurrent(path)) {
		path.append("zoneinfo/").append(_name);
		if(readTZDatabase(path))
			return;
	}

	if (FileSystem::GetCurrentApplication(path)) {
		FileSystem::GetParent(path).append("zoneinfo/").append(_name);
		if(readTZDatabase(path))
			return;
	}

#if !defined(_WIN32)
	path.assign("/etc/localtime");
	readTZDatabase(path);
#endif

}
Beispiel #3
0
int _CRTAPI1
main(
    int argc,
    char *argv[],
    char *envp[]
    )
{

    char chChar, *pchChar;
    envp;
    _tzset();

    pgnIgnoreListHdr = (PGROUPNODE) malloc( sizeof ( GROUPNODE ) );
    pgnIgnoreListHdr->chName = NULL;
    pgnIgnoreListHdr->pgnNext = NULL;
    pgnIgnoreListEnd = pgnIgnoreListHdr;


    fVerbose = FALSE;
    fQuiet = FALSE;
    fGoingDown = FALSE;
    fSumOnly = FALSE;
    fRebaseSysfileOk = FALSE;
    fShowAllBases = FALSE;

    ImagesRoot[ 0 ] = '\0';
    SymbolPath[ 0 ] = '\0';

    if (argc <= 1) {
        ShowUsage();
        }

    while (--argc) {
        pchChar = *++argv;
        if (*pchChar == '/' || *pchChar == '-') {
            while (chChar = *++pchChar) {
                ParseSwitch( chChar, &argc, &argv );
                }
            }
        else {
            if ( !FindInIgnoreList( pchChar ) ) {
                ReBaseFile( pchChar, TRUE );
                }
            }
        }

    if ( !fQuiet ) {

        if ( BaseAddrFile ) {
            InitialBase = MinBase;
        }

        if ( fGoingDown ) {
            TotalSize = InitialBase - NewImageBase;
        }
        else {
            TotalSize = NewImageBase - InitialBase;
        }

        fprintf( stdout, "\n" );
        fprintf( stdout, "REBASE: Total Size of mapping 0x%08x\n", TotalSize );
        fprintf( stdout, "REBASE: Range 0x%08x -0x%08x\n",
                 min(NewImageBase, InitialBase), max(NewImageBase, InitialBase));

        if (RebaseLog) {
            fprintf( RebaseLog, "\nTotal Size of mapping 0x%08x\n", TotalSize );
            fprintf( RebaseLog, "Range 0x%08x -0x%08x\n\n",
                     min(NewImageBase, InitialBase), max(NewImageBase, InitialBase));
        }
    }

    if (RebaseLog) {
        fclose(RebaseLog);
        }

    if (BaseAddrFile){
        fclose(BaseAddrFile);
        }

    if (CoffBaseDotTxt){
        fclose(CoffBaseDotTxt);
        }

    return ReturnCode;
}
Beispiel #4
0
static void threadProc(PVOID params) {
  _putenv("TZ=UTC");
  _tzset();
  ExecuteTasks();
  addConsoleText(NORMAL, "%s", "Done!\n");
}
Beispiel #5
0
// returns the time zone in the C sense, i.e. the difference UTC - local
// (in seconds)
int wxGetTimeZone()
{
#ifdef WX_GMTOFF_IN_TM
    // set to true when the timezone is set
    static bool s_timezoneSet = false;
    static long gmtoffset = LONG_MAX; // invalid timezone

    // ensure that the timezone variable is set by calling wxLocaltime_r
    if ( !s_timezoneSet )
    {
        // just call wxLocaltime_r() instead of figuring out whether this
        // system supports tzset(), _tzset() or something else
        time_t t = time(NULL);
        struct tm tm;

        wxLocaltime_r(&t, &tm);
        s_timezoneSet = true;

        // note that GMT offset is the opposite of time zone and so to return
        // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
        // cases we have to negate it
        gmtoffset = -tm.tm_gmtoff;

        // this function is supposed to return the same value whether DST is
        // enabled or not, so we need to use an additional offset if DST is on
        // as tm_gmtoff already does include it
        if ( tm.tm_isdst )
            gmtoffset += 3600;
    }
    return (int)gmtoffset;
#elif defined(__WINE__)
    struct timeb tb;
    ftime(&tb);
    return tb.timezone*60;
#elif defined(__VISUALC__)
    // We must initialize the time zone information before using it (this will
    // be done only once internally).
    _tzset();

    // Starting with VC++ 8 timezone variable is deprecated and is not even
    // available in some standard library version so use the new function for
    // accessing it instead.
    #if wxCHECK_VISUALC_VERSION(8)
        long t;
        _get_timezone(&t);
        return t;
    #else // VC++ < 8
        return timezone;
    #endif
#else // Use some kind of time zone variable.
    // In any case we must initialize the time zone before using it.
    tzset();

    #if defined(WX_TIMEZONE) // If WX_TIMEZONE was defined by configure, use it.
        return WX_TIMEZONE;
    #elif defined(__BORLANDC__) || defined(__MINGW32__)
        return _timezone;
    #else // unknown platform -- assume it has timezone
        return timezone;
    #endif // different time zone variables
#endif // different ways to determine time zone
}
Beispiel #6
0
size_t
strftime(char *str, size_t maxsize, const char *fmt, const struct tm *ts)
{
        long	num = 0;
        long    len;
	int n;
	int year;
        char    q;
        char    buf[BIG_LEN], *putstr, *s;

        for(;;) {
                if (num >= maxsize) return 0;
                if ((q = *fmt++) == 0)  break;
                if (q != '%') {
                        *str++ = q;
                        num++;
                        continue;
                }
                if ((q = *fmt++) == 0) break;       /* get format command */

/* assume that sprintf will be used, with a variable length */
/* this is the most common case, so it saves us some coding to do it here */
                putstr = buf;

                switch(q) {
                  case 'A':
                  case 'a':
		  /*
		   * cases 'a' and 'b' are still wrong -
		   * in some locale short names do not have to be
		   * 3 characters wide - still works in North America.
		   */
	                if (ts->tm_wday < 0 || ts->tm_wday > 6)
			        putstr = "?";
			else
			        if ( 'A' == q)
				        putstr = _LC_Day_name[ts->tm_wday];
				else
				        sprintf(buf, "%-.3s",
						_LC_Day_name[ts->tm_wday]);
                        break;
                  case 'b':
                  case 'B':
                  case 'h':	/* same as 'b' */
	                if (ts->tm_mon < 0 || ts->tm_mon > 11)
			        putstr = "?";
			else
			        if ( 'B' == q)
				        putstr = _LC_Mth_name[ts->tm_mon];
				else
				        sprintf(buf, "%-.3s",
						_LC_Mth_name[ts->tm_mon]);
                        break;
                  case 'c':
			/* this format should be set in setlocale.c */
                        strftime(buf, sizeof buf, "%a %b %d %X %Y", ts);
                        break;
		  case 'd':
                        sprintf(buf, "%02d", ts->tm_mday);
                        break;
		  case 'D':	/* date as %m/%d/%y */
 		  case 'x':     /* locale preferred date; for C locale same as 'D' */
			strftime(buf, sizeof buf, "%m/%d/%y", ts);
			break;
		  case 'e':	/* day of month, blank padded */
			sprintf(buf, "%2d", ts->tm_mday);
			break;
		  case 'F':
		        sprintf(buf, "%04d-%02d-%02d", 1900+ts->tm_year, ts->tm_mon+1, ts->tm_mday);
			break;
		  case 'g':
		  case 'G':
		        isoweeknumber(ts, &year);
		        if (q == 'g') year = year % 100;
		        sprintf(buf, "%02d", year);
			break;
                  case 'H':
                        sprintf(buf, "%02d", ts->tm_hour);
                        break;
                  case 'I':
                        n = ts->tm_hour;
                        if (n == 0) n = 12;
			else if (n > 12) n -= 12;
                        sprintf(buf, "%02d", n);
                        break;
                  case 'j':
                        sprintf(buf, "%03d", ts->tm_yday + 1);
                        break;
                  case 'm':
                        sprintf(buf, "%02d", ts->tm_mon + 1);
                        break;
                  case 'M':
                        sprintf(buf, "%02d", ts->tm_min);
                        break;
		   case 'n':	/* same as \n */
			putstr = "\n";
			break;
                  case 'p':
			/*
			 * this is wrong - strings "AM', "PM" are
			 * locale dependent
			 */
                        putstr = (ts->tm_hour < 12) ? "AM" : "PM";
                        break;
		  case 'r':	/* time as %I:%M:%S %p */
			strftime(buf, sizeof buf, "%I:%M:%S %p", ts);
			break;
		  case 'R':	/* time as %H:%M */
			strftime(buf, sizeof buf, "%H:%M", ts);
			break;
                  case 'S':
                        sprintf(buf, "%02d", ts->tm_sec);
                        break;
		  case 't':	/* same as \t */
			putstr = "\t";
			break;
                  case 'T':
		  case 'X': /* locale dependent time form; for now, fix to C locale  */
                        sprintf(buf, "%02d:%02d:%02d", ts->tm_hour,
                                ts->tm_min, ts->tm_sec);
                        break;
		  case 'u':
		    	sprintf(buf, "%d", (ts->tm_wday == 0) ? 7 : ts->tm_wday);
                        break;
                  case 'U':  /* week of year - starting Sunday */
			sprintf(buf, "%02d", weeknumber(ts, 0));
                        break;
		  case 'V':
		        sprintf(buf, "%02d", isoweeknumber(ts, &year));
                        break;
		  case 'w':
		    	sprintf(buf, "%d", ts->tm_wday);
                        break;
                  case 'W': /* week of year - starting Monday */
			sprintf(buf, "%02d", weeknumber(ts, 1));
                        break;
                  case 'y':
                        sprintf(buf, "%02d", ts->tm_year % 100);
                        break;
		  case 'Y':
                        sprintf(buf, "%d", ts->tm_year + 1900);
                        break;
		  case 'z':
                        if (NULL != (s = getenv("TZ")))
			  {
			    int hh, mm;
			    char c='+';
			    _tzset();
			    hh = -_timezone;
			    if (hh < 0) {
			      c = '-';
			      hh = -hh;
			    }
			    mm = (hh/60)%60;
			    hh = hh/3600;
			    sprintf(buf, "%c%02d%02d", c, hh, mm);
			  }
			else
			  buf[0] = '\0'; /* empty string */
                        break;
                  case 'Z':
                        if (NULL != (s = getenv("TZ")))
			  {
			    _tzset();
			    if (ts->tm_isdst) {
			      strcpy(buf, _tzname[1]);
			    } else {
			      strcpy(buf, _tzname[0]);
			    }
			  }
			else
			  buf[0] = '\0'; /* empty string */
                        break;
                   case '%':
                        putstr = "%";
                        break;
		   default:
			buf[0] = q;
			buf[1] = 0;
			break;
                }

                if (num + (len = strlen(putstr)) >= maxsize)
                        return 0;

                num += len;
                while (--len >= 0)
                        *str++ = *putstr++;
        }
        *str = 0;
        return (size_t) num;
}
Beispiel #7
0
bool CDate::EncodeDate(
    const CString& DateString, 
    const CString& DateFormat, 
    struct tm& Result) {

  CString Date(DateString);
  
  static const char * Months[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
  static const char * WeekDays[] = {"Sun", "Mon","Tue","Wed","Thu","Fri","Sat"};
  static const char * Zones[] = {"UTC", "GMT", "EDT", "EST", "CDT", "CST", "MDT", "MST", "PDT", "PST"};
  static const int ZonesHoursSkew[] = {0, 0, 4, 5, 5, 6, 6, 7, 7, 8};
	
  CString WeekDay;
  CString Month;
  CString Zone;
  
  Date.Replace('-', ' ');

  memset(&Result, 0, sizeof(Result));

  bool fScan = 
      SSScan(
          Date, 
          &DateFormat, 
          &WeekDay, 
          NULL, 
          &Result.tm_mday, 
          &Month, 
          &Result.tm_year, 
          &Result.tm_hour, 
          NULL, 
          &Result.tm_min, 
          NULL, 
          &Result.tm_sec, 
          &Zone);
  
  Trace(tagDateTime, levVerbose, 
        ("CDate:: EncodeDate - scanned %s with " \
         "WeekDay: %s " \
         "Day: %d " \
         "Month: %s " \
         "Year: %d " \
         "Hour: %d " \
         "Minute: %d " \
         "Second: %d " \
         "Zone: %s", 
         Date.GetBuffer(),
         WeekDay.GetBuffer(),
         Result.tm_mday,
         Month.GetBuffer(),
         Result.tm_year,
         Result.tm_hour,
         Result.tm_min,
         Result.tm_sec,
         Zone.GetBuffer()));
  
  if (fScan) {

		int i;
      
		if (Result.tm_year > 1900) 
			Result.tm_year-=1900;
    
		for (i = 0; i < BASE_DIM(Months); i++) {
			if (Month.Same(Months[i])) {
				Result.tm_mon = i;
				break;
			}
		}

		for (i = 0; i < BASE_DIM(WeekDays); i++) {
			// support full weekdays as well
			if (WeekDay.StartsWithSame(WeekDays[i])) {
				Result.tm_wday = i;
				break;
			}
		}

		// time zone adjustments
		int ZoneAdjustment = 0;

		if (Zone.IsInt( & ZoneAdjustment)) {
			ZoneAdjustment *= 3600;
		} else {
			for (i = 0; i < BASE_DIM(Zones); i++) {
				if (Zone.Same(Zones[i])) {
					ZoneAdjustment = ZonesHoursSkew[i] * 3600;
					break;
				}
			}
		}

		Trace(tagDateTime, levVerbose, ("CDate:: EncodeSimpleDate - ZoneAdjustment %d second(s)", ZoneAdjustment));

		Result.tm_isdst = 0;

		if (ZoneAdjustment) {
			time_t AdjustedTime;
#ifdef _UNIX
			base_gmtime(AdjustedTime, Result);
#endif
#ifdef _WIN32
			_tzset();
			AdjustedTime = mktime(&Result);
			AdjustedTime -= _timezone;
#endif
			AdjustedTime -= ZoneAdjustment;
			base_localtime(AdjustedTime, Result);
		}

		// Result.tm_gmtoff = ZoneAdjustment;    
		return true;
  }
  return false;
}
Beispiel #8
0
bool lib::date::isDaylightSavingsTime() {
	struct _timeb tb;
	_tzset();
	_ftime(&tb);
	return tb.dstflag;
}
Beispiel #9
0
static void my_win_init(void)
{
  HKEY	hSoftMysql ;
  DWORD dimName = 256 ;
  DWORD dimData = 1024 ;
  DWORD dimNameValueBuffer = 256 ;
  DWORD dimDataValueBuffer = 1024 ;
  DWORD indexValue = 0 ;
  long	retCodeEnumValue ;
  char	NameValueBuffer[256] ;
  char	DataValueBuffer[1024] ;
  char	EnvString[1271] ;
  const char *targetKey = "Software\\MySQL" ;
  DBUG_ENTER("my_win_init");

  setlocale(LC_CTYPE, "");             /* To get right sortorder */

#if defined(_MSC_VER) && (_MSC_VER < 1300)
  /* 
    Clear the OS system variable TZ and avoid the 100% CPU usage
    Only for old versions of Visual C++
  */
  _putenv( "TZ=" ); 
#endif  
  _tzset();

  /* apre la chiave HKEY_LOCAL_MACHINES\software\MySQL */
  if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,(LPCTSTR)targetKey,0,
		   KEY_READ,&hSoftMysql) != ERROR_SUCCESS)
    DBUG_VOID_RETURN;

  /*
  ** Ne legge i valori e li inserisce  nell'ambiente
  ** suppone che tutti i valori letti siano di tipo stringa + '\0'
  ** Legge il valore con indice 0 e lo scarta
  */
  retCodeEnumValue = RegEnumValue(hSoftMysql, indexValue++,
				  (LPTSTR)NameValueBuffer, &dimNameValueBuffer,
				  NULL, NULL, (LPBYTE)DataValueBuffer,
				  &dimDataValueBuffer) ;

  while (retCodeEnumValue != ERROR_NO_MORE_ITEMS)
  {
    char *my_env;
    /* Crea la stringa d'ambiente */
    setEnvString(EnvString, NameValueBuffer, DataValueBuffer) ;

    /* Inserisce i dati come variabili d'ambiente */
    my_env=strdup(EnvString);  /* variable for putenv must be allocated ! */
    putenv(my_env) ;

    dimNameValueBuffer = dimName ;
    dimDataValueBuffer = dimData ;

    retCodeEnumValue = RegEnumValue(hSoftMysql, indexValue++,
				    NameValueBuffer, &dimNameValueBuffer,
				    NULL, NULL, (LPBYTE)DataValueBuffer,
				    &dimDataValueBuffer) ;
  }

  /* chiude la chiave */
  RegCloseKey(hSoftMysql) ;
  DBUG_VOID_RETURN ;
}
Beispiel #10
0
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
	FILETIME        ft;
	LARGE_INTEGER   li;
	__int64         t;
	int             nnested = 0;
	LARGE_INTEGER stamp;
	time_t now;
	TIME_CTX_T *ctx = tls_calloc(sizeof(TIME_CTX_T));

	/* 每个线程调用此函数时都需要进行初始化,但为了防止开机时间太长
	 * 而造成时钟计数归零溢出,所以每隔 1 天校对一次基准时间
	 */
#define DAY_SEC	(3600 * 24)

	time(&now);
	if (now - ctx->last_init > DAY_SEC) {
		ctx->last_init = now;

		/* 获得CPU的时钟频率 */
		if (!QueryPerformanceFrequency(&ctx->frequency))
			acl_msg_fatal("%s(%d): Unable to get System Frequency(%s)",
				__FILE__, __LINE__, acl_last_serror());
		/* 获得系统时间(自 1970 至今) */
		GetSystemTimeAsFileTime(&ft);
		li.LowPart  = ft.dwLowDateTime;
		li.HighPart = ft.dwHighDateTime;
		t  = li.QuadPart;       /* In 100-nanosecond intervals */
		t -= EPOCHFILETIME;     /* Offset to the Epoch time */
		t /= 10;                /* In microseconds */

		/* 转换成本次开机后的基准时间 */
		ctx->tvbase.tv_sec  = (long)(t / 1000000);
		ctx->tvbase.tv_usec = (long)(t % 1000000);

		/* 获得本次开机后到现在的时钟计数 */
		if (!QueryPerformanceCounter(&ctx->stamp))
			acl_msg_fatal("%s(%d): unable to get System time(%s)",
				__FILE__, __LINE__, acl_last_serror());
	}

	/* 开始获得现在的时间截 */

	if (tv) {
		/* 获得本次开机后至现在的时钟计数  */
		if (!QueryPerformanceCounter(&stamp))
			acl_msg_fatal("%s(%d): unable to get System time(%s)",
				__FILE__, __LINE__, acl_last_serror());

		/* 计算当前精确时间截 */
		t = (stamp.QuadPart - ctx->stamp.QuadPart) * 1000000 / ctx->frequency.QuadPart;
		tv->tv_sec = ctx->tvbase.tv_sec + (long)(t / 1000000);
		tv->tv_usec = ctx->tvbase.tv_usec + (long)(t % 1000000);
	}

	if (tz) {
		if (!ctx->tzflag) {
			_tzset();
			ctx->tzflag++;
		}
		tz->tz_minuteswest = _timezone / 60;
		tz->tz_dsttime = _daylight;
	}

	return (0);
}
Beispiel #11
0
int lib::date::getLocalTimezoneOffset() {
	struct _timeb tb;
	_tzset();
	_ftime(&tb);
	return -tb.timezone * 60;
}
Beispiel #12
0
time_t __stdcall DateToUnixTime(const TCHAR *stamp, bool FeedType)
{
	struct tm timestamp;
	TCHAR date[9];
	int i, y;
	time_t t;

	if (stamp == NULL)
		return 0;

	TCHAR *p = NEWTSTR_ALLOCA(stamp);

	if (FeedType) {
		// skip '-' chars
		int si = 0, sj = 0;
		while (true) {
			if (p[si] == _T('-'))
				si++;
			else if (!(p[sj++] = p[si++]))
				break;
		}
	}
	else {
		TCHAR *weekday, monthstr[4], timezonesign[2];
		int day, month = 0, year, hour, min, sec, timezoneh, timezonem;
		if (_tcsstr(p, _T(","))) {
			weekday = _tcstok(p, _T(","));
			p = _tcstok(NULL, _T(","));
			_stscanf(p + 1, _T("%d %3s %d %d:%d:%d %1s%02d%02d"), &day, &monthstr, &year, &hour, &min, &sec, &timezonesign, &timezoneh, &timezonem);
			if (!mir_tstrcmpi(monthstr, _T("Jan")))
				month = 1;
			if (!mir_tstrcmpi(monthstr, _T("Feb")))
				month = 2;
			if (!mir_tstrcmpi(monthstr, _T("Mar")))
				month = 3;
			if (!mir_tstrcmpi(monthstr, _T("Apr")))
				month = 4;
			if (!mir_tstrcmpi(monthstr, _T("May")))
				month = 5;
			if (!mir_tstrcmpi(monthstr, _T("Jun")))
				month = 6;
			if (!mir_tstrcmpi(monthstr, _T("Jul")))
				month = 7;
			if (!mir_tstrcmpi(monthstr, _T("Aug")))
				month = 8;
			if (!mir_tstrcmpi(monthstr, _T("Sep")))
				month = 9;
			if (!mir_tstrcmpi(monthstr, _T("Oct")))
				month = 10;
			if (!mir_tstrcmpi(monthstr, _T("Nov")))
				month = 11;
			if (!mir_tstrcmpi(monthstr, _T("Dec")))
				month = 12;
			if (year < 2000)
				year += 2000;
			if (!mir_tstrcmp(timezonesign, _T("+")))
				mir_sntprintf(p, 4 + 2 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1, _T("%04d%02d%02dT%02d:%02d:%02d"), year, month, day, hour - timezoneh, min - timezonem, sec);
			else if (!mir_tstrcmp(timezonesign, _T("-")))
				mir_sntprintf(p, 4 + 2 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1, _T("%04d%02d%02dT%02d:%02d:%02d"), year, month, day, hour + timezoneh, min + timezonem, sec);
			else
				mir_sntprintf(p, 4 + 2 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1, _T("%04d%02d%02dT%02d:%02d:%02d"), year, month, day, hour, min, sec);
		}
		else if (_tcsstr(p, _T("T"))) {
			_stscanf(p, _T("%d-%d-%dT%d:%d:%d"), &year, &month, &day, &hour, &min, &sec);
			mir_sntprintf(p, 4 + 2 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1, _T("%04d%02d%02dT%02d:%02d:%02d"), year, month, day, hour, min, sec);
		}
		else
		{
			_stscanf(p, _T("%d-%d-%d %d:%d:%d %1s%02d%02d"), &year, &month, &day, &hour, &min, &sec, &timezonesign, &timezoneh, &timezonem);
			if (!mir_tstrcmp(timezonesign, _T("+")))
				mir_sntprintf(p, 4 + 2 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1, _T("%04d%02d%02dT%02d:%02d:%02d"), year, month, day, hour - timezoneh, min - timezonem, sec);
			else if (!mir_tstrcmp(timezonesign, _T("-")))
				mir_sntprintf(p, 4 + 2 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1, _T("%04d%02d%02dT%02d:%02d:%02d"), year, month, day, hour + timezoneh, min + timezonem, sec);
			else
				mir_sntprintf(p, 4 + 2 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1, _T("%04d%02d%02dT%02d:%02d:%02d"), year, month, day, hour, min, sec);
		}
	}
	// Get the date part
	for (i = 0; *p != '\0' && i < 8 && isdigit(*p); p++, i++)
		date[i] = *p;

	// Parse year
	if (i == 6) {
		// 2-digit year ( 1970-2069 )
		y = (date[0] - '0') * 10 + (date[1] - '0');
		if (y < 70)
			y += 100;
	}
	else if (i == 8) {
		// 4-digit year
		y = (date[0] - '0') * 1000 + (date[1] - '0') * 100 + (date[2] - '0') * 10 + date[3] - '0';
		y -= 1900;
	}
	else return 0;

	timestamp.tm_year = y;
	// Parse month
	timestamp.tm_mon = (date[i - 4] - '0') * 10 + date[i - 3] - '0' - 1;
	// Parse date
	timestamp.tm_mday = (date[i - 2] - '0') * 10 + date[i - 1] - '0';

	// Skip any date/time delimiter
	for (; *p != '\0' && !isdigit(*p); p++);

	// Parse time
	if (_stscanf(p, _T("%d:%d:%d"), &timestamp.tm_hour, &timestamp.tm_min, &timestamp.tm_sec) != 3)
		return 0;

	timestamp.tm_isdst = 0;	// DST is already present in _timezone below
	t = mktime(&timestamp);

	_tzset();
	t -= (time_t)_timezone;
	return (t >= 0) ? t : 0;
}
__timeref::__timeref() {
#ifdef USE_TSC
    LARGE_INTEGER f;
    QueryPerformanceFrequency(&f);

    // calibrate timing info: figure out time it takes to call QueryPerformanceCounter and figure out clock rate
    LARGE_INTEGER tpc_start, tpc_end, pc_start, pc_end;
    __int64 tsc_start, tsc_end, crap;

    printf("running timing calibration\n");

    int prev_pri = GetThreadPriority(GetCurrentThread());
    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

    double avg_speed = 0, avg_tpc = 0;
    double var_speed = 0, var_tpc = 0;
    int n = 20;
    for (int i = 0; i < n; i++) {
        // first, measure time it takes to call QueryPerformanceCounter
        QueryPerformanceCounter(&tpc_start);
        QueryPerformanceCounter(&tpc_end);

        // next, try to calculate clock speed knowing that info
        tsc_start = __rdtsc();
        QueryPerformanceCounter(&pc_start);
        // spin for a while by reading the tsc
        for (int i = 0; i < 10000000; i++) {
            crap = i * 10;
        }
        QueryPerformanceCounter(&pc_end);
        tsc_end = __rdtsc();

        // we can now calculate the clock rate
        double tpc = (tpc_end.QuadPart - tpc_start.QuadPart) / (double)f.QuadPart;
        double deltat = (pc_end.QuadPart - pc_start.QuadPart) / (double)f.QuadPart + tpc;
        double clock_rate = (tsc_end - tsc_start) / deltat;

        avg_speed += clock_rate;
        var_speed += clock_rate * clock_rate;
        avg_tpc += tpc;
        var_tpc += tpc * tpc;
    }

    avg_speed /= n;
    avg_tpc /= n;
    var_speed = var_speed / n - avg_speed * avg_speed;
    if (var_speed < 0) var_speed = 0;
    var_tpc = var_tpc / n - avg_tpc * avg_tpc;
    if (var_tpc < 0) var_tpc = 0;

    double std_speed = sqrt(var_speed);
    double std_tpc = sqrt(var_tpc);

    double err_percentage = std_speed / avg_speed * 100.0;

#ifdef CAL_RDTSC
    // calculate time to call __rdtsc()
    // first, calculate time to execute a loop
    const int n_loop = 10000000;
    QueryPerformanceCounter(&pc_start);
    for (int i = 0; i < n_loop; i++);
    QueryPerformanceCounter(&pc_end);

    double tloop = (pc_end.QuadPart - pc_start.QuadPart) / (double)f.QuadPart;

    // now, do again but call __rdtsc() each time
    QueryPerformanceCounter(&pc_start);
    for (int i = 0; i < n_loop; i++) crap = __rdtsc();
    QueryPerformanceCounter(&pc_end);

    double trdtsc = (pc_end.QuadPart - pc_start.QuadPart) / (double)f.QuadPart - tloop;
#else
    double trdtsc = 0.0;
#endif

    SetThreadPriority(GetCurrentThread(), prev_pri);

    printf("qpc freq: %I64d\n", f.QuadPart);
    printf("avg TSC speed: %.0f Hz, std: %.0f Hz (%f %% err)\n", avg_speed, std_speed, err_percentage);
    printf("avg time for qpc: %f ms, std: %f ms\n", avg_tpc * 1000, std_tpc * 1000);

#ifdef CAL_RDTSC
    printf("avg time for __rdtsc: %f, loop %f (per 10mil)\n", trdtsc, tloop);
    trdtsc /= n_loop;
#endif

    // this is commented out to ignore rounding for now
    // force avg_speed to have 0's up through the 10,000 place
    //avg_speed = floor(avg_speed / 10000) * 10000;
    //printf("rounded speed: %f\n", avg_speed);

    freq_s = (__int64)avg_speed;
    freq_ms = (__int64)(avg_speed / 1000);

    conv_s = 1.0 / avg_speed;
    conv_ms = 1000.0 / avg_speed;

    // there are 1x10^7 .Net ticks per second, so this will give us system ticks per .Net tick
    // not sure which will be more frequent, the high-performance couter or .Net ticks, so use a double
    conv_net = avg_speed / 10000000.0;

    _tzset();
    time_t now = time(NULL);
    __int64 now_tsc = __rdtsc();
    start = now * freq_s - now_tsc;
    start_elapsed = now_tsc;

#else
    LARGE_INTEGER f;
    QueryPerformanceFrequency(&f);

    freq_s = f.QuadPart;
    freq_ms = f.QuadPart / 1000;

    conv_s = 1.0 / (double)freq_s;
    conv_ms = 1000.0 / (double)freq_s;

    // there are 1x10^7 .Net ticks per second, so this will give us system ticks per .Net tick
    // not sure which will be more frequent, the high-performance couter or .Net ticks, so use a double
    conv_net = 10000000.0 / (double)freq_s;

    _tzset();
    time_t now = time(NULL);
    start = now * freq_s;

    __int64 ft_now;
    GetSystemTimeAsFileTime((LPFILETIME)&ft_now);
    dnt_start = ft_now;

    QueryPerformanceCounter(&f);
    start -= f.QuadPart;
    start_elapsed = f.QuadPart;
    // start is the time in ticks of the current system time less the starting value for QueryPerformanceCounter
#endif
}
Beispiel #14
0
int gettimeofday(struct timeval* tv, struct timezone* tz)
{
   // define tzinit flag (whether or not the timezone has been initialized)
   static bool tzinit = false;

   // NOTE: use FileTimeToSystemTime to convert a FILETIME to a SYSTEMTIME
   // that has years, months, days, hours, seconds, milliseconds, etc
   if(tv != NULL)
   {
//      // get the system time as a file time (a UTC time object)
//      FILETIME ft;
//      GetSystemTimeAsFileTime(&ft);
//
//      // use a large integer to combine the time into a 64-bit long
//      LARGE_INTEGER li;
//      li.LowPart = ft.dwLowDateTime;
//      li.HighPart = ft.dwHighDateTime;
//
//      // get the 64-bit long in
//      // the time is in 100-nanosecond intervals (1000 nanoseconds in
//      // a microsecond, so this is really just microseconds / 10)
//      __int64 time = li.QuadPart;

      // get the system time as a file time (a UTC time object),
      // interpretable as a 64-bit integer
      union now
      {
         FILETIME ft;
         __int64 time;
      };

      GetSystemTimeAsFileTime(&now.ft);

      // eliminate time between 01/01/1601 (UTC) and 01/01/1970 (epoch)
      now.time -= EPOCH_UTC_TENTHMICROSECS_DELTA;

      // get time in microseconds
      now.time /= UINT64_C(10);

      // store time in seconds and microseconds (1 microsecond = 1000000 sec)
      tv->tv_sec  = (uint64_t)(now.time / UINT64_C(1000000));
      tv->tv_usec = (uint64_t)(now.time % UINT64_C(1000000));
   }

   // populate timezone
   if(tz != NULL)
   {
      if(!tzinit)
      {
         // initialize timezone
         _tzset();
         tzinit = true;
      }

      // set timezone information:

      // get the number of minutes west (tz_dsttime is supposedly obsolete)
      tz->tz_minuteswest = gGetTimeZoneMinutesWest();
      tz->tz_dsttime = _daylight;
   }

   // success
   return 0;
}
Beispiel #15
0
/*
 * init_timer - initialize the timer data structures
 */
void
init_timer(void)
{
# if defined SYS_WINNT & !defined(SYS_CYGWIN32)
	HANDLE hToken = INVALID_HANDLE_VALUE;
	TOKEN_PRIVILEGES tkp;
# endif /* SYS_WINNT */

	/*
	 * Initialize...
	 */
	alarm_flag = 0;
	alarm_overflow = 0;
	adjust_timer = 1;
	stats_timer = 0;
	huffpuff_timer = 0;
	interface_timer = 0;
	current_time = 0;
	timer_overflows = 0;
	timer_xmtcalls = 0;
	timer_timereset = 0;

#if !defined(SYS_WINNT)
	/*
	 * Set up the alarm interrupt.	The first comes 2**EVENT_TIMEOUT
	 * seconds from now and they continue on every 2**EVENT_TIMEOUT
	 * seconds.
	 */
# if !defined(VMS)
#  if defined(HAVE_TIMER_CREATE) && defined(HAVE_TIMER_SETTIME)
	if (timer_create (CLOCK_REALTIME, NULL, &ntpd_timerid) ==
#	ifdef SYS_VXWORKS
		ERROR
#	else
		-1
#	endif
	   )
	{
		fprintf (stderr, "timer create FAILED\n");
		exit (0);
	}
	(void) signal_no_reset(SIGALRM, alarming);
	itimer.it_interval.tv_sec = itimer.it_value.tv_sec = (1<<EVENT_TIMEOUT);
	itimer.it_interval.tv_nsec = itimer.it_value.tv_nsec = 0;
	timer_settime(ntpd_timerid, 0 /*!TIMER_ABSTIME*/, &itimer, NULL);
#  else
	(void) signal_no_reset(SIGALRM, alarming);
	itimer.it_interval.tv_sec = itimer.it_value.tv_sec = (1<<EVENT_TIMEOUT);
	itimer.it_interval.tv_usec = itimer.it_value.tv_usec = 0;
	setitimer(ITIMER_REAL, &itimer, (struct itimerval *)0);
#  endif
# else /* VMS */
	vmsinc[0] = 10000000;		/* 1 sec */
	vmsinc[1] = 0;
	lib$emul(&(1<<EVENT_TIMEOUT), &vmsinc, &0, &vmsinc);

	sys$gettim(&vmstimer);	/* that's "now" as abstime */

	lib$addx(&vmsinc, &vmstimer, &vmstimer);
	sys$setimr(0, &vmstimer, alarming, alarming, 0);
# endif /* VMS */
#else /* SYS_WINNT */
	_tzset();

	/*
	 * Get privileges needed for fiddling with the clock
	 */

	/* get the current process token handle */
	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
		msyslog(LOG_ERR, "OpenProcessToken failed: %m");
		exit(1);
	}
	/* get the LUID for system-time privilege. */
	LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
	tkp.PrivilegeCount = 1;  /* one privilege to set */
	tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	/* get set-time privilege for this process. */
	AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);
	/* cannot test return value of AdjustTokenPrivileges. */
	if (GetLastError() != ERROR_SUCCESS) {
		msyslog(LOG_ERR, "AdjustTokenPrivileges failed: %m");
	}

	/*
	 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
	 * Under Windows/NT, 
	 */

	WaitableTimerHandle = CreateWaitableTimer(NULL, FALSE, NULL);
	if (WaitableTimerHandle == NULL) {
		msyslog(LOG_ERR, "CreateWaitableTimer failed: %m");
		exit(1);
	}
	else {
		DWORD Period = (1<<EVENT_TIMEOUT) * 1000;
		LARGE_INTEGER DueTime;
		DueTime.QuadPart = Period * 10000i64;
		if (!SetWaitableTimer(WaitableTimerHandle, &DueTime, Period, NULL, NULL, FALSE) != NO_ERROR) {
			msyslog(LOG_ERR, "SetWaitableTimer failed: %m");
			exit(1);
		}
	}

#endif /* SYS_WINNT */
}
void dbugfile_init()
{
	// Clear the counters
	memset(dbugfile_counters, 0, sizeof(int) * MAX_COUNTERS);

	char big_buffer[1000];
	char temp_buff[512];

	dbugfile_filename[0] = '\0';

#ifdef _WIN32

	char path[MAX_PATH];

	GetCurrentDirectory(MAX_PATH, path);

	int path_len = strlen(path);
	if(path[path_len - 1] != '\\')
	{
	 	path[path_len] = '\\';
		path[path_len + 1] = '\0';
	}

 	strcpy(dbugfile_filename, path);

#endif

	strcat(dbugfile_filename, "DBUG-");
	strcpy(big_buffer, "DBUGFILE Active: ");

#ifdef _WIN32
	{
		unsigned long len = 512;
		GetUserName(temp_buff, &len);
		
		strcat(dbugfile_filename, temp_buff);
		strcat(big_buffer, temp_buff);
		
		strcat(dbugfile_filename, "-");
		strcat(big_buffer, " ");
	}
#endif

    _tzset();

    // Display operating system-style date and time.
	_strdate( temp_buff);
	strcat(dbugfile_filename, "D(");
	strcat(dbugfile_filename,temp_buff);
	strcat(big_buffer,temp_buff);

	strcat(dbugfile_filename, ") T(");
	strcat(big_buffer, " ");

    _strtime( temp_buff);
	strcat(dbugfile_filename,temp_buff);
	strcat(big_buffer,temp_buff);

	strcat(dbugfile_filename, ").txt");
	strcat(big_buffer, "\n");

	// Remove invalid slash chars
	int len = strlen(dbugfile_filename);
	while(len >= 2)
	{
		if(dbugfile_filename[len] == '/' || dbugfile_filename[len] == ':')
		{
			dbugfile_filename[len] = '-';
		}
		len--;
	}

	// open file
	// Uncomment this to see where the file is going
  	//MessageBox(NULL, dbugfile_filename, "das", MB_OK); 
	FILE *fp = fopen(dbugfile_filename, "w");

	if(fp == NULL)
	{
		return;
	}

	fwrite(big_buffer, sizeof(char) * strlen(big_buffer), 1, fp);

#ifdef _WIN32

	// detect OS type

	OSVERSIONINFO version_info;
	version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

	if(GetVersionEx(&version_info) != false)
	{
		char *error = "Error in detecting OS version";
		char *version = error;

		switch(version_info.dwMajorVersion)
		{
			case 4:
			{
				if(version_info.dwMinorVersion == 0)
				{
					version = "Windows 95"; 
				}
				else if(version_info.dwMinorVersion == 10)
				{
					version = "Windows 98";  
				}
				else if(version_info.dwMinorVersion == 90)
				{
					version = "Windows Me";
				}
				break;
			}
			case 5:
			{
				if(version_info.dwMinorVersion == 0)
				{
					version = "Windows 2000"; 
				}
				else if(version_info.dwMinorVersion == 1)
				{
					version = "Windows XP";
				}
				break;
			}
		}

		char *release_type = NULL;
#ifdef _DEBUG 
		release_type = "Debug";
#else
		release_type = "Release";
#endif
		sprintf(big_buffer, "OS: %s %s, ", version, release_type);
	}				  

	fwrite(big_buffer, sizeof(char) * strlen(big_buffer), 1, fp);

	char exe_name[MAX_PATH];

	GetModuleFileName(NULL, exe_name, MAX_PATH);
	strcat(exe_name, "\n");
	fwrite(exe_name, sizeof(char) * strlen(exe_name), 1, fp);


#endif

	fclose(fp);

	dbugfile_init_var = true;
}
Beispiel #17
0
int main (int argc, char ** argv)
{
    time_t tm;
    int i, new_mudlib = 0, got_defaults = 0;
    char *p;
    char version_buf[80];
#if 0
    int dtablesize;
#endif
    error_context_t econ;

#ifdef PROTO_TZSET
    void tzset();
#endif

#ifdef INCL_LOCALE_H
    setlocale(LC_ALL, "C");
#endif

#if !defined(__SASC) && (defined(AMITCP) || defined(AS225))
    amiga_sockinit();
    atexit(amiga_sockexit);
#endif
#ifdef WRAPPEDMALLOC
    wrappedmalloc_init();
#endif        /* WRAPPEDMALLOC */
#ifdef DEBUGMALLOC
    MDinit();
#endif

#if (defined(PROFILING) && !defined(PROFILE_ON) && defined(HAS_MONCONTROL))
    moncontrol(0);
#endif
#ifdef USE_TZSET
    tzset();
#endif
    boot_time = get_current_time();

    const0.type = T_NUMBER;
    const0.u.number = 0;
    const1.type = T_NUMBER;
    const1.u.number = 1;

    /* const0u used by undefinedp() */
    const0u.type = T_NUMBER;
    const0u.subtype = T_UNDEFINED;
    const0u.u.number = 0;

    //fake_prog.program_size = 0; //0 anyway

    /*
     * Check that the definition of EXTRACT_UCHAR() is correct.
     */
    p = (char *) &i;
    *p = -10;
    if (EXTRACT_UCHAR(p) != 0x100 - 10) {
        fprintf(stderr, "Bad definition of EXTRACT_UCHAR() in interpret.h.\n");
        exit(-1);
    }

    /*
     * An added test: can we do EXTRACT_UCHAR(x++)?
     * (read_number, etc uses it)
     */
    p = (char *) &i;
    (void) EXTRACT_UCHAR(p++);
    if ((p - (char *) &i) != 1) {
        fprintf(stderr, "EXTRACT_UCHAR() in interpret.h evaluates its argument more than once.\n");
        exit(-1);
    }

    /*
     * Check the living hash table size
     */
    if (CFG_LIVING_HASH_SIZE != 4 && CFG_LIVING_HASH_SIZE != 16 &&
            CFG_LIVING_HASH_SIZE != 64 && CFG_LIVING_HASH_SIZE != 256 &&
            CFG_LIVING_HASH_SIZE != 1024 && CFG_LIVING_HASH_SIZE != 4096) {
        fprintf(stderr, "CFG_LIVING_HASH_SIZE in options.h must be one of 4, 16, 64, 256, 1024, 4096, ...\n");
        exit(-1);
    }

#ifdef RAND
    srand(get_current_time());
#else
#  ifdef DRAND48
    srand48(get_current_time());
#  else
#    ifdef RANDOM
    srandom(get_current_time());
#    else
    fprintf(stderr, "Warning: no random number generator specified!\n");
#    endif
#  endif
#endif
    current_time = get_current_time();
    /*
     * Initialize the microsecond clock.
     */
    init_usec_clock();

    /* read in the configuration file */

    got_defaults = 0;
    for (i = 1; (i < argc) && !got_defaults; i++) {
        if (argv[i][0] != '-') {
            set_defaults(argv[i]);
            got_defaults = 1;
        }
    }
    get_version(version_buf);
    if (!got_defaults) {
        fprintf(stderr, "%s for %s.\n", version_buf, ARCH);
        fprintf(stderr, "You must specify the configuration filename as an argument.\n");
        exit(-1);
    }

    printf("Initializing internal tables....\n");
    init_strings();   /* in stralloc.c */
    init_otable();    /* in otable.c */
    init_identifiers();   /* in lex.c */
    init_locals();              /* in compiler.c */

    /*
     * If our estimate is larger than FD_SETSIZE, then we need more file
     * descriptors than the operating system can handle.  This is a problem
     * that can be resolved by decreasing MAX_USERS, MAX_EFUN_SOCKS, or both.
     *
     * Unfortunately, since neither MAX_USERS or MAX_EFUN_SOCKS exist any more,
     * we have no clue how many we will need.  This code really should be
     * moved to places where ENFILE/EMFILE is returned.
     */
#if 0
    if (dtablesize > FD_SETSIZE) {
        fprintf(stderr, "Warning: File descriptor requirements exceed system capacity!\n");
        fprintf(stderr, "         Configuration exceeds system capacity by %d descriptor(s).\n",
                dtablesize - FD_SETSIZE);
    }
#ifdef HAS_SETDTABLESIZE
    /*
     * If the operating system supports setdtablesize() then we can request
     * the number of file descriptors we really need.  First check to see if
     * wee already have enough.  If so dont bother the OS. If not, attempt to
     * allocate the number we estimated above.  There are system imposed
     * limits on file descriptors, so we may not get as many as we asked for.
     * Check to make sure we get enough.
     */
    if (getdtablesize() < dtablesize)
        if (setdtablesize(dtablesize) < dtablesize) {
            fprintf(stderr, "Warning: Could not allocate enough file descriptors!\n");
            fprintf(stderr, "         setdtablesize() could not allocate %d descriptor(s).\n",
                    getdtablesize() - dtablesize);
        }
    /*
     * Just be polite and tell the administrator how many he has.
     */
    fprintf(stderr, "%d file descriptors were allocated, (%d were requested).\n",
            getdtablesize(), dtablesize);
#endif
#endif
    time_to_clean_up = TIME_TO_CLEAN_UP;
    max_cost = MAX_COST;
    reserved_size = RESERVED_SIZE;
    max_array_size = MAX_ARRAY_SIZE;
    if(max_array_size > 65535){
        fprintf(stderr, "Maximum array size can not exceed 65535");
        max_array_size = 65535;
    }
    max_buffer_size = MAX_BUFFER_SIZE;
    max_string_length = MAX_STRING_LENGTH;
    mud_lib = (char *) MUD_LIB;
    set_inc_list(INCLUDE_DIRS);
    if (reserved_size > 0)
        reserved_area = (char *) DMALLOC(reserved_size, TAG_RESERVED, "main.c: reserved_area");
    for (i = 0; i < sizeof consts / sizeof consts[0]; i++)
        consts[i] = exp(-i / 900.0);
    reset_machine(1);
    /*
     * The flags are parsed twice ! The first time, we only search for the -m
     * flag, which specifies another mudlib, and the D-flags, so that they
     * will be available when compiling master.c.
     */
    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-')
            continue;
        switch (argv[i][1]) {
            case 'D':
                if (argv[i][2]) {
                    lpc_predef_t *tmp = ALLOCATE(lpc_predef_t, TAG_PREDEFINES,
                            "predef");
                    tmp->flag = argv[i] + 2;
                    tmp->next = lpc_predefs;
                    lpc_predefs = tmp;
                    continue;
                }
                fprintf(stderr, "Illegal flag syntax: %s\n", argv[i]);
                exit(-1);
            case 'N':
                no_ip_demon++;
                continue;
#ifdef HAS_CONSOLE
            case 'C':
                has_console = 1;
                continue;
#endif
#ifdef YYDEBUG
            case 'y':
                yydebug = 1;
                continue;
#endif        /* YYDEBUG */
            case 'm':
                mud_lib = alloc_cstring(argv[i] + 2, "mudlib dir");
                if (chdir(mud_lib) == -1) {
                    fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
                    exit(-1);
                }
                new_mudlib = 1;
                break;
        }
    }
    if (!new_mudlib && chdir(mud_lib) == -1) {
        fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
        exit(-1);
    }
    time(&tm);
    debug_message("----------------------------------------------------------------------------\n%s (%s) starting up on %s - %s\n\n", MUD_NAME, version_buf, ARCH, ctime(&tm));

    add_predefines();
#ifdef WIN32
    _tzset();
#endif

#ifndef NO_IP_DEMON
    if (!no_ip_demon && ADDR_SERVER_IP)
        init_addr_server(ADDR_SERVER_IP, ADDR_SERVER_PORT);
#endif        /* NO_IP_DEMON */

    set_eval(max_cost);

    save_context(&econ);
    if (SETJMP(econ.context)) {
        debug_message("The simul_efun (%s) and master (%s) objects must be loadable.\n",
                SIMUL_EFUN, MASTER_FILE);
        exit(-1);
    } else {
        init_simul_efun(SIMUL_EFUN);
        init_master();
    }
    pop_context(&econ);

    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-') {
            continue;
        } else {
            /*
             * Look at flags. -m and -o has already been tested.
             */
            switch (argv[i][1]) {
                case 'D':
                case 'N':
                case 'm':
                case 'y':
                case 'C':
                    continue;
                case 'f':
                    save_context(&econ);
                    if (SETJMP(econ.context)) {
                        debug_message("Error while calling master::flag(\"%s\"), aborting ...\n", argv[i] + 2);
                        exit(-1);
                    }
                    push_constant_string(argv[i] + 2);
                    apply_master_ob(APPLY_FLAG, 1);
                    if (MudOS_is_being_shut_down) {
                        debug_message("Shutdown by master object.\n");
                        exit(0);
                    }
                    pop_context(&econ);
                    continue;
                case 'e':
                    e_flag++;
                    continue;
                case 'p':
                    external_port[0].port = atoi(argv[i] + 2);
                    continue;
                case 'd':
#ifdef DEBUG_MACRO
                    if (argv[i][2])
                        debug_level_set(&argv[i][2]);
                    else
                        debug_level |= DBG_d_flag;
#else
                    debug_message("Driver must be compiled with DEBUG_MACRO on to use -d.\n");
#endif
                    break;
                case 'c':
                    comp_flag++;
                    continue;
                case 't':
                    t_flag++;
                    continue;
                default:
                    debug_message("Unknown flag: %s\n", argv[i]);
                    exit(-1);
            }
        }
    }
    if (MudOS_is_being_shut_down)
        exit(1);
    if (*(DEFAULT_FAIL_MESSAGE)) {
        char buf[8192];

        strcpy(buf, DEFAULT_FAIL_MESSAGE);
        strcat(buf, "\n");
        default_fail_message = make_shared_string(buf);
    } else
        default_fail_message = "What?\n";
#ifdef PACKAGE_MUDLIB_STATS
    restore_stat_files();
#endif
    preload_objects(e_flag);
#ifdef SIGFPE
    signal(SIGFPE, sig_fpe);
#endif
#ifdef TRAP_CRASHES
#ifdef SIGUSR1
    signal(SIGUSR1, sig_usr1);
#endif
#ifdef SIGUSR2
    signal(SIGUSR2, sig_usr2);
#endif
    signal(SIGTERM, sig_term);
    signal(SIGINT, sig_int);
#ifndef DEBUG
#if defined(SIGABRT)
    signal(SIGABRT, sig_abrt);
#endif
#ifdef SIGIOT
    signal(SIGIOT, sig_iot);
#endif
#ifdef SIGHUP
    signal(SIGHUP, sig_hup);
#endif
#ifdef SIGBUS
    signal(SIGBUS, sig_bus);
#endif
    signal(SIGSEGV, sig_segv);
    signal(SIGILL, sig_ill);
#endif        /* DEBUG */
#endif
#ifndef WIN32
#ifdef USE_BSD_SIGNALS
    signal(SIGCHLD, sig_cld);
#else
    signal(SIGCLD, sig_cld);
#endif
#endif

#ifdef HAS_CONSOLE
    if(has_console >= 0)
        signal(SIGTTIN, sig_ttin);
    signal(SIGTTOU, SIG_IGN);
#endif

    backend();
    return 0;
}
Beispiel #18
0
size_t
strftime(char *s, size_t maxsize,
		const char *format, const struct tm *timeptr)
{
	size_t n;
	char *firsts, *olds;

	if (!format) return 0;

	_tzset();	/* for %Z conversion */
	firsts = s;
	while (maxsize && *format) {
		while (maxsize && *format && *format != '%') {
			*s++ = *format++;
			maxsize--;
		}
		if (!maxsize || !*format) break;
		format++;

		olds = s;
		switch (*format++) {
		case 'a':
			s = s_prnt(s, maxsize,
					_days[timeptr->tm_wday], ABB_LEN);
			maxsize -= s - olds;
			break;
		case 'A':
			s = s_prnt(s, maxsize, _days[timeptr->tm_wday], -1);
			maxsize -= s - olds;
			break;
		case 'b':
			s = s_prnt(s, maxsize,
					_months[timeptr->tm_mon], ABB_LEN);
			maxsize -= s - olds;
			break;
		case 'B':
			s = s_prnt(s, maxsize, _months[timeptr->tm_mon], -1);
			maxsize -= s - olds;
			break;
		case 'c':
			n = strftime(s, maxsize,
					"%a %b %d %H:%M:%S %Y", timeptr);
			if (n) maxsize -= n;
			else maxsize = 0;
			s += n;
			break;
		case 'd':
			s = u_prnt(s, maxsize, timeptr->tm_mday, 2);
			maxsize -= s - olds;
			break;
		case 'H':
			s = u_prnt(s, maxsize, timeptr->tm_hour, 2);
			maxsize -= s - olds;
			break;
		case 'I':
			s = u_prnt(s, maxsize,
					(timeptr->tm_hour + 11) % 12 + 1, 2);
			maxsize -= s - olds;
			break;
		case 'j':
			s = u_prnt(s, maxsize, timeptr->tm_yday + 1, 3);
			maxsize -= s - olds;
			break;
		case 'm':
			s = u_prnt(s, maxsize, timeptr->tm_mon + 1, 2);
			maxsize -= s - olds;
			break;
		case 'M':
			s = u_prnt(s, maxsize, timeptr->tm_min, 2);
			maxsize -= s - olds;
			break;
		case 'p':
			s = s_prnt(s, maxsize,
				    (timeptr->tm_hour < 12) ? "AM" : "PM", 2);
			maxsize -= s - olds;
			break;
		case 'S':
			s = u_prnt(s, maxsize, timeptr->tm_sec, 2);
			maxsize -= s - olds;
			break;
		case 'U':
			s = u_prnt(s, maxsize,		/* ??? */
			    (timeptr->tm_yday + 7 - timeptr->tm_wday) / 7, 2);
			maxsize -= s - olds;
			break;
		case 'w':
			s = u_prnt(s, maxsize, timeptr->tm_wday, 1);
			maxsize -= s - olds;
			break;
		case 'W':
			s = u_prnt(s, maxsize,		/* ??? */
			    (timeptr->tm_yday+7-(timeptr->tm_wday+6)%7)/7,2);
			maxsize -= s - olds;
			break;
		case 'x':
			n = strftime(s, maxsize, "%a %b %d %Y", timeptr);
			if (n) maxsize -= n;
			else maxsize = 0;
			s += n;
			break;
		case 'X':
			n = strftime(s, maxsize, "%H:%M:%S", timeptr);
			if (n) maxsize -= n;
			else maxsize = 0;
			s += n;
			break;
		case 'y':
			s = u_prnt(s, maxsize, timeptr->tm_year % 100, 2);
			maxsize -= s - olds;
			break;
		case 'Y':
			s = u_prnt(s, maxsize, timeptr->tm_year + YEAR0, -1);
			maxsize -= s - olds;
			break;
		case 'Z':
			s = s_prnt(s, maxsize,
					_tzname[(timeptr->tm_isdst > 0)], -1);
			maxsize -= s - olds;
			break;
		case '%':
			*s++ = '%';
			maxsize--;
			break;
		default:
			/* A conversion error. Leave the loop. */
			while (*format) format++;
			break;
		}

	}
	if (maxsize) {
		*s = '\0';
		return s - firsts;
	}
	return 0;	/* The buffer is full */
}
Beispiel #19
0
FILE *open_gps_file (NV_CHAR *path)
{
  FILE                   *fp;
  NV_INT32               i;
  GPS_OUTPUT_T           gps;
  time_t                 tv_sec;
  NV_INT32               tv_nsec;
  struct tm              tm;
  static NV_INT32        tz_set = 0;


  NV_INT32 big_endian ();


  sscanf (&path[strlen (path) - 15], "%02d%02d%02d", &year, &month, &day);


  /*  tm struct wants years since 1900!!!  */

  tm.tm_year = year + 100;
  tm.tm_mon = month - 1;
  tm.tm_mday = day;
  tm.tm_hour = 0.0;
  tm.tm_min = 0.0;
  tm.tm_sec = 0.0;
  tm.tm_isdst = -1;

  if (!tz_set)
    {
#ifdef NVWIN3X
  #ifdef __MINGW64__
      _putenv("TZ=GMT");
      _tzset();
  #else
      _putenv("TZ=GMT");
      _tzset();
  #endif
#else
      putenv("TZ=GMT");
      tzset();
#endif
      tz_set = 1;
    }


  /*  Get seconds from the epoch (01-01-1970) for the date in the filename. 
      This will also give us the day of the week for the GPS seconds of
      week calculation.  */

  tv_sec = mktime (&tm);
  tv_nsec = 0.0;


  /*  Subtract the number of days since Saturday midnight (Sunday morning) in seconds.  */

  tv_sec = tv_sec - (tm.tm_wday * 86400);
  start_week = tv_sec;


  /*  We have to assume that the file is little endian since there is no
      header and no field that we can use to deduce what it is.  */

  swap = (NV_BOOL) big_endian ();


  if ((fp = fopen (path, "rb")) == NULL)
    {
      return ((FILE *) NULL);
    }
  else
    {
      fread (&gps, sizeof (GPS_OUTPUT_T), 1, fp);
      if (swap) swap_gps (&gps);
      start_timestamp = (NV_INT64) (((NV_FLOAT64) start_week + gps.gps_time) * 1000000.0);
      start_record = 0;


      i = fseeko64 (fp, -sizeof (GPS_OUTPUT_T), SEEK_END);

      fread (&gps, sizeof (GPS_OUTPUT_T), 1, fp);
      if (swap) swap_gps (&gps);
      end_timestamp = (NV_INT64) (((NV_FLOAT64) start_week + gps.gps_time) * 1000000.0);

      end_record = ftell (fp) / sizeof (GPS_OUTPUT_T);

      fseek (fp, 0, SEEK_SET);
    }

  return (fp);
}
Beispiel #20
0
void setUtcTZ()
{
    _wputenv(L"TZ=UTC0UTC");
    _tzset();
}
Beispiel #21
0
static void my_win_init(void)
{
  DBUG_ENTER("my_win_init");

#if defined(_MSC_VER)
#if _MSC_VER < 1300
  /* 
    Clear the OS system variable TZ and avoid the 100% CPU usage
    Only for old versions of Visual C++
  */
  _putenv( "TZ=" ); 
#endif 
#if _MSC_VER >= 1400
  /* this is required to make crt functions return -1 appropriately */
  _set_invalid_parameter_handler(my_parameter_handler);
#endif
#endif  
#ifdef __MSVC_RUNTIME_CHECKS
  /*
    Install handler to send RTC (Runtime Error Check) warnings
    to log file
  */
  _RTC_SetErrorFunc(handle_rtc_failure);
#endif

  _tzset();

               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
  /* The following is used by time functions */
#define OFFSET_TO_EPOC ((__int64) 134774 * 24 * 60 * 60 * 1000 * 1000 * 10)
#define MS 10000000
  {
    FILETIME ft;
    LARGE_INTEGER li, t_cnt;
    DBUG_ASSERT(sizeof(LARGE_INTEGER) == sizeof(query_performance_frequency));
    if (QueryPerformanceFrequency((LARGE_INTEGER *)&query_performance_frequency) == 0)
      query_performance_frequency= 0;
    else
    {
      GetSystemTimeAsFileTime(&ft);
      li.LowPart=  ft.dwLowDateTime;
      li.HighPart= ft.dwHighDateTime;
      query_performance_offset= li.QuadPart-OFFSET_TO_EPOC;
      QueryPerformanceCounter(&t_cnt);
      query_performance_offset-= (t_cnt.QuadPart /
                                  query_performance_frequency * MS +
                                  t_cnt.QuadPart %
                                  query_performance_frequency * MS /
                                  query_performance_frequency);
    }
  }

  {
    /*
      Open HKEY_LOCAL_MACHINE\SOFTWARE\MySQL and set any strings found
      there as environment variables
    */
    HKEY key_handle;
    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, (LPCTSTR)"SOFTWARE\\MySQL",
                     0, KEY_READ, &key_handle) == ERROR_SUCCESS)
    {
      LONG ret;
      DWORD index= 0;
      DWORD type;
      char key_name[256], key_data[1024];
      DWORD key_name_len= sizeof(key_name) - 1;
      DWORD key_data_len= sizeof(key_data) - 1;

      while ((ret= RegEnumValue(key_handle, index++,
                                key_name, &key_name_len,
                                NULL, &type, (LPBYTE)&key_data,
                                &key_data_len)) != ERROR_NO_MORE_ITEMS)
      {
        char env_string[sizeof(key_name) + sizeof(key_data) + 2];

        if (ret == ERROR_MORE_DATA)
        {
          /* Registry value larger than 'key_data', skip it */
          DBUG_PRINT("error", ("Skipped registry value that was too large"));
        }
        else if (ret == ERROR_SUCCESS)
        {
          if (type == REG_SZ)
          {
            strxmov(env_string, key_name, "=", key_data, NullS);

            /* variable for putenv must be allocated ! */
            putenv(strdup(env_string)) ;
          }
        }
        else
        {
          /* Unhandled error, break out of loop */
          break;
        }

        key_name_len= sizeof(key_name) - 1;
        key_data_len= sizeof(key_data) - 1;
      }

      RegCloseKey(key_handle) ;
    }
  }
  DBUG_VOID_RETURN ;
}
Beispiel #22
0
void setLocalTZ()
{
    _wputenv(localTZ);
    _tzset();
}
Beispiel #23
0
struct tm * __cdecl localtime (
        const time_t *ptime
        )
{
        REG1 struct tm *ptm;
        long ltime;

        /*
         * Check for illegal time_t value
         */
        if ( (long)*ptime < 0L )
                return( NULL );

#ifdef _WIN32
        __tzset();
#else  /* _WIN32 */
#if defined (_M_MPPC) || defined (_M_M68K)
        _tzset();
#endif  /* defined (_M_MPPC) || defined (_M_M68K) */
#endif  /* _WIN32 */

        if ( (*ptime > 3 * _DAY_SEC) && (*ptime < LONG_MAX - 3 * _DAY_SEC) ) {
                /*
                 * The date does not fall within the first three, or last
                 * three, representable days of the Epoch. Therefore, there
                 * is no possibility of overflowing or underflowing the
                 * time_t representation as we compensate for timezone and
                 * Daylight Savings Time.
                 */

                ltime = (long)*ptime - _timezone;
                ptm = gmtime( (time_t *)&ltime );

                /*
                 * Check and adjust for Daylight Saving Time.
                 */
                if ( _daylight && _isindst( ptm ) ) {
                        ltime -= _dstbias;
                        ptm = gmtime( (time_t *)&ltime );
                        ptm->tm_isdst = 1;
                }
        }
        else {
                ptm = gmtime( ptime );

                /*
                 * The date falls with the first three, or last three days
                 * of the Epoch. It is possible the time_t representation
                 * would overflow or underflow while compensating for
                 * timezone and Daylight Savings Time. Therefore, make the
                 * timezone and Daylight Savings Time adjustments directly
                 * in the tm structure. The beginning of the Epoch is
                 * 00:00:00, 01-01-70 (UTC) and the last representable second
                 * in the Epoch is 03:14:07, 01-19-2038 (UTC). This will be
                 * used in the calculations below.
                 *
                 * First, adjust for the timezone.
                 */
                if ( _isindst(ptm) )
                        ltime = (long)ptm->tm_sec - (_timezone + _dstbias);
                else
                        ltime = (long)ptm->tm_sec - _timezone;
                ptm->tm_sec = (int)(ltime % 60);
                if ( ptm->tm_sec < 0 ) {
                        ptm->tm_sec += 60;
                        ltime -= 60;
                }

                ltime = (long)ptm->tm_min + ltime/60;
                ptm->tm_min = (int)(ltime % 60);
                if ( ptm->tm_min < 0 ) {
                        ptm->tm_min += 60;
                        ltime -= 60;
                }

                ltime = (long)ptm->tm_hour + ltime/60;
                ptm->tm_hour = (int)(ltime % 24);
                if ( ptm->tm_hour < 0 ) {
                        ptm->tm_hour += 24;
                        ltime -=24;
                }

                ltime /= 24;

                if ( ltime > 0L ) {
                        /*
                         * There is no possibility of overflowing the tm_mday
                         * and tm_yday fields since the date can be no later
                         * than January 19.
                         */
                        ptm->tm_wday = (ptm->tm_wday + ltime) % 7;
                        ptm->tm_mday += ltime;
                        ptm->tm_yday += ltime;
                }
                else if ( ltime < 0L ) {
                        /*
                         * It is possible to underflow the tm_mday and tm_yday
                         * fields. If this happens, then adjusted date must
                         * lie in December 1969.
                         */
                        ptm->tm_wday = (ptm->tm_wday + 7 + ltime) % 7;
                        if ( (ptm->tm_mday += ltime) <= 0 ) {
                                ptm->tm_mday += 31;
                                ptm->tm_yday = 364;
                                ptm->tm_mon = 11;
                                ptm->tm_year--;
                        }
                        else {
                                ptm->tm_yday += ltime;
                        }
                }


        }


        return(ptm);
}
CVMBool
CVMgetJavaProperties(java_props_t *sprops)
{
    const char *v; /* tmp var */

    if (sprops->user_dir) {
        return CVM_TRUE;
    }

    /* tmp dir */
    {
      DWORD err;
      char consdir[MAX_PATH];        
        TCHAR tmpdir[MAX_PATH];
        if (GetTempPath(MAX_PATH, tmpdir) <= 0) {         
          char msg[1024];
          jio_snprintf(msg, 1024,
                       "GetTempPath: error=%d", GetLastError());
          return CVM_FALSE;
        }
        // convert wide character to sequence of multibyte characters. 
        copyToMCHAR(consdir, tmpdir, MAX_PATH);
        sprops->tmp_dir = strdup(consdir);
    }

    /* Printing properties */
    sprops->printerJob = "sun.awt.motif.PSPrinterJob";

    /* Java 2D properties */
    sprops->graphics_env = NULL;
    sprops->awt_toolkit = NULL;

    v = getenv("JAVA_FONTS");

    /* If JAVA_FONTS is not set, the system-dependent fontpath will
     * be evaluated later
     */
    sprops->font_dir = v ? v : "";


    sprops->cpu_isalist = NULL;

    /* endianness of platform */
    {
        unsigned int endianTest = 0xff000000;
        if (((char*)(&endianTest))[0] != 0)
            sprops->cpu_endian = "big";
        else
            sprops->cpu_endian = "little";
    }

    /* os properties */
    {
        OSVERSIONINFO si;

	si.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); 
	if (GetVersionEx(&si) == 0) {
		printf("GetVersion Error \n");
	}

	switch (si.dwPlatformId) {
	case VER_PLATFORM_WIN32s:
		sprops->os_name = strdup("Windows 3.1");
		sprops->os_version = strdup("Unknown");
		break;
	case VER_PLATFORM_WIN32_WINDOWS:
		if (si.dwMinorVersion == 0)
		    sprops->os_name = strdup("Windows 95");
		else
		    sprops->os_name = strdup("Windows 98");
		sprops->os_version = strdup((char*)si.szCSDVersion);
		break;
	case VER_PLATFORM_WIN32_NT:
          if (si.dwMajorVersion <= 4) {
	        sprops->os_name = strdup("Windows NT");
          } else if (si.dwMajorVersion == 5) {
	        switch (si.dwMinorVersion) {
		case 0:
		    sprops->os_name = strdup("Windows 2000");
		    break;
	        case 1:
		    sprops->os_name = strdup("Windows XP");
		    break;
	        case 2:
		    sprops->os_name = strdup("Windows 2003");
		    break;
	        default:
		    sprops->os_name = strdup("Windows NT (unknown)");
		    break;
                }
          } else {
            sprops->os_name = strdup("Windows NT (unknown)");
          }

          sprops->os_version = malloc(30);
          if (sprops->os_version == NULL) break;
          sprintf((char*)sprops->os_version, "%d.%d", si.dwMajorVersion, si.dwMinorVersion);
          break;

#ifdef WINCE
	case VER_PLATFORM_WIN32_CE: 
		sprops->os_name = strdup("Windows CE");
		sprops->os_version = malloc(32);
		if (sprops->os_name == NULL || sprops->os_version == NULL)
		    break;
		sprintf((char*)sprops->os_version, "%d.%d build %d",
			si.dwMajorVersion, si.dwMinorVersion,
			si.dwBuildNumber);
		break;
#endif
	default:
	        sprops->os_name = strdup("Unknown");
		sprops->os_version = strdup("Unknown");
		break;
	}
	if (sprops->os_name == NULL || sprops->os_version == NULL) {
	    goto out_of_memory;
	}


#ifdef WINCE

	/* Set WINCE processor properties using SYSTEM_INFO */
	{
	  SYSTEM_INFO si;
	  GetSystemInfo (&si);
	  switch (si.wProcessorArchitecture) {
	  case PROCESSOR_ARCHITECTURE_INTEL:
	    sprops->os_arch = strdup("x86");
	    break;
	  case PROCESSOR_ARCHITECTURE_MIPS:
	    sprops->os_arch = strdup("mips");
	    break;
	  case PROCESSOR_ARCHITECTURE_SHX:
	    sprops->os_arch = strdup("shx");
	    break;
	  case PROCESSOR_ARCHITECTURE_ARM:
	    sprops->os_arch = strdup("arm");
	    break;
	  case PROCESSOR_ARCHITECTURE_UNKNOWN:
	  default:
	    sprops->os_arch = strdup("unknown");   
	  }
	}

#else  /* not WINCE */

	/* Set Windows XP/2000 processor properties using SYSTEM_INFO */
	{
	  SYSTEM_INFO si;
	  GetSystemInfo (&si);
	  switch (si.wProcessorArchitecture) {
	  case PROCESSOR_ARCHITECTURE_AMD64:
	    sprops->os_arch = strdup("amd64");
	    break;
	  case PROCESSOR_ARCHITECTURE_IA64:
	    sprops->os_arch = strdup("ia64");
	    break;
	  case PROCESSOR_ARCHITECTURE_INTEL:
	    sprops->os_arch = strdup("x86");
	    break;
	  case PROCESSOR_ARCHITECTURE_UNKNOWN:
	  default:
	    sprops->os_arch = strdup("unknown");   
	  }
	}

#endif /* WINCE */
    }

    /* Determing the language, country, and encoding from the host,
     * and store these in the user.language, user.region, and
     * file.encoding system properties. */
    {
        char *lc = "UTF-8";
#ifndef WINCE
        lc = setlocale(LC_CTYPE, "");
        if (lc == NULL) {
            /*
             * 'lc == null' means system doesn't support user's environment
             * variable's locale.
             */
          setlocale(LC_ALL, "C");
          sprops->language = "en";
          sprops->encoding = "UTF-8";
#else
        if (lc == NULL || !strcmp(lc, "C") || !strcmp(lc, "POSIX")) {
            lc = "en_US";
#endif
        } else {
            /*
             * locale string format in Solaris is
             * <language name>_<region name>.<encoding name>
             * <region name> and <encoding name> are optional.
             */
            char temp[64], *language = NULL, *region = NULL, *encoding = NULL;
            char *std_language = NULL, *std_region = NULL,
                 *std_encoding = NULL;
            char region_variant[64], *variant = NULL, *std_variant = NULL;
            char *p, encoding_variant[64];

            strcpy(temp, lc);
#ifndef WINCE
            setlocale(LC_ALL, lc);
#endif
            /* Parse the language, region, encoding, and variant from the
             * locale.  Any of the elements may be missing, but they must occur
             * in the order language_region.encoding@variant, and must be
             * preceded by their delimiter (except for language).
             *
             * If the locale name (without .encoding@variant, if any) matches
             * any of the names in the locale_aliases list, map it to the
             * corresponding full locale name.  Most of the entries in the
             * locale_aliases list are locales that include a language name but
             * no country name, and this facility is used to map each language
             * to a default country if that's possible.  It's also used to map
             * the Solaris locale aliases to their proper Java locale IDs.
             */
            if ((p = strchr(temp, '.')) != NULL) {
                strcpy(encoding_variant, p); /* Copy the leading '.' */
                *p = '\0';
            } else if ((p = strchr(temp, '@')) != NULL) {
                 strcpy(encoding_variant, p); /* Copy the leading '@' */
                 *p = '\0';
            } else {
                *encoding_variant = '\0';
            }
            
            if (mapLookup(locale_aliases, temp, &p)) {
                strcpy(temp, p);
            }
            
            language = temp;
            if ((region = strchr(temp, '_')) != NULL) {
                *region++ = '\0';
            }
            
            p = encoding_variant;
            if ((encoding = strchr(p, '.')) != NULL) {
                p[encoding++ - p] = '\0';
                p = encoding;
            }
            if ((variant = strchr(p, '@')) != NULL) {
                p[variant++ - p] = '\0';
            }

            /* Normalize the language name */
            std_language = "en";
            if (language != NULL) {
                mapLookup(language_names, language, &std_language);
            }
            sprops->language = std_language;

            /* Normalize the variant name.  Do this BEFORE handling the region
             * name, since the variant name will be incorporated into the
             * user.region property.
             */
            if (variant != NULL) {
                mapLookup(variant_names, variant, &std_variant);
            }

            /* Normalize the region name.  If there is a std_variant, then
             * append it to the region.  This applies even if there is no
             * region, in which case the empty string is used for the region.
             * Note that we only use variants listed in the mapping array;
	     * others are ignored.
             */
            *region_variant = '\0';
            if (region != NULL) {
                std_region = region;
                mapLookup(region_names, region, &std_region);
                strcpy(region_variant, std_region);
            }
            if (std_variant != NULL) {
               strcat(region_variant, "_");
               strcat(region_variant, std_variant);
            }
            if ((*region_variant) != '\0') {
               sprops->region = strdup(region_variant);
	       if (sprops->region == NULL) {
		   goto out_of_memory;
	       }
            }

            /* Normalize the encoding name.  Note that we IGNORE the string
             * 'encoding' extracted from the locale name above.  Instead, we 
             * use the more reliable method of calling nl_langinfo(CODESET).  
             * This function returns an empty string if no encoding is set for
             * the given locale (e.g., the C or POSIX locales); we use the
             * default ISO 8859-1 converter for such locales.  We don't need 
             * to map from the Solaris string to the Java identifier at this 
             * point because that mapping is handled by the character
             * converter alias table in CharacterEncoding.java.
             */
/*
            p = nl_langinfo(CODESET);
	    if (*p == '\0' || strcmp(p, "ANSI_X3.4-1968") == 0) {
		std_encoding = "8859_1";
	    } else {
		std_encoding = p;
	    }
*/
	    std_encoding = "UTF-8";

            sprops->encoding = std_encoding;
        }
    }
    
    sprops->unicode_encoding = "UnicodeLittle";

    /* 
     *  User Properties 
     */
    {  
      DWORD len = 256;
      char *uname, *userprofile;
      int length;   

      /* User Name */
      {
        sprops->user_name = (char *)malloc(len);
        if (sprops->user_name == NULL) {
          goto out_of_memory;
        }
        uname = getenv("USERNAME");
        if (uname != NULL && strlen(uname) > 0) {
          strcpy((char *)sprops->user_name, uname);
        } else {
          GetUserNameA((char*)sprops->user_name, &len);
        }
      }

      /* User Home Directory */
      {
        userprofile = getenv("USERPROFILE");
        if (userprofile != NULL) {
	  length = strlen(userprofile);
          sprops->user_home = (char *)malloc(length + 1);  
          if (sprops->user_home == NULL) {
            goto out_of_memory;
          }
          strcpy((char*)sprops->user_home, userprofile); 
        }          
        else {
          sprops->user_home = strdup("");
        }        
      }
    }
    
    /* User TIMEZONE */
    {
	/*
	 * We defer setting up timezone until it's actually necessary.
	 * Refer to TimeZone.getDefault(). However, the system
	 * property is necessary to be able to be set by the command
	 * line interface -D. Here temporarily set a null string to
	 * timezone.
	 */
#ifndef WINCE
	_tzset(); /* for compatibility */
#endif
	sprops->timezone = "";

    }

    /* Current directory */
#ifndef WINCE
    sprops->user_dir = (char *)malloc(256);
    if (sprops->user_dir == NULL) {
	goto out_of_memory;
    }
    GetCurrentDirectoryA(256, (char*)sprops->user_dir);
#else
    sprops->user_dir ="\\";
#endif

    sprops->file_separator = "\\";
    sprops->path_separator = ";";
    sprops->line_separator = "\n";

    /* Generic Connection Framework (GCF): CommConnection Property */
    /* NOTE: comma-delimited (no spaces) list of available comm (serial)
       ports */
    sprops->commports = "com0";

    return CVM_TRUE;

 out_of_memory:
    CVMreleaseJavaProperties(sprops);
    return CVM_FALSE;
}

/*
 * Free up memory allocated by CVMgetJavaProperties().
 */
void CVMreleaseJavaProperties(java_props_t *sprops)
{
    if (sprops->os_name != NULL) {
	free((char*)sprops->os_name);
    }
    if (sprops->os_version != NULL) {
	free((char*)sprops->os_version);
    }
    if (sprops->region != NULL) {
	free((char*)sprops->region);
    }
    if (sprops->user_name != NULL) {
	free((char*)sprops->user_name);
    }
    if (sprops->user_home != NULL) {
	free((char*)sprops->user_home);
    }
#ifndef WINCE
    if (sprops->user_dir != NULL) {
	free((char*)sprops->user_dir);
    }
#endif
}
Beispiel #25
0
/**
 * Create a tempfile with the given prefix (e.g. "wireshark").
 *
 * @param namebuf If not NULL, receives the full path of the temp file.
 *                Should NOT be freed.
 * @param pfx A prefix for the temporary file.
 * @param sfx [in] A file extension for the temporary file. NULL can be passed
 *                 if no file extension is needed
 * @return The file descriptor of the new tempfile, from mkstemps().
 */
int
create_tempfile(char **namebuf, const char *pfx, const char *sfx)
{
  static struct _tf {
    char *path;
    size_t len;
  } tf[MAX_TEMPFILES];
  static int idx;

  const char *tmp_dir;
  int old_umask;
  int fd;
  time_t current_time;
  char timestr[14 + 1];
  gchar *tmp_file;
  gchar *safe_pfx;
  gchar sep[2] = {0, 0};

  /* The characters in "delimiters" come from:
   * http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx.
   * Add to the list as necessary for other OS's.
   */
  const gchar *delimiters = "<>:\"/\\|?*"
    "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a"
    "\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
    "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f";

  /* Sanitize the pfx to resolve bug 7877 */
  safe_pfx = g_strdup(pfx);
  safe_pfx = g_strdelimit(safe_pfx, delimiters, '-');

  idx = (idx + 1) % MAX_TEMPFILES;

  /*
   * Allocate the buffer if it's not already allocated.
   */
  if (tf[idx].path == NULL) {
    tf[idx].len = INITIAL_PATH_SIZE;
    tf[idx].path = (char *)g_malloc(tf[idx].len);
  }

  tmp_dir = g_get_tmp_dir();

#ifdef _WIN32
  _tzset();
#endif
  current_time = time(NULL);
  /* We trust the OS not to return a time before the Epoch. */
  strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
  sep[0] = G_DIR_SEPARATOR;
  tmp_file = g_strconcat(tmp_dir, sep, safe_pfx, "_", timestr, "_", TMP_FILE_SUFFIX, sfx, NULL);
  g_free(safe_pfx);
  if (strlen(tmp_file) > tf[idx].len) {
    tf[idx].len = strlen(tmp_file) + 1;
    tf[idx].path = (char *)g_realloc(tf[idx].path, tf[idx].len);
  }
  g_strlcpy(tf[idx].path, tmp_file, tf[idx].len);
  g_free(tmp_file);

  if (namebuf) {
    *namebuf = tf[idx].path;
  }
  /* The Single UNIX Specification doesn't say that "mkstemps()"
     creates the temporary file with mode rw-------, so we
     won't assume that all UNIXes will do so; instead, we set
     the umask to 0077 to take away all group and other
     permissions, attempt to create the file, and then put
     the umask back. */
  old_umask = ws_umask(0077);
  fd = mkstemps(tf[idx].path, sfx ? (int) strlen(sfx) : 0);
  ws_umask(old_umask);
  return fd;
}
Beispiel #26
0
char * strptime(const char *buf, const char *fmt, struct tm *tm)
{
#ifdef _MSC_VER
    char** tzname_compat = _tzname;
#else
    char* tzname_compat = tzname;
#endif
    unsigned char c;
    const unsigned char *bp, *ep;
    int alt_format, i, split_year = 0, neg = 0, offs;
    const char *new_fmt;

    bp = (const u_char *)buf;

    while (bp != NULL && (c = *fmt++) != '\0') {
        /* Clear `alternate' modifier prior to new conversion. */
        alt_format = 0;
        i = 0;

        /* Eat up white-space. */
        if (isspace(c)) {
            while (isspace(*bp))
                bp++;
            continue;
        }

        if (c != '%')
            goto literal;


again:      switch (c = *fmt++) {
                case '%':   /* "%%" is converted to "%". */
literal:
                    if (c != *bp++)
                        return NULL;
                    LEGAL_ALT(0);
                    continue;

                    /*
                     * "Alternative" modifiers. Just set the appropriate flag
                     * and start over again.
                     */
                case 'E':   /* "%E?" alternative conversion modifier. */
                    LEGAL_ALT(0);
                    alt_format |= ALT_E;
                    goto again;

                case 'O':   /* "%O?" alternative conversion modifier. */
                    LEGAL_ALT(0);
                    alt_format |= ALT_O;
                    goto again;

                    /*
                     * "Complex" conversion rules, implemented through recursion.
                     */
                    /* we do not need 'c'
                       case 'c': Date and time, using the locale's format. 
                       new_fmt = _ctloc(d_t_fmt);
                       goto recurse;
                       */

                case 'D':   /* The date as "%m/%d/%y". */
                    new_fmt = "%m/%d/%y";
                    LEGAL_ALT(0);
                    goto recurse;

                case 'F':   /* The date as "%Y-%m-%d". */
                    new_fmt = "%Y-%m-%d";
                    LEGAL_ALT(0);
                    goto recurse;

                case 'R':   /* The time as "%H:%M". */
                    new_fmt = "%H:%M";
                    LEGAL_ALT(0);
                    goto recurse;

                case 'r':   /* The time in 12-hour clock representation. */
                    new_fmt = "%I:%M:S %p";//_ctloc(t_fmt_ampm);
                    LEGAL_ALT(0);
                    goto recurse;

                case 'T':   /* The time as "%H:%M:%S". */
                    new_fmt = "%H:%M:%S";
                    LEGAL_ALT(0);
                    goto recurse;

                    /* we don't use 'X'
                       case 'X': The time, using the locale's format.
                       new_fmt =_ctloc(t_fmt);
                       goto recurse;
                       */

                    /* we do not need 'x'
                       case 'x': The date, using the locale's format.
                       new_fmt =_ctloc(d_fmt);*/
recurse:
                    bp = (const u_char *)strptime((const char *)bp,
                            new_fmt, tm);
                    LEGAL_ALT(ALT_E);
                    continue;

                    /*
                     * "Elementary" conversion rules.
                     */
                case 'A':   /* The day of week, using the locale's form. */
                case 'a':
                    bp = find_string(bp, &tm->tm_wday, day, abday, 7);
                    LEGAL_ALT(0);
                    continue;

                case 'B':   /* The month, using the locale's form. */
                case 'b':
                case 'h':
                    bp = find_string(bp, &tm->tm_mon, mon, abmon, 12);
                    LEGAL_ALT(0);
                    continue;

                case 'C':   /* The century number. */
                    i = 20;
                    bp = conv_num(bp, &i, 0, 99);

                    i = i * 100 - TM_YEAR_BASE;
                    if (split_year)
                        i += tm->tm_year % 100;
                    split_year = 1;
                    tm->tm_year = i;
                    LEGAL_ALT(ALT_E);
                    continue;

                case 'd':   /* The day of month. */
                case 'e':
                    bp = conv_num(bp, &tm->tm_mday, 1, 31);
                    LEGAL_ALT(ALT_O);
                    continue;

                case 'k':   /* The hour (24-hour clock representation). */
                    LEGAL_ALT(0);
                    /* FALLTHROUGH */
                case 'H':
                    bp = conv_num(bp, &tm->tm_hour, 0, 23);
                    LEGAL_ALT(ALT_O);
                    continue;

                case 'l':   /* The hour (12-hour clock representation). */
                    LEGAL_ALT(0);
                    /* FALLTHROUGH */
                case 'I':
                    bp = conv_num(bp, &tm->tm_hour, 1, 12);
                    if (tm->tm_hour == 12)
                        tm->tm_hour = 0;
                    LEGAL_ALT(ALT_O);
                    continue;

                case 'j':   /* The day of year. */
                    i = 1;
                    bp = conv_num(bp, &i, 1, 366);
                    tm->tm_yday = i - 1;
                    LEGAL_ALT(0);
                    continue;

                case 'M':   /* The minute. */
                    bp = conv_num(bp, &tm->tm_min, 0, 59);
                    LEGAL_ALT(ALT_O);
                    continue;

                case 'm':   /* The month. */
                    i = 1;
                    bp = conv_num(bp, &i, 1, 12);
                    tm->tm_mon = i - 1;
                    LEGAL_ALT(ALT_O);
                    continue;

                case 'p':   /* The locale's equivalent of AM/PM. */
                    bp = find_string(bp, &i, am_pm, NULL, 2);
                    if (tm->tm_hour > 11)
                        return NULL;
                    tm->tm_hour += i * 12;
                    LEGAL_ALT(0);
                    continue;

                case 'S':   /* The seconds. */
                    bp = conv_num(bp, &tm->tm_sec, 0, 61);
                    LEGAL_ALT(ALT_O);
                    continue;

#ifndef TIME_MAX
#define TIME_MAX  INT64_MAX
#endif
                case 's':   /* seconds since the epoch */
                    {
                        time_t sse = 0;
                        uint64_t rulim = TIME_MAX;

                        if (*bp < '0' || *bp > '9') {
                            bp = NULL;
                            continue;
                        }

                        do {
                            sse *= 10;
                            sse += *bp++ - '0';
                            rulim /= 10;
                        } while ((sse * 10 <= TIME_MAX) &&
                                rulim && *bp >= '0' && *bp <= '9');

                        if (sse < 0 || (uint64_t)sse > TIME_MAX) {
                            bp = NULL;
                            continue;
                        }

                        tm = localtime(&sse);
                        if (tm == NULL)
                            bp = NULL;
                    }
                    continue;

                case 'U':   /* The week of year, beginning on sunday. */
                case 'W':   /* The week of year, beginning on monday. */
                    /*
                     * XXX This is bogus, as we can not assume any valid
                     * information present in the tm structure at this
                     * point to calculate a real value, so just check the
                     * range for now.
                     */
                    bp = conv_num(bp, &i, 0, 53);
                    LEGAL_ALT(ALT_O);
                    continue;

                case 'w':   /* The day of week, beginning on sunday. */
                    bp = conv_num(bp, &tm->tm_wday, 0, 6);
                    LEGAL_ALT(ALT_O);
                    continue;

                case 'u':   /* The day of week, monday = 1. */
                    bp = conv_num(bp, &i, 1, 7);
                    tm->tm_wday = i % 7;
                    LEGAL_ALT(ALT_O);
                    continue;

                case 'g':   /* The year corresponding to the ISO week
                             * number but without the century.
                             */
                    bp = conv_num(bp, &i, 0, 99);
                    continue;

                case 'G':   /* The year corresponding to the ISO week
                             * number with century.
                             */
                    do
                        bp++;
                    while (isdigit(*bp));
                    continue;

                case 'V':   /* The ISO 8601:1988 week number as decimal */
                    bp = conv_num(bp, &i, 0, 53);
                    continue;

                case 'Y':   /* The year. */
                    i = TM_YEAR_BASE; /* just for data sanity... */
                    bp = conv_num(bp, &i, 0, 9999);
                    tm->tm_year = i - TM_YEAR_BASE;
                    LEGAL_ALT(ALT_E);
                    continue;

                case 'y':   /* The year within 100 years of the epoch. */
                    /* LEGAL_ALT(ALT_E | ALT_O); */
                    bp = conv_num(bp, &i, 0, 99);

                    if (split_year)
                        /* preserve century */
                        i += (tm->tm_year / 100) * 100;
                    else {
                        split_year = 1;
                        if (i <= 68)
                            i = i + 2000 - TM_YEAR_BASE;
                        else
                            i = i + 1900 - TM_YEAR_BASE;
                    }
                    tm->tm_year = i;
                    continue;

                case 'Z':
                    _tzset();
                    if (strncasecmp((const char *)bp, gmt, 3) == 0
                            || strncasecmp((const char *)bp, utc, 3) == 0) {
                        tm->tm_isdst = 0;
#ifdef TM_GMTOFF
                        tm->TM_GMTOFF = 0;
#endif
#ifdef TM_ZONE
                        tm->TM_ZONE = gmt;
#endif
                        bp += 3;
                    } else {
                        ep = find_string(bp, &i,
                                (const char * const *)tzname_compat,
                                NULL, 2);
                        if (ep != NULL) {
                            tm->tm_isdst = i;
#ifdef TM_GMTOFF
                            tm->TM_GMTOFF = -(timezone);
#endif
#ifdef TM_ZONE
                            tm->TM_ZONE = tzname_compat[i];
#endif
                        }
                        bp = ep;
                    }
                    continue;

                case 'z':
                    /*
                     * We recognize all ISO 8601 formats:
                     * Z  = Zulu time/UTC
                     * [+-]hhmm
                     * [+-]hh:mm
                     * [+-]hh
                     * We recognize all RFC-822/RFC-2822 formats:
                     * UT|GMT
                     *          North American : UTC offsets
                     * E[DS]T = Eastern : -4 | -5
                     * C[DS]T = Central : -5 | -6
                     * M[DS]T = Mountain: -6 | -7
                     * P[DS]T = Pacific : -7 | -8
                     *          Military
                     * [A-IL-M] = -1 ... -9 (J not used)
                     * [N-Y]  = +1 ... +12
                     */
                    while (isspace(*bp))
                        bp++;

                    switch (*bp++) {
                        case 'G':
                            if (*bp++ != 'M')
                                return NULL;
                            /*FALLTHROUGH*/
                        case 'U':
                            if (*bp++ != 'T')
                                return NULL;
                            /*FALLTHROUGH*/
                        case 'Z':
                            tm->tm_isdst = 0;
#ifdef TM_GMTOFF
                            tm->TM_GMTOFF = 0;
#endif
#ifdef TM_ZONE
                            tm->TM_ZONE = utc;
#endif
                            continue;
                        case '+':
                            neg = 0;
                            break;
                        case '-':
                            neg = 1;
                            break;
                        default:
                            --bp;
                            ep = find_string(bp, &i, nast, NULL, 4);
                            if (ep != NULL) {
#ifdef TM_GMTOFF
                                tm->TM_GMTOFF = -5 - i;
#endif
#ifdef TM_ZONE
                                tm->TM_ZONE = __UNCONST(nast[i]);
#endif
                                bp = ep;
                                continue;
                            }
                            ep = find_string(bp, &i, nadt, NULL, 4);
                            if (ep != NULL) {
                                tm->tm_isdst = 1;
#ifdef TM_GMTOFF
                                tm->TM_GMTOFF = -4 - i;
#endif
#ifdef TM_ZONE
                                tm->TM_ZONE = __UNCONST(nadt[i]);
#endif
                                bp = ep;
                                continue;
                            }

                            if ((*bp >= 'A' && *bp <= 'I') ||
                                    (*bp >= 'L' && *bp <= 'Y')) {
#ifdef TM_GMTOFF
                                /* Argh! No 'J'! */
                                if (*bp >= 'A' && *bp <= 'I')
                                    tm->TM_GMTOFF =
                                        ('A' - 1) - (int)*bp;
                                else if (*bp >= 'L' && *bp <= 'M')
                                    tm->TM_GMTOFF = 'A' - (int)*bp;
                                else if (*bp >= 'N' && *bp <= 'Y')
                                    tm->TM_GMTOFF = (int)*bp - 'M';
#endif
#ifdef TM_ZONE
                                tm->TM_ZONE = NULL; /* XXX */
#endif
                                bp++;
                                continue;
                            }
                            return NULL;
                    }
                    offs = 0;
                    for (i = 0; i < 4; ) {
                        if (isdigit(*bp)) {
                            offs = offs * 10 + (*bp++ - '0');
                            i++;
                            continue;
                        }
                        if (i == 2 && *bp == ':') {
                            bp++;
                            continue;
                        }
                        break;
                    }
                    switch (i) {
                        case 2:
                            offs *= 100;
                            break;
                        case 4:
                            i = offs % 100;
                            if (i >= 60)
                                return NULL;
                            /* Convert minutes into decimal */
                            offs = (offs / 100) * 100 + (i * 50) / 30;
                            break;
                        default:
                            return NULL;
                    }
                    if (neg)
                        offs = -offs;
                    tm->tm_isdst = 0; /* XXX */
#ifdef TM_GMTOFF
                    tm->TM_GMTOFF = offs;
#endif
#ifdef TM_ZONE
                    tm->TM_ZONE = NULL;  /* XXX */
#endif
                    continue;

                    /*
                     * Miscellaneous conversions.
                     */
                case 'n':   /* Any kind of white-space. */
                case 't':
                    while (isspace(*bp))
                        bp++;
                    LEGAL_ALT(0);
                    continue;


                default: /* Unknown/unsupported conversion. */
                    return NULL;
            }
    }

    return (char *)(bp);
}
Beispiel #27
0
		file_logger(std::wstring path, std::wstring filename) : file_appender(path, filename), datemask_(_T("%Y-%m-%d %H:%M:%S")) {
			_tzset();
		}
Beispiel #28
0
void FormatTime(ScriptValue &s, ScriptValue *args) {
	unsigned char *c = args[0].stringVal->value;
	if (!AllocateStringValue(s, (int)(3 * strlen(c) + 14))) return;
	static bool settz = 0;
	if (args[0].stringVal->value[0] == 'S') {
		args[0].stringVal->value[0] = args[0].stringVal->value[0];
	}
	// Nasty layout, but boils down to:  If a tz is specified, try to set it.
	// If either couldn't set it or not specified and was set previously, unset it.
	while (1) {
		if (args[2].stringVal->len >= 1 && args[2].stringVal->len <= 20) {
			if (args[2].stringVal->len < 4 || (args[2].stringVal->len == 4 && !IsNumber(args[2].stringVal->value[3]))) {
				for (int i=0; i<sizeof(tzlist)/sizeof(tzlist[0]); i++) {
					if (!stricmp(tzlist[i][0], (char*)args[2].stringVal->value)) {
						char temp[60] = "TZ=";
						sprintf(temp+3, tzlist[i][1]);
						if (!_putenv(temp)) {
							_tzset();
							settz = 1;
							break;
						}
					}
				}
			}
			else {
				wchar_t temp[60] = L"TZ=";
				if (UTF8toUTF16(temp+3, args[2].stringVal->value, args[2].stringVal->len) > 0) {
					if (!_wputenv(temp)) {
						_tzset();
						settz = 1;
						break;
					}
				}
			}
		}
		if (settz) {
			if (!_putenv("TZ=")) {
				_tzset();
				settz = 0;
			}
		}
		break;
	}
	static LCID locale = 0;
	if (!locale) {
		locale = GetThreadLocale();
	}
	__int64 x = args[1].intVal;
	if (!x) x = time64i();
	tm *date = _localtime64(&x);
	SYSTEMTIME st;

	st.wYear = date->tm_year+1900;
	st.wMonth = date->tm_mon+1;
	st.wDayOfWeek = date->tm_wday;
	st.wDay = date->tm_mday;
	st.wHour = date->tm_hour;
	st.wMinute = date->tm_min;
	st.wSecond = date->tm_sec;
	st.wMilliseconds = 0;
	char *out = (char*) s.stringVal->value;
	char * start = (char*) c;
	//static const char *wday[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	//static const char *wday2[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
	//static const char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	//static const char *months2[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	while (*start) {
		if (LCASE(start[0]) == 'h') {
			int h = date->tm_hour;
			if (*start == 'h') {
				if (h >12) h -= 12;
				else if (!h) h = 12;
			}
			GenericDisplay(start, out, h);
		}
		else if (LCASE(start[0]) == 'n')
			GenericDisplay(start, out, date->tm_min);
		else if (LCASE(start[0]) == 's')
			GenericDisplay(start, out, date->tm_sec);
		else if (LCASE(start[0]) == 't') {
			char letter = 'A';
			if (date->tm_hour >= 12) letter = 'P';
			if (start[0] == 't')
				out++[0]  = LCASE(letter);
			else
				out++[0]  = letter;
			start ++;
			if (start[0] == 't') {
				out++[0]  = 'm';
				start ++;
			}
			else if (start[0] == 'T') {
				out++[0]  = 'M';
				start ++;
			}
		}
		else if (LCASE(start[0]) == 'd') {
			if (LCASE(start[1]) == 'd' && LCASE(start[2]) == 'd') {
				start += 2;
				int incr = 1;
				wchar_t day[100];
				int len;
				if (LCASE(start[1]) == 'd') {
					len = GetDateFormat(locale, 0, &st, L"dddd", day, sizeof(day)/sizeof(wchar_t));
					//day = wday2[date->tm_wday];
					incr = 2;
				}
				else {
					len = GetDateFormat(locale, 0, &st, L"ddd", day, sizeof(day)/sizeof(wchar_t));
				}
				if (len < 0) len = 0;
				else if (len > 99) len = 99;
				day[len] = 0;
				int e = GetLastError();
				wchar_t *p = day;
				int i;
				for (i=0; i<len && i <99; i++) {
					p[i] = towupper(p[i]);
					if (start[0] != 'D') break;
				}
				UTF16toUTF8(out, day);
				out += strlen(out);
				start += incr;
			}
			else
				GenericDisplay(start, out, date->tm_mday);
		}
		else if (LCASE(start[0]) == 'm') {
			if (LCASE(start[1]) == 'm' && LCASE(start[2]) == 'm') {
				start += 2;
				int incr = 1;
				wchar_t day[100];
				int len;
				if (LCASE(start[1]) == 'm') {
					len = GetDateFormat(locale, 0, &st, L"MMMM", day, sizeof(day)/sizeof(wchar_t));
					//day = wday2[date->tm_wday];
					incr = 2;
				}
				else {
					len = GetDateFormat(locale, 0, &st, L"MMM", day, sizeof(day)/sizeof(wchar_t));
				}
				if (len < 0) len = 0;
				else if (len > 99) len = 99;
				day[len] = 0;
				int e = GetLastError();
				wchar_t *p = day;
				int i;
				for (i=0; i<len && i <99; i++) {
					p[i] = towupper(p[i]);
					if (start[0] != 'M') break;
				}
				UTF16toUTF8(out, day);
				out += strlen(out);
				start += incr;
			}
			else
				GenericDisplay(start, out, 1+date->tm_mon);
		}
		else if (LCASE(start[0]) == 'y') {
			int year = date->tm_year%100;
			if (LCASE(start[1]) == 'y') {
				start++;
				if (LCASE(start[1]) == 'y') {
					start ++;
					year = 1900 + date->tm_year;
					if (LCASE(start[1]) == 'y') start++;
				}
			}
			sprintf(out, "%02i", year);
			out+=strlen(out);
			start++;
		}
		else {
			out ++[0] = start++[0];
		}
		if ((out-(char*)s.stringVal->value) + 20 > s.stringVal->len) {
			size_t d = out - (char*)s.stringVal->value;
			ResizeStringValue(s, s.stringVal->len+50);
			out = (char*)s.stringVal->value + d;
		}
	}
	ResizeStringValue(s, (int)(out-(char*)s.stringVal->value));
}
Beispiel #29
0
PHPAPI int gettimeofday(struct timeval *time_Info, struct timezone *timezone_Info)
{
	__int64 timer;
	LARGE_INTEGER li;
	BOOL b;
	double dt;
	TSRMLS_FETCH();

	/* Get the time, if they want it */
	if (time_Info != NULL) {
		if (PW32G(starttime).tv_sec == 0) {
            b = QueryPerformanceFrequency(&li);
            if (!b) {
                PW32G(starttime).tv_sec = -1;
            }
            else {
                PW32G(freq) = li.QuadPart;
                b = QueryPerformanceCounter(&li);
                if (!b) {
                    PW32G(starttime).tv_sec = -1;
                }
                else {
                    getfilesystemtime(&PW32G(starttime));
                    timer = li.QuadPart;
                    dt = (double)timer/PW32G(freq);
                    PW32G(starttime).tv_usec -= (int)((dt-(int)dt)*1000000);
                    if (PW32G(starttime).tv_usec < 0) {
                        PW32G(starttime).tv_usec += 1000000;
                        --PW32G(starttime).tv_sec;
                    }
                    PW32G(starttime).tv_sec -= (int)dt;
                }
            }
        }
        if (PW32G(starttime).tv_sec > 0) {
            b = QueryPerformanceCounter(&li);
            if (!b) {
                PW32G(starttime).tv_sec = -1;
            }
            else {
                timer = li.QuadPart;
                if (timer < PW32G(lasttime)) {
                    getfilesystemtime(time_Info);
                    dt = (double)timer/PW32G(freq);
                    PW32G(starttime) = *time_Info;
                    PW32G(starttime).tv_usec -= (int)((dt-(int)dt)*1000000);
                    if (PW32G(starttime).tv_usec < 0) {
                        PW32G(starttime).tv_usec += 1000000;
                        --PW32G(starttime).tv_sec;
                    }
                    PW32G(starttime).tv_sec -= (int)dt;
                }
                else {
                    PW32G(lasttime) = timer;
                    dt = (double)timer/PW32G(freq);
                    time_Info->tv_sec = PW32G(starttime).tv_sec + (int)dt;
                    time_Info->tv_usec = PW32G(starttime).tv_usec + (int)((dt-(int)dt)*1000000);
                    if (time_Info->tv_usec > 1000000) {
                        time_Info->tv_usec -= 1000000;
                        ++time_Info->tv_sec;
                    }
                }
            }
        }
        if (PW32G(starttime).tv_sec < 0) {
            getfilesystemtime(time_Info);
        }

	}
	/* Get the timezone, if they want it */
	if (timezone_Info != NULL) {
		_tzset();
		timezone_Info->tz_minuteswest = _timezone;
		timezone_Info->tz_dsttime = _daylight;
	}
	/* And return */
	return 0;
}
Beispiel #30
0
int
not_an_API_LeashAFSGetToken(
    TICKETINFO * ticketinfo,
    TicketList** ticketList,
    char * kerberosPrincipal
    )
{
#ifdef NO_AFS
    return(0);
#else
    struct ktc_principal    aserver;
    struct ktc_principal    aclient;
    struct ktc_token        atoken;
    int                     EndMonth;
    int                     EndDay;
    int                     cellNum;
    int                     BreakAtEnd;
    char                    UserName[64];
    char                    CellName[64];
    char                    ServiceName[64];
    char                    InstanceName[64];
    char                    EndTime[16];
    char                    Buffer[256];
    char                    Months[12][4] = {"Jan\0", "Feb\0", "Mar\0", "Apr\0", "May\0", "Jun\0", "Jul\0", "Aug\0", "Sep\0", "Oct\0", "Nov\0", "Dec\0"};
    char                    TokenStatus[16];
    time_t                  CurrentTime;
    struct tm               *newtime;
    DWORD                   CurrentState;
    DWORD                   rc;
    char                    HostName[64];


    TicketList* list = NULL;
    if ( ticketinfo ) {
        ticketinfo->btickets = NO_TICKETS;
        ticketinfo->principal[0] = '\0';
    }
    if ( !kerberosPrincipal )
        kerberosPrincipal = "";

    if (!AfsAvailable || GetAfsStatus(&AfsOnLine) && !AfsOnLine)
        return(0);

    CurrentState = 0;
    memset(HostName, '\0', sizeof(HostName));
    gethostname(HostName, sizeof(HostName));
    if (GetServiceStatus(HostName, TRANSARCAFSDAEMON, &CurrentState) != NOERROR)
        return(0);
    if (CurrentState != SERVICE_RUNNING)
        return(0);

    BreakAtEnd = 0;
    cellNum = 0;
    while (1)
    {
        if (rc = ktc_ListTokens(cellNum, &cellNum, &aserver))
        {
            if (rc != KTC_NOENT)
                return(0);

            if (BreakAtEnd == 1)
                break;
        }
        BreakAtEnd = 1;
        memset(&atoken, '\0', sizeof(atoken));
        if (rc = ktc_GetToken(&aserver, &atoken, sizeof(atoken), &aclient))
        {
            if (rc == KTC_ERROR)
                return(0);

            continue;
        }

        if (!list)
        {
            list = (TicketList*) calloc(1, sizeof(TicketList));
            (*ticketList) = list;
        }
        else
        {
            list->next = (struct TicketList*) calloc(1, sizeof(TicketList));
            list = (TicketList*) list->next;
        }

        CurrentTime = time(NULL);

        newtime = localtime(&atoken.endTime);

        memset(UserName, '\0', sizeof(UserName));
        strcpy(UserName, aclient.name);

        memset(CellName, '\0', sizeof(CellName));
        strcpy(CellName, aclient.cell);

        memset(InstanceName, '\0', sizeof(InstanceName));
        strcpy(InstanceName, aclient.instance);

        memset(ServiceName, '\0', sizeof(ServiceName));
        strcpy(ServiceName, aserver.name);

        memset(TokenStatus, '\0', sizeof(TokenStatus));

        EndDay = newtime->tm_mday;

        EndMonth = newtime->tm_mon + 1;;

        sprintf(EndTime, "%02d:%02d:%02d", newtime->tm_hour, newtime->tm_min, newtime->tm_sec);

        sprintf(Buffer,"                          %s %02d %s      %s%s%s@%s  %s",
                Months[EndMonth - 1], EndDay, EndTime,
                UserName,
                InstanceName[0] ? "." : "",
                InstanceName,
                CellName,
                TokenStatus);

        list->theTicket = (char*) calloc(1, sizeof(Buffer));
        if (!list->theTicket)
        {
#ifdef USE_MESSAGE_BOX
            MessageBox(NULL, "Memory Error", "Error", MB_OK);
#endif /* USE_MESSAGE_BOX */
            return ENOMEM;
        }

        strcpy(list->theTicket, Buffer);
        list->name = strdup(aclient.name);
        list->inst = aclient.instance[0] ? strdup(aclient.instance) : NULL;
        list->realm = strdup(aclient.cell);
        list->encTypes = NULL;
        list->addrCount = 0;
        list->addrList = NULL;

        if ( ticketinfo ) {
            sprintf(Buffer,"%s@%s",UserName,CellName);
            if (!ticketinfo->principal[0] || !stricmp(Buffer,kerberosPrincipal)) {
                strcpy(ticketinfo->principal, Buffer);
                ticketinfo->issue_date = 0;
                ticketinfo->lifetime = atoken.endTime;
                ticketinfo->renew_till = 0;

                _tzset();
                if ( ticketinfo->lifetime - time(0) <= 0L )
                    ticketinfo->btickets = EXPD_TICKETS;
                else
                    ticketinfo->btickets = GOOD_TICKETS;
            }
        }
    }
    return(0);
#endif
}