Esempio n. 1
0
/*
 * Write a configuration to the config file.
 */
static void write_config(struct config_s *config)
{
#ifdef WINDOWS
    remove(CONFIG_BAK_FILENAME);    // For windows rename() bug.
#endif
    if (rename(CONFIG_FILENAME, CONFIG_BAK_FILENAME) != 0 && errno != ENOENT)
    {
        warning("unable to back-up old configuation file \"%s\" to \"%s\"",
            CONFIG_FILENAME, CONFIG_BAK_FILENAME);
    }
    errno = 0;

    FILE *file = fopen(CONFIG_TMP_FILENAME, "w");
    if (file == NULL)
    {
        warning("unable to open configuration file \"%s\" for writing",
            CONFIG_TMP_FILENAME);
        return;
    }
    fprintf(file, "# %s configuration file\n", PROGRAM_NAME_LONG);
    fputs("# AUTOMATICALLY GENERATED, DO NOT EDIT\n", file);
    fputc('\n', file);
    fprintf(file, "%s = \"%s\"\n", VAR_ENABLED,
        bool_to_string(config->enabled));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP,
        bool_to_string(config->hide_tcp));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_DATA,
        bool_to_string(config->hide_tcp_data));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_SYN,
        enum_to_string(config->hide_tcp_syn, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_ACK,
        enum_to_string(config->hide_tcp_ack, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_PSH,
        enum_to_string(config->hide_tcp_psh, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_FIN,
        enum_to_string(config->hide_tcp_fin, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_TCP_RST,
        enum_to_string(config->hide_tcp_rst, flag_def, DEF_SIZE(flag_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_HIDE_UDP,
        bool_to_string(config->hide_udp));
    fprintf(file, "%s = \"%s\"\n", VAR_SPLIT_MODE,
        enum_to_string(config->split, split_def, DEF_SIZE(split_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_LOG_LEVEL,
        enum_to_string((config_enum_t)log_get_level(), log_level_def,
        DEF_SIZE(log_level_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_GHOST_MODE,
        enum_to_string(config->ghost, ghost_def, DEF_SIZE(ghost_def)));
    fprintf(file, "%s = \"%s\"\n", VAR_GHOST_CHECK,
        bool_to_string(config->ghost_check));
    fprintf(file, "%s = \"%s\"\n", VAR_GHOST_SET_TTL,
        bool_to_string(config->ghost_set_ttl));
    fprintf(file, "%s = \"%u\"\n", VAR_GHOST_TTL, config->ghost_ttl);
    fprintf(file, "%s = \"%s\"\n", VAR_FRAG_MODE,
        enum_to_string(config->fragment, frag_def, DEF_SIZE(frag_def)));
    fprintf(file, "%s = \"%u\"\n", VAR_TCP_PORT, config->tcp_port);
    fprintf(file, "%s = \"%s\"\n", VAR_TCP_PROTO,
        protocol_get_name(config->tcp_proto));
    fprintf(file, "%s = \"%u\"\n", VAR_UDP_PORT, config->udp_port);
    fprintf(file, "%s = \"%s\"\n", VAR_UDP_PROTO,
        protocol_get_name(config->udp_proto));
    fprintf(file, "%s = \"%u\"\n", VAR_MTU, config->mtu);
    fprintf(file, "%s = \"%s\"\n", VAR_LAUNCH_UI,
        bool_to_string(config->launch_ui));
    fclose(file);

#ifdef WINDOWS
    remove(CONFIG_FILENAME);
#endif
    if (rename(CONFIG_TMP_FILENAME, CONFIG_FILENAME) != 0)
    {
        warning("unable to move temporary configuration file \"%s\" to \"%s\"",
            CONFIG_TMP_FILENAME, CONFIG_FILENAME);
    }
}
Esempio n. 2
0
int
main(int argc, char **argv)
{
	struct stat buf;
	int ret;
	char scratch[BUFSIZ];
	char log[BUFSIZ];
	char olog[BUFSIZ];
	char *scratch_p = scratch;
	char *mytag_p;
	FILE *fp;
	extern char *getenv();
	char *parse();
	int	c;
	extern	char *optarg;
	extern	int optind;
	int i;
	char	*Mytag_p = Mytag;

	/* Get my port monitor tag out of the environment		*/
	if ((mytag_p = getenv("PMTAG")) == NULL) {
		/* no place to write */
		exit(1);
	}
	strcpy(Mytag, mytag_p);

	/* open log file */
	sprintf(log, "%s/%s/%s", ALTDIR, Mytag_p, LOGNAME);
	sprintf(olog, "%s/%s/%s", ALTDIR, Mytag_p, OLOGNAME);
	if (stat(log, &buf) == 0) {
		/* file exists, try and save it but if we can't don't worry */
		unlink(olog);
		rename(log, olog);
	}
	if ((i = open(log, O_WRONLY|O_CREAT|O_APPEND, 0444)) < 0)
		logexit(1, nologfile);
	/* as stated above, the log file should be file descriptor 5 */
	if ((ret = fcntl(i, F_DUPFD, 5)) != 5)
		logexit(1, nologfile);
	Logfp = fdopen(ret, "a+");

	/* Get my port monitor tag out of the environment		*/
	if ((mytag_p = getenv("PMTAG")) == NULL) {
		logexit(1, nopmtag);
	}
	strcpy(Mytag, mytag_p);

	(void) umask(022);
	Readdb = FALSE;

	if (geteuid() != (uid_t) 0) {
		logmessage("Must be root to start listener");
		logexit(1, badstart);
	}

	while ((c = getopt(argc, argv, "m:")) != EOF) 
		switch (c) {
		case 'm':
			Minor_prefix = optarg;
			break;
		default:
			logexit(1, usage);
			break;
		}

	if ((Netspec = argv[optind]) == NULL) {
		logexit(1, usage);
	}
	if ((Netconf = getnetconfigent(Netspec)) == NULL) {
		sprintf(scratch, "no netconfig entry for <%s>", Netspec);
		logmessage(scratch);
		logexit(1, badstart);
	}
	if (!Minor_prefix)
		Minor_prefix = argv[optind];

	if ((int) strlen(Netspec) > PATHSIZE)  {
		logmessage(badnspmsg);
		logexit(1, badstart);
	}

	/* 
	 * SAC will start the listener in the correct directory, so we
	 * don't need to chdir there, as we did in older versions
	 */

	strcpy(Provbuf, "/dev/");
	strcat(Provbuf, Netspec);

	(void) umask(0);

	init_files();		/* open Accept, Sac, Pm, Pass files	*/
	pid_open();		/* create pid file			*/

#ifdef	DEBUGMODE
	sprintf(scratch, "%s/%s/%s", ALTDIR, Mytag, DBGNAME);
	Debugfp = fopen(scratch, "w");
#endif


#ifdef	DEBUGMODE
	if ((!Logfp) || (!Debugfp)) 
#else
	if (!Logfp)
#endif
		logexit(1, badstart);

/*
 * In case we started with no environment, find out what timezone we're
 * in.  This will get passed to children, so only need to do once.
 */

	if (getenv("TZ") == NULL) {
		fp = fopen(TIMEZONE, "r");
		if (fp) {
			while (fgets(tzenv, BUFSIZ, fp)) {
				if (tzenv[strlen(tzenv) - 1] == '\n')
					tzenv[strlen(tzenv) - 1] = '\0';
				if (!strncmp(TZSTR, tzenv, strlen(TZSTR))) {
					putenv(parse(tzenv));
					break;
				}
			}
			fclose(fp);
		}
		else {
			sprintf(scratch, "couldn't open %s, default to GMT", TIMEZONE);
			logmessage(scratch);
		}
	}

	logmessage("@(#)listen:listen.c	1.19.9.1");

#ifdef	DEBUGMODE
	logmessage("Listener process with DEBUG capability");
#endif

	sprintf(scratch, "Listener port monitor tag: %s", Mytag_p);
	logmessage(scratch);
	DEBUG((9, "Minor prefix: %s  Netspec %s", Minor_prefix, Netspec));

	/* fill in Pmmesg fields that always stay the same */

	Pmmsg.pm_maxclass = MAXCLASS;
	strcpy(Pmmsg.pm_tag, Mytag_p);
	Pmmsg.pm_size = 0;

	/* Find out what state to start in.  If not in env, exit */
	if ((scratch_p = getenv("ISTATE")) == NULL)
		logexit(1, "ERROR: ISTATE variable not set in environment");
	
	if (!strcmp(scratch_p, "enabled")) {
		State = PM_ENABLED;
		logmessage("Starting state: ENABLED");
	}
	else {
		State = PM_DISABLED;
		logmessage("Starting state: DISABLED");
	}

	/* try to get my "basename"		*/
	Progname = strrchr(argv[0], '/');
	if (Progname && Progname[1])
		++Progname;
	else
		Progname = argv[0];

	catch_signals();

	/* 
	 * Allocate memory for private address and file descriptor table 
	 * Here we are assuming that no matter how many private addresses
	 * exist in the system if the system limit is 20 then we will only
	 * get 20 file descriptors
	 */

	Ndesc = ulimit(4,0L);		/* get num of file des on system */

	read_dbf(DB_INIT);
	net_open();			/* init, open, bind names 	*/

	for (i = 3; i < Ndesc; i++)  {	/* leave stdout, stderr open	*/
		fcntl(i, F_SETFD, 1);	/* set close on exec flag*/
	}

	logmessage("Initialization Complete");

	listen();
	return (0);
}
Esempio n. 3
0
//!
//! Function description.
//!
//! @param[in] file
//! @param[in] file_updated
//!
//! @return
//!
//! @see
//!
//! @pre List of pre-conditions
//!
//! @post List of post conditions
//!
//! @note
//!
int atomic_file_get(atomic_file * file, boolean * file_updated)
{
    int port = 0;
    int fd = 0;
    int ret = 0;
    int rc = 0;
    char *hash = NULL;
    char type[32] = "";
    char hostname[512] = "";
    char path[EUCA_MAX_PATH] = "";
    char tmpsource[EUCA_MAX_PATH] = "";
    char tmppath[EUCA_MAX_PATH] = "";

    if (!file || !file_updated) {
        return (1);
    }

    ret = 0;
    *file_updated = FALSE;

    snprintf(file->tmpfile, EUCA_MAX_PATH, "%s", file->tmpfilebase);
    fd = safe_mkstemp(file->tmpfile);
    if (fd < 0) {
        LOGERROR("cannot open tmpfile '%s': check permissions\n", file->tmpfile);
        return (1);
    }
    if (chmod(file->tmpfile, 0600)) {
        LOGWARN("chmod failed: was able to create tmpfile '%s', but could not change file permissions\n", file->tmpfile);
    }
    close(fd);

    snprintf(tmpsource, EUCA_MAX_PATH, "%s", file->source);
    type[0] = tmppath[0] = path[0] = hostname[0] = '\0';
    port = 0;

    tokenize_uri(tmpsource, type, hostname, &port, tmppath);
    snprintf(path, EUCA_MAX_PATH, "/%s", tmppath);

    if (!strcmp(type, "http")) {
        rc = http_get_timeout(file->source, file->tmpfile, 0, 0, 10, 15, NULL);
        if (rc) {
            LOGERROR("http client failed to fetch file URL=%s: check http server status\n", file->source);
            ret = 1;
        }
    } else if (!strcmp(type, "file")) {
        if (!strlen(path) || copy_file(path, file->tmpfile)) {
            LOGERROR("could not copy source file (%s) to dest file (%s): check permissions\n", path, file->tmpfile);
            ret = 1;
        }
    } else {
        LOGWARN("BUG: incompatible URI type (%s) passed to routine (only supports http, file)\n", type);
        ret = 1;
    }

    if (!ret) {
        if (file->dosort) {
            rc = atomic_file_sort_tmpfile(file);
            if (rc) {
                LOGWARN("could not sort tmpfile (%s) inplace: continuing without sort\n", file->tmpfile);
            }
        }
        // do checksum - only copy if file has changed
        hash = file2md5str(file->tmpfile);
        if (!hash) {
            LOGERROR("could not compute hash of tmpfile (%s): check permissions\n", file->tmpfile);
            ret = 1;
        } else {
            if (file->currhash)
                EUCA_FREE(file->currhash);
            file->currhash = hash;
            if (check_file(file->dest) || strcmp(file->currhash, file->lasthash)) {
                // hashes are different, put new file in place
                LOGDEBUG("update triggered due to file update (%s)\n", file->dest);
                LOGDEBUG("source and destination file contents have become different, triggering update of dest (%s)\n", file->dest);
                LOGDEBUG("renaming file %s -> %s\n", file->tmpfile, file->dest);
                if (rename(file->tmpfile, file->dest)) {
                    LOGERROR("could not rename (move) source file '%s' to dest file '%s': check permissions\n", file->tmpfile, file->dest);
                    ret = 1;
                } else {
                    EUCA_FREE(file->lasthash);
                    file->lasthash = strdup(file->currhash);
                    *file_updated = TRUE;
                }
            }
        }
    }

    unlink(file->tmpfile);
    return (ret);
}
Esempio n. 4
0
void modeltest::editNexus(wxCommandEvent& event)
{
	wxString wxline, nexusFile, nexP, finalB, nexTemp, temp, BICblock, AICblock, HLRTblock;
	char line[2000];
	string p1, p2, p3, sline; int pBpos, sel;
	bool pBlock = false, toIns = true;
	wxArrayString block;
	const wxString choices[] = { _T("hLRTs"), _T("AIC"), _T("BIC")};


	wxFileDialog* dialog = new wxFileDialog (this, "Select NEXUS file to insert PAUP block", "", "", FILETYPES3, wxOPEN, wxDefaultPosition);

    if (dialog->ShowModal() == wxID_OK)
    {
		nexusFile = dialog->GetPath();
		this->outputText->SaveFile("temp.txt");
		ifstream modelOut ("temp.txt");
	
		wxSingleChoiceDialog dialog(this, _T("Select LSET command to parse into NEXUS files"),_T("Please select one"), 3, choices);
		if(dialog.ShowModal() == wxID_OK)
		{
			sel = dialog.GetSelection();
			//if(sel == 1)
			//{
			//	toIns = false;
			//}

			/* getting PAUP blocks from modeltest result file*/
			while(!modelOut.eof())
			{
				modelOut.getline(line, 2000);
				wxline = line;
				if(wxline.Contains("PAUP* Commands Block"))
				{
						modelOut.getline(line, 2000);
						wxline = line;
						do
						{
							if(wxline.Length() >= 1)
							{
								block.Add(wxline+"\n");
							}
							temp += wxline + "\n";
							modelOut.getline(line, 2000);
							wxline = line;
						}while(!wxline.Contains("END"));
						block.Add("END;\n");
						temp += "END;\n";
				}
			}
			HLRTblock = block[0]+block[1]+block[2]+block[3]+block[4]+block[5];
			AICblock = block[6]+block[7]+block[8]+block[9]+block[10]+block[11];
			if(BIC == true)
			{
				BICblock = block[6]+block[7]+block[8]+block[9]+block[10]+block[11];
			}
			modelOut.close();
			/*inserting block on nexus file*/
			string nexustr;
			nexustr = nexusFile;
			ifstream nex(nexustr.c_str());
			nexTemp = nexusFile + "temp";
			ofstream nexT(nexTemp);
			while(!nex.eof())
			{
				nex.getline(line, 2000);
				wxline = line;
				nexT << line << "\n";
			}
			if(sel == 0)
			{
				p1 = HLRTblock;
				nexT << p1 << "\n";
			}
			else if(sel == 1)
			{
				p2 = AICblock;
				nexT << p2 << "\n";
			}
			else if(sel == 2 && BIC == true)
			{
				p3 = BICblock;
				nexT << p3 << "\n";
			}
			else if(sel == 2 && BIC == false)
			{
				wxMessageBox("BIC analysis not available.\nPlease rerun ModelTest with this option enabled");
			}
			nexT << line << "\n";
			nex.close();
			nexT.close();
			remove(nexusFile);
			rename(nexTemp, nexusFile);
		}
	}
}
Esempio n. 5
0
int main ( int argc, char** argv ) {


	int ret;
	int i;

	uint32_t mode= MODE_DEFAULT;
	const char* command= NULL;
	const char* p;

	const char* infilename;
	char outfilename[OTF_PATH_MAX];
	char* outdir= NULL;

	int keep= 0;
	int zlevel= ZLEVEL;


	if ( 1 >= argc ) {

			SHOW_HELPTEXT;
			return 0;
	}
	

	/* collect parameters */
	for ( i= 1; i < argc; i++ ) {

		if ( 0 == strcmp( "-h", argv[i] ) || 0 == strcmp( "--help", argv[i] ) ) {

			SHOW_HELPTEXT;
			exit( 0 );

		} else 

		if ( 0 == strcmp( "-k", argv[i] ) ) {

			keep= 1;

		} else 

		if ( 0 == strcmp( "-o", argv[i] ) && i < argc -1 ) {

			outdir= argv[++i];
			keep= 1;

		} else 

		if ( 0 == strcmp( "-c", argv[i] ) ) {

			if ( MODE_DEFAULT == mode ) {

				mode= MODE_COMPRESS;

			} else {

				fprintf( stderr, "mode already set, cannot re-set, ignoring '-c'\n" );
			}

		} else 

		if ( 0 == strcmp( "-d", argv[i] ) ) {

			if ( MODE_DEFAULT == mode ) {

				mode= MODE_DECOMPRESS;

			} else {

				fprintf( stderr, "mode already set, cannot re-set, ignoring '-d'\n" );
			}

		} else 

		if ( ( '-' == argv[i][0] ) && ( '0' <= argv[i][1] ) && ( '9' >= argv[i][1] ) )  {

			zlevel= (int) ( argv[i][1] - '0' );

		} else 
		
		if ( 0 == strcmp( "-V", argv[i] ) ) {
		
			printf( "%u.%u.%u \"%s\"\n", OTF_VERSION_MAJOR, OTF_VERSION_MINOR,
				OTF_VERSION_SUB, OTF_VERSION_STRING);
			exit( 0 );
		}
	}

	/* look at argv[0], mode defaults to compress/decomress according to command name */
	if ( MODE_DEFAULT == mode ) {
	
		p= strrchr( argv[0], '/' );
		command = NULL != p ? p+1 : argv[0];

		if ( 0 == strcmp( "otfdecompress", command ) || 0 == strcmp( "otfdecompress.exe", command ) ) {

			mode= MODE_DECOMPRESS;

		}

	}


	/* files to (de)compress */
	for ( i= 1; i < argc; i++ ) {

		if ( '-' == argv[i][0] ) {

			/* switches already handled */

			if ( outdir != NULL && 0 == strcmp( argv[i], "-o" ) ) {

				/* skip value of option '-o' */
				i++;

			}

		} else {
		
			/* assume argument is a file name */

			infilename= argv[i];

			/* compose output file name */

			if ( NULL == outdir ) {

				snprintf( outfilename, sizeof( outfilename ) -1, "%s",
					  infilename );

			} else {

				p= strrchr( infilename, '/' );
				if ( NULL != p ) p++;
				else p= infilename;
				
				snprintf( outfilename, sizeof( outfilename ) -1, "%s/%s",
					  outdir, p );

			}

			switch ( mode ) {

			case MODE_DECOMPRESS:

				/* decompress file */

				/* check for ".z" at the end and refuse uncompression if not found */
				if ( ( 2 >= strlen( infilename ) ) ||
				     ( 0 != strcmp( infilename +strlen( infilename ) -2, ".z" ) ) ) {
				
					fprintf( stderr, "ERROR: no trailing '.z' in filename '%s', rejecting\n", 
						 infilename );

					continue;
				}

				/* cut trailing '.z' from output file name */
				outfilename[strlen( outfilename )-2] = '\0';

				fprintf( stdout, "decompress \"%s\" -> \"%s\"\n", 
					infilename, outfilename );

				ret= decompressFile( infilename, outfilename, BUFFERSIZE );

				if ( 0 == ret ) {

					if ( keep ) {

						/* keep compressed file */

					} else {

						/* remove compressed file */
						ret= unlink( infilename );

						if ( 0 != ret ) {

							fprintf( stderr, "error removing '%s'\n", infilename );
						}
					}

				} else {

					fprintf( stderr, "decompress error for file '%s'\n", infilename );
				} 

				break;

			case MODE_COMPRESS:
			case MODE_DEFAULT:
			default:

				/* compress file */

				/* check for ".z" at the end and refuse compression if found */
				if ( ( 2 < strlen( infilename ) ) &&
				     ( 0 == strcmp( infilename +strlen( infilename ) -2, ".z" ) ) ) {
				
					fprintf( stderr, "ERROR: found '.z' suffix in filename, "
						"file '%s' seems already compressed, skip\n", 
						infilename );

					continue;
				}

				/* add trailing '.z' to output file name */
				if ( strlen( outfilename ) +2 < sizeof( outfilename ) )
					strcat( outfilename, ".z" );

				fprintf( stdout, "compress \"%s\" -> \"%s\"\n", 
					infilename, outfilename );

				ret= compressFile( infilename, outfilename, zlevel, BUFFERSIZE );

				if ( 0 == ret ) {

					if ( keep ) {

						if ( outdir ) {

							/* keep uncompressed file */

						} else {

							/* rename original file */

							snprintf( outfilename, sizeof( outfilename ) -1, "%s.original",
								  infilename );

							ret= rename( infilename, outfilename );
						
							if ( 0 != ret ) {

								fprintf( stderr, "error renaming '%s' to '%s'\n", 
									 infilename, outfilename );

							}

						}

					} else {

						/* remove uncompressed */

						ret= unlink( infilename );

						if ( 0 != ret ) {

							fprintf( stderr, "error removing '%s'\n", infilename );
						}
					}

				} else {

					fprintf( stderr, "compress error for file '%s'\n", infilename );
				}

				break;
			}
		}
	}

	return 0;
}
Esempio n. 6
0
static int trunk_binlog_merge_file(int old_fd)
{
	int result;
	int tmp_fd;
	int bytes;
	char binlog_filename[MAX_PATH_SIZE];
	char tmp_filename[MAX_PATH_SIZE];
	char buff[64 * 1024];

	get_trunk_binlog_filename(binlog_filename);
	sprintf(tmp_filename, "%s.tmp", binlog_filename);
	tmp_fd = open(tmp_filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
	if (tmp_fd < 0)
	{
		result = errno != 0 ? errno : EACCES;
		logError("file: "__FILE__", line: %d, " \
			"open file \"%s\" fail, " \
			"errno: %d, error info: %s", \
			__LINE__, tmp_filename, result, STRERROR(result));
		return result;
	}

	while ((bytes=fc_safe_read(old_fd, buff, sizeof(buff))) > 0)
	{
		if (fc_safe_write(tmp_fd, buff, bytes) != bytes)
		{
			result = errno != 0 ? errno : EACCES;
			logError("file: "__FILE__", line: %d, " \
				"write to file \"%s\" fail, " \
				"errno: %d, error info: %s", \
				__LINE__, tmp_filename,
				result, STRERROR(result));
			close(tmp_fd);
			return result;
		}
	}

	if (access(binlog_filename, F_OK) == 0)
	{
		int binlog_fd;
		if ((binlog_fd=trunk_binlog_open_read(binlog_filename,
			false)) < 0)
		{
			close(tmp_fd);
			return errno != 0 ? errno : EPERM;
		}

		while ((bytes=fc_safe_read(binlog_fd, buff, sizeof(buff))) > 0)
		{
			if (fc_safe_write(tmp_fd, buff, bytes) != bytes)
			{
				result = errno != 0 ? errno : EACCES;
				logError("file: "__FILE__", line: %d, " \
					"write to file \"%s\" fail, " \
					"errno: %d, error info: %s", \
					__LINE__, tmp_filename,
					result, STRERROR(result));
				close(tmp_fd);
				close(binlog_fd);
				return result;
			}
		}
		close(binlog_fd);
	}

	if (fsync(tmp_fd) != 0)
	{
		result = errno != 0 ? errno : EIO;
		logError("file: "__FILE__", line: %d, " \
			"sync file \"%s\" fail, " \
			"errno: %d, error info: %s",  \
			__LINE__, tmp_filename, \
			errno, STRERROR(errno));
		close(tmp_fd);
		return result;
	}
	close(tmp_fd);

	if (rename(tmp_filename, binlog_filename) != 0)
	{
		result = errno != 0 ? errno : EPERM;
		logError("file: "__FILE__", line: %d, " \
			"rename %s to %s fail, " \
			"errno: %d, error info: %s",
			__LINE__, tmp_filename, binlog_filename,
			result, STRERROR(result));
		return result;
	}

	return 0;
}
Esempio n. 7
0
int trunk_reader_init(FDFSStorageBrief *pStorage, TrunkBinLogReader *pReader)
{
	char full_filename[MAX_PATH_SIZE];
	IniContext iniContext;
	int result;
	int64_t saved_binlog_offset;
	bool bFileExist;

	saved_binlog_offset = pReader->binlog_offset;

	memset(pReader, 0, sizeof(TrunkBinLogReader));
	pReader->mark_fd = -1;
	pReader->binlog_fd = -1;

	pReader->binlog_buff.buffer = (char *)malloc( \
				TRUNK_BINLOG_BUFFER_SIZE);
	if (pReader->binlog_buff.buffer == NULL)
	{
		logError("file: "__FILE__", line: %d, " \
			"malloc %d bytes fail, " \
			"errno: %d, error info: %s", \
			__LINE__, TRUNK_BINLOG_BUFFER_SIZE, \
			errno, STRERROR(errno));
		return errno != 0 ? errno : ENOMEM;
	}
	pReader->binlog_buff.current = pReader->binlog_buff.buffer;

	if (pStorage == NULL)
	{
		strcpy(pReader->storage_id, "0.0.0.0");
	}
	else
	{
		strcpy(pReader->storage_id, pStorage->id);
	}
	trunk_mark_filename_by_reader(pReader, full_filename);

	if (pStorage == NULL)
	{
		bFileExist = false;
		pReader->binlog_offset = saved_binlog_offset;
	}
	else
	{
		bFileExist = fileExists(full_filename);
		if (!bFileExist && (g_use_storage_id && pStorage != NULL))
		{
			char old_mark_filename[MAX_PATH_SIZE];
			trunk_get_mark_filename_by_ip_and_port( \
				pStorage->ip_addr, g_server_port, \
				old_mark_filename, sizeof(old_mark_filename));
			if (fileExists(old_mark_filename))
			{
				if (rename(old_mark_filename, full_filename)!=0)
				{
					logError("file: "__FILE__", line: %d, "\
						"rename file %s to %s fail" \
						", errno: %d, error info: %s", \
						__LINE__, old_mark_filename, \
						full_filename, errno, \
						STRERROR(errno));
					return errno != 0 ? errno : EACCES;
				}
				bFileExist = true;
			}
		}
	}

	if (bFileExist)
	{
		memset(&iniContext, 0, sizeof(IniContext));
		if ((result=iniLoadFromFile(full_filename, &iniContext)) \
			 != 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"load from mark file \"%s\" fail, " \
				"error code: %d", \
				__LINE__, full_filename, result);
			return result;
		}

		if (iniContext.global.count < 1)
		{
			iniFreeContext(&iniContext);
			logError("file: "__FILE__", line: %d, " \
				"in mark file \"%s\", item count: %d < 7", \
				__LINE__, full_filename, iniContext.global.count);
			return ENOENT;
		}

		pReader->binlog_offset = iniGetInt64Value(NULL, \
					MARK_ITEM_BINLOG_FILE_OFFSET, \
					&iniContext, -1);
		if (pReader->binlog_offset < 0)
		{
			iniFreeContext(&iniContext);
			logError("file: "__FILE__", line: %d, " \
				"in mark file \"%s\", binlog_offset: "\
				"%"PRId64" < 0", \
				__LINE__, full_filename, \
				pReader->binlog_offset);
			return EINVAL;
		}

		iniFreeContext(&iniContext);
	}

	pReader->last_binlog_offset = pReader->binlog_offset;

	pReader->mark_fd = open(full_filename, O_WRONLY | O_CREAT, 0644);
	if (pReader->mark_fd < 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"open mark file \"%s\" fail, " \
			"error no: %d, error info: %s", \
			__LINE__, full_filename, \
			errno, STRERROR(errno));
		return errno != 0 ? errno : ENOENT;
	}

	if (!bFileExist && pStorage != NULL)
	{
		if ((result=trunk_write_to_mark_file(pReader)) != 0)
		{
			return result;
		}
	}

	if ((result=trunk_open_readable_binlog(pReader, \
			get_binlog_readable_filename, pReader)) != 0)
	{
		return result;
	}

	result = trunk_binlog_preread(pReader);
	if (result != 0 && result != ENOENT)
	{
		return result;
	}

	return 0;
}
Esempio n. 8
0
static int os_rename (lua_State *L) {
  const char *fromname = luaL_checkstring(L, 1);
  const char *toname = luaL_checkstring(L, 2);
  return luaL_fileresult(L, rename(fromname, toname) == 0, fromname);
}
Esempio n. 9
0
int wrename(const OsPath& pathnameOld, const OsPath& pathnameNew)
{
	return rename(OsString(pathnameOld).c_str(), OsString(pathnameNew).c_str());
}
Esempio n. 10
0
int
main (int argc, char **argv)
{
  const char *name, *error;
  char *renamed;
  aiger *aiger;
  int i, res;

  name = 0;
  for (i = 1; i < argc; i++)
    {
      if (!strcmp (argv[i], "-h"))
	{
	  fprintf (stderr, "usage: aigstrip [-h][<file>]\n");
	  return 0;
	}
      else if (argv[i][0] == '-')
	{
	  fprintf (stderr, "*** [aigstrip] invalid option '%s'\n", argv[i]);
	  return 1;
	}
      else if (name)
	{
	  fprintf (stderr, "*** [aigstrip] multiple files\n");
	  return 1;
	}
      else
	name = argv[i];
    }

  res = 0;

  aiger = aiger_init ();
  if (!name) 
    {
      if((error = aiger_read_from_file (aiger, stdin))) goto PARSE_ERROR;
      (void) aiger_strip_symbols_and_comments (aiger);
      if (!aiger_write_to_file (aiger,
             (isatty (1) ? aiger_ascii_mode : aiger_binary_mode), stdout))
	{
	  fprintf (stderr, "*** [aigstrip] write error\n");
	  res = 1;
	}
    }
  else if ((error = aiger_open_and_read_from_file (aiger, name)))
    {
PARSE_ERROR:
      fprintf (stderr, "*** [aigstrip] read error: %s\n", error);
      res = 1;
    }
  else 
    {
      (void) aiger_strip_symbols_and_comments (aiger);
      renamed = malloc (strlen (name) + 2);
      sprintf (renamed, "%s~", name);

      if (rename (name, renamed))
	{
	  fprintf (stderr, "*** [aigstrip] failed to rename '%s'\n", name);
	  res = 1;
	}
      else if (aiger_open_and_write_to_file (aiger, name))
	{
	  if (unlink (renamed))
	    {
	      fprintf (stderr,
		       "*** [aigstrip] failed to remove '%s'\n", renamed);

	      res = 0;		/* !!! */
	    }
	}
      else
	{

	  fprintf (stderr, "*** [aigstrip] failed to write '%s'\n", name);
	  res = 1;

	  if (rename (renamed, name))
	    fprintf (stderr, "*** [aigstrip] backup in '%s'\n", renamed);
	  else
	    fprintf (stderr, "*** [aigstrip] original file restored\n");
	}

      free (renamed);
    }

  aiger_reset (aiger);

  return res;
}
Esempio n. 11
0
void redirect (const char *line, const char *makefile)
{
    struct stat st;
    FILE *fdin, *fdout;
    char backup[BUFSIZ], buf[BUFSIZ];
    bool found = false;
    int len;

    /* if makefile is "-" then let it pour onto stdout. */
    if (makefile && *makefile == '-' && *(makefile + 1) == '\0')
    {
        puts (line);
        return;
    }

    /* use a default makefile is not specified. */
    if (!makefile)
    {
        if (stat ("Makefile", &st) == 0)
            makefile = "Makefile";
        else if (stat ("makefile", &st) == 0)
            makefile = "makefile";
        else
            fatalerr ("[mM]akefile is not present\n");
    }
    else
        if (stat (makefile, &st))
            st.st_mode = 0640;

    if ((fdin = fopen (makefile, "r")) == NULL)
    {
        /* Try to create file if it does not exist */
        if (opt_create)
        {
            fdin = fopen (makefile, "w");
            if (fdin)
            {
                fclose (fdin);
                fdin = fopen (makefile, "r");
            }
        }
        if (!fdin)
            fatalerr ("cannot open \"%s\"\n", makefile);
    }

#if defined (__DJGPP__)
    // DOS cannot handle long filenames
    {
        char *src = makefile;
        char *dst = backup;
        while (*src && (*src != '.'))
            *dst++ = *src++;
        strcpy (dst, ".bak");
    }
#else
    sprintf (backup, "%s.bak", makefile);
#endif
    unlink (backup);
#if defined(WIN32) || defined(__EMX__) || defined (__DJGPP__)
    fclose (fdin);
#endif
    if (rename (makefile, backup) < 0)
        fatalerr ("cannot rename %s to %s\n", makefile, backup);
#if defined(WIN32) || defined(__EMX__) || defined (__DJGPP__)
    if ((fdin = fopen (backup, "r")) == NULL)
        fatalerr ("cannot open \"%s\"\n", backup);
#endif
    if ((fdout = freopen (makefile, "w", stdout)) == NULL)
        fatalerr ("cannot open \"%s\"\n", backup);
    len = strlen (line);
    while (!found && fgets (buf, BUFSIZ, fdin))
    {
        if (*buf == '#' && strncmp (line, buf, len) == 0)
            found = true;
        fputs (buf, fdout);
    }
    if (!found)
    {
        if (opt_verbose)
            warning ("Adding new delimiting line \"%s\" and dependencies...\n",
                     line);
        puts (line);	/* same as fputs(fdout); but with newline */
    }
    else if (opt_append)
    {
        while (fgets (buf, BUFSIZ, fdin))
        {
            fputs (buf, fdout);
        }
    }
    fflush (fdout);
#if defined(USGISH) || defined(_SEQUENT_) || defined(USE_CHMOD)
    chmod (makefile, st.st_mode);
#else
    fchmod (fileno (fdout), st.st_mode);
#endif /* USGISH */

    fclose (fdin);
    if (!opt_backup)
        unlink (backup);
}
Esempio n. 12
0
int32_t
omrfile_move(struct OMRPortLibrary *portLibrary, const char *pathExist, const char *pathNew)
{
	return rename(pathExist, pathNew);
}
Esempio n. 13
0
int main()


{while(1)
{
    system("cls");
    gotoxy(28,6);
    printf("HOSTEL MANAGEMENT SYSTEM");
    gotoxy(25,10);
    printf("--->>Press '1' for New Entry\n");
   gotoxy(25,12);
    printf("--->>Press '2' for Searching Existing Record\n");
    gotoxy(25,14);
    printf("--->>Press '3' for Deleting Record\n");
    gotoxy(25,16);
    printf("--->>Press '4' for Modifying  Record\n");
    gotoxy(25,18);
    printf("--->>Press '5' to Exit\n");
    gotoxy(25,20);
    printf("Choice you Entered is:");
    scanf("%d",&choice);


    switch(choice)
    {
                   case 1:
                        //new entry
                             system("cls");



                             fp=fopen("hostel_data.txt","a+");
                                 char another='y';
                                  int j=0;
                                   while(fscanf(fp,"%d%s%s%s%d%d%d%d",&eh[i].roll,eh[i].name,eh[i].deptt,eh[i].permntadd,&eh[i].roomno,&eh[i].ac.messchrges,&eh[i].ac.fine,&eh[i].ac.total)!=EOF)
                                   {
                                       printf("%d",count);
                                   count++;
                                   }

                              while(another=='y'||another=='Y')
                                   {
                             for(j=0;j<1;j++)
                                   {
                                           gotoxy(25,10);
                                           printf("Enter Name(use underscore for spaces)\t");
                                           scanf("%s",nh[j].name);
                                           gotoxy(25,12);
                                           printf("Enter Department\t");
                                           scanf("%s",nh[j].deptt);
                                           gotoxy(25,14);
                                           printf("Enter Permanent Address\t");
                                           scanf("%s",nh[j].permntadd);
                                           gotoxy(25,16);
                                           printf("Security amount rs.2500\n");
                                              gotoxy(25,18);
                                           printf("Security Deposited(Press 1/0 ::Y/N)\t");

                                           scanf("%d",&sd);
                                   switch(sd)

                                 {

                                  case 1:

                                    rewind(fp);

                                   nh[j].roll=count+1;
                                   nh[j].roomno=count+279;

                                   gotoxy(25,20);
                                   printf("Allotment Details:");
                                   gotoxy(25,22);
                                   printf("Roll Number %d\n",nh[j].roll);
                                   gotoxy(25,24);
                                   printf("Room Number %d\n",nh[j].roomno);
                                   nh[j].ac.messchrges=0;
                                   nh[j].ac.fine=0;
                                   nh[j].ac.total=nh[j].ac.messchrges+nh[j].ac.fine;
                                   fprintf(fp,"%d\t%s\t%s\t%s\t%d\t%d\t%d\t%d\n",nh[j].roll,nh[j].name,nh[j].deptt,nh[j].permntadd,nh[j].roomno,nh[j].ac.messchrges,nh[j].ac.fine,nh[j].ac.total);

                                    gotoxy(25,26);
                                    printf("Entry Successfully Done!!!!\n");
                                    gotoxy(25,28);
                                    printf("%d",j);
                                   break;

                                   case 0:

                                        gotoxy(25,20);
                                        printf("Security Pending");
                                         gotoxy(25,22);
                                         printf("Sorry!Roll Number and Room Number will be allotted on Receiving Security");
                                        gotoxy(25,24);
                                   break;

                                   }
                                   }

                                   gotoxy(25,30);

                                    printf("want to Add Another Record!\t");
                                   fflush(stdin);
                                   scanf("%c",&another);

                                   system("cls");
                                   }
                                fclose(fp);
                                        printf("Press any key to Return to Main Menu");
                                   getch();
                                   break ;




                  case 2:
                       //searching entry
                        system("cls");


                                    fp=fopen("hostel_data.txt","r");
                                    if(fp==NULL)
                                    exit(0);


                                   while(another=='y'||another=='Y')
                                   {gotoxy(25,10);
                                                                     printf("Enter Roll Number:\t");
                                    scanf("%d",&rol);
                                      rewind(fp);
                                    while(fscanf(fp,"%d%s%s%s%d%d%d%d",&eh[i].roll,eh[i].name,eh[i].deptt,eh[i].permntadd,&eh[i].roomno,&eh[i].ac.messchrges,&eh[i].ac.fine,&eh[i].ac.total)!=EOF)
                                   { if(rol==eh[i].roll)
                                                                      { gotoxy(25,12);
                                                                       printf("%d\t%s\t%s\t%s\t%d\t%d\t%d\t%d\n",eh[i].roll,eh[i].name,eh[i].deptt,eh[i].permntadd,eh[i].roomno,eh[i].ac.messchrges,eh[i].ac.fine,eh[i].ac.total);
                                                                       }

                                                                        }
                                                                       gotoxy(25,14);
                                                                       fflush(stdin);
                                                                        printf("Want to Search Another Entry(press y/n):\t");
                                                                        scanf("%c",&another);
                                                                        system("cls");
                                                                        }

                                                                       gotoxy(25,16);

                                                                        printf("Press any key to Return to Main Menu");
                                                                               getch();
                                                                               break;
                  case 3:
                       //Delete entry
                                                system("cls");
                                                FILE *fn;
                                                  gotoxy(25,10);
                                                  printf("Enter roll no.:\t");
                                                  scanf("%d",&rol);

                                                  fp=fopen("hostel_data.txt","r");
                                                  fn=fopen("hostel_data2.txt","w");
                                                   while(another=='y'||another=='Y')
                                   {

                                                  while(fscanf(fp,"%d%s%s%s%d%d%d%d",&eh[i].roll,eh[i].name,eh[i].deptt,eh[i].permntadd,&eh[i].roomno,&eh[i].ac.messchrges,&eh[i].ac.fine,&eh[i].ac.total)!=EOF)
                                                  { if(eh[i].roll==rol)
                                                  flag=1;


                                                  if(eh[i].roll!=rol)
                                                  {fprintf(fn,"%d\t%s\t%s\t%s\t%d\t%d\t%d\t%d\n",eh[i].roll,eh[i].name,eh[i].deptt,eh[i].permntadd,eh[i].roomno,eh[i].ac.messchrges,eh[i].ac.fine,eh[i].ac.total);
                                                  }
                                                                        }
                                                                        fclose(  fp);
                                                                            fclose(  fn);
                                                                            remove(  "hostel_data.txt");
                                                                            rename( "hostel_data2.txt", "hostel_data.txt");
                                                                      gotoxy(25,12);
                                                                      if(flag==1)
                                                                       printf("Entry Successfully Deleted");
                                                                       if(flag==0)
                                                                       printf("Not in Record!");
                                                                       gotoxy(25,14);
                                                                      printf("Want to Delete Another Record(press y/n):\t");
                                                                       fflush(stdin);
                                                                        scanf("%c",&another);
                                                                        getch();
                                                                        system("cls");
                                                                        }
                                                                        gotoxy(25,16);
                                                                       printf("Press any key to Return to Main Menu");
                                                                        getch();
                                                                       break;





                  case 4:
                       //modify entry
                       system("cls");
                       FILE *f;
                       gotoxy(25,10);
                       printf("Enter Roll number whose Record is to be modified\t");
                       scanf("%d",&rol);
                       fp=fopen("hostel_data.txt","r");
                       f=fopen("hostel_data3.txt","w");

                        while(another=='y'||another=='Y')
                                   {
                       while(fscanf(fp,"%d%s%s%s%d%d%d%d",&eh[i].roll,eh[i].name,eh[i].deptt,eh[i].permntadd,&eh[i].roomno,&eh[i].ac.messchrges,&eh[i].ac.fine,&eh[i].ac.total)!=EOF)
{
                       if(eh[i].roll==rol)
                       {
                                          gotoxy(25,12);
                                          printf("Enter Mess charges");
                                          scanf("%d",&eh[i].ac.messchrges);
                                                        gotoxy(25,14);
                                                         printf("Enter Fine");
                                          scanf("%d",&eh[i].ac.fine);
                                              eh[i].ac.total=eh[i].ac.messchrges+eh[i].ac.fine;
                                           }
                       fprintf(f,"%d\t%s\t%s\t%s\t%d\t%d\t%d\t%d\n",eh[i].roll,eh[i].name,eh[i].deptt,eh[i].permntadd,eh[i].roomno,eh[i].ac.messchrges,eh[i].ac.fine,eh[i].ac.total);


                                                                        }

                                                 fclose(fp);
                                                                            fclose(f);
                                                                            remove(  "hostel_data.txt");
                                                                            rename( "hostel_data3.txt", "hostel_data.txt");

                  gotoxy(25,16);
                  printf("Entry Successfully Modified");
                  gotoxy(25,18);
                      printf("Want to Modify Another Record(press y/n):\t");
                                                                        scanf("%c",&another);
                                                                        system("cls");
                                                                        }
                   gotoxy(25,20);
                  printf("Press any key to Return to Main Menu");
                   getch();
                   break;



                  case 5:
                       {exit(0);
                       }
                }  }
    getch();

}
Esempio n. 14
0
/*lint -e528*/
static int dload_printf_to_file(const char *path, int tv_sec, int tv_usec, const char *buf)
{
    FILE    *pFile = NULL;
    int     file_length = 0;
    char    filea_name[DLOAD_LOGREC_PATH_LENGTH] = {0};
    char    fileb_name[DLOAD_LOGREC_PATH_LENGTH] = {0};
    int     ret = 0;
    int     status = 0;

    ret = access(path, F_OK);
    if(ret)
    {
        /* 目录不存在,则创建目录 */
        status = mkdir(path, S_IRWXU);
        if(-1 == status)
        {
            printf("[DLOAD LOGREC] mkdir %s error.\n", path, strerror(errno));
            return DLOAD_ERR;
        }
    }

    /*获取file A长度*/
    /*lint -e119*/
    snprintf(filea_name, DLOAD_LOGREC_PATH_LENGTH, "%s%s", path, DLOAD_LOGREC_FILENAME_A);
    /*lint +e119*/
    pFile = fopen(filea_name, "a+");
    if (NULL == pFile)
    {
        printf("[DLOAD LOGREC] fopen %s, %s\n", filea_name, strerror(errno));
        return DLOAD_ERR;
    }

    ret = fseek(pFile, 0, SEEK_END);
    if(0 != ret)
    {
        fclose(pFile);

        printf("[DLOAD LOGREC] fseek %s, %s\n", filea_name, strerror(errno));
        return DLOAD_ERR;       
    }
    
    file_length = ftell(pFile);
    if(0 > file_length)
    {
        fclose(pFile);

        printf("[DLOAD LOGREC] Get length %s, %s\n", filea_name, strerror(errno));
        return DLOAD_ERR;
    }

    /*如果超长: A->B, new A*/
    if (DLOAD_LOGREC_MAX_FILESIZE <= file_length)
    {
        fclose(pFile);
        /*lint -e119*/
        snprintf(fileb_name, DLOAD_LOGREC_PATH_LENGTH, "%s%s", path, DLOAD_LOGREC_FILENAME_B);
        /*lint +e119*/
        ret = rename(filea_name, fileb_name);
        if (0 != ret)
        {
            printf("[DLOAD LOGREC] Rename %s to %s, %s\n", filea_name, fileb_name, strerror(errno));
            return DLOAD_ERR;
        }

        pFile = NULL;
        pFile = fopen(filea_name, "a+");
        if (NULL == pFile)
        {
            printf("[DLOAD LOGREC] Open %s, %s\n", filea_name, strerror(errno));
            return DLOAD_ERR;
        }
    }

    ret = fprintf(pFile, "[%d.%d]", tv_sec, tv_usec);
    if (0 > ret)
    {
        fclose(pFile);
        printf("[DLOAD LOGREC] fprintf %s, %s\n", filea_name, strerror(errno));
        return DLOAD_ERR;
    }

    ret = fprintf(pFile, "%s", buf);
    if (0 > ret)
    {
        fclose(pFile);

        printf("[DLOAD LOGREC] fvprintf %s, %s\n", filea_name, strerror(errno));
        return DLOAD_ERR;
    }

    fclose(pFile);
    return DLOAD_OK;
}
Esempio n. 15
0
File: mv.c Progetto: JamesLinus/vsta
main(int argc, char **argv)
{
	struct stat sb;
	int errs;

	if (argc < 3) {
		usage();
	}

	/*
	 * If moving a bunch of files to a directory, last element
	 * has to be a directory.
	 */
	if (stat(argv[argc-1], &sb) < 0) {
		/*
		 * a, b, c -> d		But d doesn't exist
		 */
		if (argc > 3) {
			fprintf(stderr, "Last argument should be dir: %s\n",
				argv[argc-1]);
			exit(1);
		}

		/*
		 * a -> b
		 */
		if (rename(argv[1], argv[2]) < 0) {
			perror(argv[2]);
			exit(1);
		}
		exit(0);
	}

	/*
	 * If dest is a directory, move each into it
	 */
	errs = 0;
	if ((sb.st_mode & S_IFMT) == S_IFDIR) {
		int x, len;
		char *base;

		argc -= 1;
		base = argv[argc];
		len = strlen(base)+1;
		for (x = 1; x < argc; ++x) {
			char *dest;

			dest = malloc(len + strlen(argv[x]) + 1);
			sprintf(dest, "%s/%s", base, argv[x]);
			if (rename(argv[x], dest) < 0) {
				perror(dest);
				errs += 1;
			}
		}
	} else {
		/*
		 * Existing dest--overwrite if a -> b, otherwise error
		 */
		if (argc != 3) {
			fprintf(stderr, "Last argument should be dir: %s\n",
				argv[argc-1]);
			exit(1);
		}
		unlink(argv[2]);
		if (rename(argv[1], argv[2]) < 0) {
			perror(argv[2]);
			errs = 1;
		}
	}
	return(errs ? 1 : 0);
}
Esempio n. 16
0
void test_rename(char *workdir) {
    char file1[1024], file2[1024], link[1024],
         subdir[1024], newdir[1024];
    struct stat sb1, sb2;
    int fd;

    printf("testing rename\n");

    sprintf(file1, "%s/file1", workdir);
    sprintf(file2, "%s/file2", workdir);

    /* test stat first.. since we need it to test rename */
    my_stat(file1, &sb1);

    /* Not much to look at, really..  how about making sure that
       the modification time of the file is not in the future.
       allow ten seconds of slack */
    if (sb1.st_mtime > time(NULL) + 10) {
        printf("Modification time of %s is in the future!\n",
               file1);
        exit(1);
    }

    my_rename(file1, file2);

    /* try repeat */
    if (!rename(file1, file2)) {
        printf("repeat rename(%s,%s) worked.. but it shouldn't have\n",
               file1, file2);
        exit(1);
    }


    /* inode number of file2 should be the same as it was for file1 */
    verify_inum(file2, &sb1);


    /* rename back */
    my_rename(file2, file1);

    verify_inum(file1, &sb1);

    /* Make a subdir, which will be renamed */
    sprintf(subdir, "%s/rename_this_dir", workdir);

    my_mkdir(subdir);
    my_stat(subdir, &sb2);

    /* Test moving a file into a subdir */
    sprintf(file2, "%s/file1", subdir);
    my_rename(file1, file2);
    verify_inum(file2, &sb1);

    /* Add in a hard link to spice things up */
    sprintf(link, "%s/link", subdir);
    my_link(file2, link);

    sprintf(newdir, "%s/newdirname", workdir);
    my_rename(subdir, newdir);
    verify_inum(newdir, &sb2);
    sprintf(file2, "%s/file1", newdir);
    verify_inum(file2, &sb1);
    sprintf(link, "%s/newdirname/link", workdir);
    verify_inum(link, &sb1);

    /* Test moving up in the tree */
    my_rename(file2,file1);
    verify_inum(file1, &sb1);

    my_unlink(link);

    my_rmdir(newdir);

}
Esempio n. 17
0
int trunk_binlog_compress_apply()
{
	int result;
	char binlog_filename[MAX_PATH_SIZE];
	char rollback_filename[MAX_PATH_SIZE];

	get_trunk_binlog_filename(binlog_filename);
	if (get_trunk_rollback_filename(rollback_filename) == NULL)
	{
		logError("file: "__FILE__", line: %d, " \
			"filename: %s is too long",
			__LINE__, binlog_filename);
		return ENAMETOOLONG;
	}

	if (trunk_binlog_fd < 0)
	{
		if (access(binlog_filename, F_OK) == 0)
		{
			if (rename(binlog_filename, rollback_filename) != 0)
			{
				result = errno != 0 ? errno : EIO;
				logError("file: "__FILE__", line: %d, " \
					"rename %s to %s fail, " \
					"errno: %d, error info: %s",
					__LINE__, binlog_filename,
					rollback_filename, result,
					STRERROR(result));
				return result;
			}
		}
		else if (errno != ENOENT)
		{
			result = errno != 0 ? errno : EIO;
			logError("file: "__FILE__", line: %d, " \
				"call access %s fail, " \
				"errno: %d, error info: %s",
				__LINE__, binlog_filename,
				result, STRERROR(result));
			return result;
		}

		return 0;
	}

	if ((result=trunk_binlog_close_writer(true)) != 0)
	{
		return result;
	}

	if (rename(binlog_filename, rollback_filename) != 0)
	{
		result = errno != 0 ? errno : EIO;
		logError("file: "__FILE__", line: %d, " \
			"rename %s to %s fail, " \
			"errno: %d, error info: %s",
			__LINE__, binlog_filename, rollback_filename,
			result, STRERROR(result));
		return result;
	}

	if ((result=trunk_binlog_open_writer(binlog_filename)) != 0)
	{
		rename(rollback_filename, binlog_filename);  //rollback
		return result;
	}

	return 0;
}
Esempio n. 18
0
/********************************************************************************
* TitleBrowser- opens a browser with a list of installed Titles
* relies on code from any title deleter.
*********************************************************************************/
int TitleBrowser(u32 type) {

	u32 num_titles;
	u32 titles[100] ATTRIBUTE_ALIGN(32);
	u32 num_sys_titles;
	u32 sys_titles[10] ATTRIBUTE_ALIGN(32);
	s32 ret = -1;
	int numtitle;//to get rid of a stupid compile wrning
	//open the database file
	FILE *f;
	char path[100];

	ISFS_Initialize();

	sprintf(path,"%s/config/database.txt",bootDevice);
	f = fopen(path, "r");

	// Get count of titles of our requested type
	ret = getTitles_TypeCount(type, &num_titles);
	if (ret < 0) {
		//printf("\tError! Can't get count of titles! (ret = %d)\n", ret);
		//exit(1);
	}

	// Get titles of our requested type
	ret = getTitles_Type(type, titles, num_titles);
	if (ret < 0) {
		//printf("\tError! Can't get list of titles! (ret = %d)\n", ret);
		//exit(1);
	}

	// Get count of system titles
	ret = getTitles_TypeCount(0x00010002, &num_sys_titles);
	if (ret < 0) {
		//printf("\tError! Can't get count of titles! (ret = %d)\n", ret);
		//exit(1);
	}

	// Get system titles
	ret = getTitles_Type(0x00010002, sys_titles, num_sys_titles);
	if (ret < 0) {
		//printf("\tError! Can't get list of titles! (ret = %d)\n", ret);
		//exit(1);
	}


	//this array will hold all the names for the titles so we only have to get them one time
	char name[num_titles+num_sys_titles][50];

	customOptionList options3(num_titles+num_sys_titles+1);
	//write the titles on the option browser
	u32 i = 0;



	//first add the good stuff
	while (i < num_titles) {
		//start from the beginning of the file each loop
		if (f)rewind(f);
		//char name[50];
		char text[15];
		strcpy(name[i],"");//make sure name is empty
		u8 found=0;
		//set the title's name, number, ID to text
		sprintf(text, "%s", titleText(type, titles[i]));

		//get name from database cause i dont like the ADT function
		char line[200];
		char tmp[50];
		snprintf(tmp,50," ");
		
		//check if the content.bin is on the SD card for that game
		//if there is content.bin,then the game is on the SDmenu and not the wii
		sprintf(line,"SD:/private/wii/title/%s/content.bin",text);
		if (!checkfile(line))
			{
				if (f) {
					while (fgets(line, sizeof(line), f)) {
						if (line[0]== text[0]&&
								line[1]== text[1]&&
								line[2]== text[2]) {
							int j=0;
							found=1;
							for (j=0;(line[j+4]!='\0' || j<51);j++)

								tmp[j]=line[j+4];
							snprintf(name[i],sizeof(name[i]),"%s",tmp);
							//break;
						}
					}
				}
				if (!found) {
					if (getName00(name[i], TITLE_ID(type, titles[i]),CONF_GetLanguage()*2)>=0)
						found=2;

					if (!found) {
						if (getNameBN(name[i], TITLE_ID(type, titles[i]))>=0)
							found=3;

						if (!found)
							snprintf(name[i],sizeof(name[i]),"Unknown Title (%08x)",titles[i]);
					}
				}

				//set the text to the option browser
				options3.SetName(i, "%s",text);
				options3.SetValue(i, "%s",name[i]);
				//options3.SetValue(i, " (%08x) %s",titles[i],name[i]);//use this line to show the number to call to launch the channel
				//move on to the next title
			}
        i++;
    }

    // now add the crappy system titles
    while (i < num_titles+num_sys_titles) {
        //start from the beginning of the file each loop
        if (f)rewind(f);
        //char name[50];
        char text[15];
        strcpy(name[i],"");//make sure name is empty
        u8 found=0;
        //set the title's name, number, ID to text
        sprintf(text, "%s", titleText(0x00010002, sys_titles[i-num_titles]));

        //get name from database cause i dont like the ADT function
        char line[200];
        char tmp[50];
        snprintf(tmp,50," ");
        //snprintf(name[i],sizeof(name[i]),"Unknown Title");
        if (f) {
            while (fgets(line, sizeof(line), f)) {
                if (line[0]== text[0]&&
                        line[1]== text[1]&&
                        line[2]== text[2]) {
                    int j=0;
                    found=1;
                    for (j=0;(line[j+4]!='\0' || j<51);j++)

                        tmp[j]=line[j+4];
                    snprintf(name[i],sizeof(name[i]),"%s",tmp);
                    break;
                }
            }
        }
        if (!found) {
            if (getName00(name[i], TITLE_ID(0x00010002, sys_titles[i-num_titles]))>=0)
                found=2;

            if (!found) {
                if (getNameBN(name[i], TITLE_ID(0x00010002, sys_titles[i-num_titles]))>=0)
                    found=3;

                if (!found)
                    snprintf(name[i],sizeof(name[i]),"Unknown Title (%08x)",sys_titles[i-num_titles]);
            }
        }

        //set the text to the option browser
        options3.SetName(i, "%s",text);
        options3.SetValue(i, "%s",name[i]);
        //options3.SetValue(i, " (%08x) %s",titles[i],name[i]);//use this line to show the number to call to launch the channel
        //move on to the next title
        i++;
    }
    if (i == num_titles+num_sys_titles) {
        options3.SetName(i, " ");
        options3.SetValue(i, "%s",tr("Wii Settings"));
    }
    //we have all the titles we need so close the database and stop poking around in the wii
    fclose(f);

    //get rid of our footprints in there
    Uninstall_FromTitle(TITLE_ID(1, 0));
    ISFS_Deinitialize();
    bool exit = false;

    if (IsNetworkInit())
        ResumeNetworkWait();

    GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume);
	// because destroy GuiSound must wait while sound playing is finished, we use a global sound
	if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);
	//	GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);

    char imgPath[100];

    snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path);
    GuiImageData btnOutline(imgPath, button_dialogue_box_png);
    snprintf(imgPath, sizeof(imgPath), "%sgamesettings_background.png", CFG.theme_path);
    GuiImageData settingsbg(imgPath, settings_background_png);

    GuiTrigger trigA;
    trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);
    GuiTrigger trigHome;
    trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0);
    GuiTrigger trigB;
    trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B);

    GuiText titleTxt(tr("Title Launcher"), 28, (GXColor) {0, 0, 0, 255});
    titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    titleTxt.SetPosition(12,40);
    titleTxt.SetMaxWidth(356, GuiText::SCROLL);

    GuiImage settingsbackground(&settingsbg);
    GuiButton settingsbackgroundbtn(settingsbackground.GetWidth(), settingsbackground.GetHeight());
    settingsbackgroundbtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
    settingsbackgroundbtn.SetPosition(0, 0);
    settingsbackgroundbtn.SetImage(&settingsbackground);

    GuiText cancelBtnTxt(tr("Back"), 22, THEME.prompttext);
    cancelBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage cancelBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        cancelBtnTxt.SetWidescreen(CFG.widescreen);
        cancelBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton cancelBtn(&cancelBtnImg,&cancelBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2,1);
    cancelBtn.SetScale(0.9);
    cancelBtn.SetLabel(&cancelBtnTxt);
    cancelBtn.SetTrigger(&trigB);

    u8 scrollbaron = 0;
    if (num_titles > 9)
        scrollbaron = 1;

    GuiCustomOptionBrowser optionBrowser3(396, 280, &options3, CFG.theme_path, "bg_options_gamesettings.png", bg_options_settings_png, num_titles+num_sys_titles>9?1:0, 200);
    optionBrowser3.SetPosition(0, 90);
    optionBrowser3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);

    snprintf(imgPath, sizeof(imgPath), "%sWifi_btn.png", CFG.theme_path);
    GuiImageData wifiImgData(imgPath, Wifi_btn_png);
    GuiImage wifiImg(&wifiImgData);
    if (Settings.wsprompt == yes) {
        wifiImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton wifiBtn(wifiImg.GetWidth(), wifiImg.GetHeight());
    wifiBtn.SetImage(&wifiImg);
    wifiBtn.SetPosition(100, 400);
    wifiBtn.SetEffectGrow();
    wifiBtn.SetAlpha(80);
    wifiBtn.SetTrigger(&trigA);

    GuiTrigger trigZ;
    trigZ.SetButtonOnlyTrigger(-1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z);

    GuiButton screenShotBtn(0,0);
    screenShotBtn.SetPosition(0,0);
    screenShotBtn.SetTrigger(&trigZ);

    HaltGui();
    GuiWindow w(screenwidth, screenheight);
    w.Append(&screenShotBtn);
    w.Append(&settingsbackgroundbtn);
    w.Append(&titleTxt);
    w.Append(&cancelBtn);
    w.Append(&wifiBtn);
    w.Append(&optionBrowser3);

    mainWindow->Append(&w);


    int tmp=num_titles+num_sys_titles;
    ResumeGui();
    numtitle=num_titles;
    while (!exit) {
        VIDEO_WaitVSync();

        if (shutdown == 1)
            Sys_Shutdown();
        if (reset == 1)
            Sys_Reboot();

        else if (wifiBtn.GetState() == STATE_CLICKED) {

                ResumeNetworkWait();
                wifiBtn.ResetState();
        }

        if (IsNetworkInit()) {
                wifiBtn.SetAlpha(255);
        }

        ret = optionBrowser3.GetClickedOption();

        if (ret > -1) {//if a click happened

            //char name[50];
            char text[15];
            if (f)rewind(f);
            //strcpy(name,"");//make sure name is empty

            if (ret<numtitle) {
                //set the title's name, number, ID to text
                sprintf(text, "%s", titleText(type, titles[ret]));

                char temp[100];
                //prompt to boot selected title
                snprintf(temp, sizeof(temp), "%s : %s",text,name[ret]);
                int  choice = WindowPrompt(tr("Boot?"), temp, tr("OK"), tr("Cancel"));
                if (choice) {//if they say yes


                    //stop all this stuff before starting the channel

                    CloseXMLDatabase();
                    ExitGUIThreads();
                    ShutdownAudio();
                    StopGX();
                    WII_Initialize();
                    WII_LaunchTitle(TITLE_ID(type,titles[ret]));
                    //this really shouldn't be needed because the title will be booted
                    exit = true;
                    break;
                } else {
                    //if they said no to booting the title
                    ret = -1;
                    optionBrowser3.ResetState();
                }

            } else { //if they clicked a system title
                if (ret == tmp) {
                    CloseXMLDatabase();
                    ExitGUIThreads();
                    ShutdownAudio();
                    StopGX();
                    WII_Initialize();
                    WII_ReturnToSettings();

                } else {
                    //set the title's name, number, ID to text
                    sprintf(text, "%s", titleText(0x00010002, sys_titles[ret-num_titles]));

                    char temp[112];
                    //prompt to boot selected title
					snprintf(temp, sizeof(temp), tr("%s : %s May not boot correctly if your System Menu is not up to date."),text,name[ret]);
                    int  choice = WindowPrompt(tr("Boot?"), temp, tr("OK"), tr("Cancel"));
                    if (choice) {//if they say yes


                        //stop all this stuff before starting the channel

                        CloseXMLDatabase();
                        ExitGUIThreads();
                        ShutdownAudio();
                        StopGX();
                        WII_Initialize();
                        WII_LaunchTitle(TITLE_ID(0x00010002,sys_titles[ret-num_titles]));
                        //this really shouldn't be needed because the title will be booted
                        exit = true;
                        break;
                    } else {
                        //if they said no to booting the title
                        ret = -1;
                        optionBrowser3.ResetState();
                    }
                }
            }
        }

        if(infilesize > 0) {

                char filesizetxt[50];
                char temp[50];
                char filepath[100];
//				u32 read = 0;
				
				//make sure there is a folder for this to be saved in
				struct stat st;
                snprintf(filepath, sizeof(filepath), "%s/wad/", bootDevice);
				if (stat(filepath, &st) != 0) {
						if (subfoldercreate(filepath) != 1) {
							WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK"));
						}
					}
				snprintf(filepath, sizeof(filepath), "%s/wad/tmp.tmp", bootDevice);
				

                if (infilesize < MB_SIZE)
                    snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fKB"), infilesize/KB_SIZE);
                else
                    snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fMB"), infilesize/MB_SIZE);

                snprintf(temp, sizeof(temp), tr("Load file from: %s ?"), GetIncommingIP());

                int choice = WindowPrompt(filesizetxt, temp, tr("OK"), tr("Cancel"));
		gprintf("\nchoice:%d",choice);

		if (choice == 1) {

			u32 read = 0;
			u8 *temp = NULL;
			int len = NETWORKBLOCKSIZE;
			temp = (u8 *) malloc(infilesize);

						bool error = false;
						u8 *ptr = temp;
						gprintf("\nrecieving shit");
			while (read < infilesize) {

			    ShowProgress(tr("Receiving file from:"), GetIncommingIP(), NULL, read, infilesize, true);

			    if (infilesize - read < (u32) len)
				len = infilesize-read;
			    else
				len = NETWORKBLOCKSIZE;

			    int result = network_read(ptr, len);

			    if (result < 0) {
				WindowPrompt(tr("Error while transfering data."), 0, tr("OK"));
				error = true;
				break;
			    }
			    if (!result) {
				gprintf("\n!RESULT");
				break;
							}
			    ptr += result;
			    read += result;
			}
			ProgressStop();

						char filename[101];
						char tmptxt[200];



						//bool installWad=0;
						if (!error) {
						    gprintf("\nno error yet");

							network_read((u8*) &filename, 100);
							gprintf("\nfilename: %s",filename);

							// Do we need to unzip this thing?
							if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) {
							    gprintf("\nusing newer wiiload version");

								if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed
								    gprintf("\ntrying to uncompress");
									// It's compressed, uncompress
									u8 *unc = (u8 *) malloc(uncfilesize);
									uLongf f = uncfilesize;
									error = uncompress(unc, &f, temp, infilesize) != Z_OK;
									uncfilesize = f;

									free(temp);
									temp = unc;
								}
							}

							if (!error) {
								sprintf(tmptxt,"%s",filename);
								//if we got a wad
								if (strcasestr(tmptxt,".wad")) {
								    FILE *file = fopen(filepath, "wb");
								    fwrite(temp, 1, (uncfilesize>0?uncfilesize:infilesize), file);
								    fclose(file);

								    sprintf(tmptxt,"%s/wad/%s",bootDevice,filename);
								    if (checkfile(tmptxt))remove(tmptxt);
								    rename(filepath, tmptxt);

								    //check and make sure the wad we just saved is the correct size
								    u32 lSize;
								    file = fopen(tmptxt, "rb");

								    // obtain file size:
								    fseek (file , 0 , SEEK_END);
								    lSize = ftell (file);

								    rewind (file);
								    if (lSize==(uncfilesize>0?uncfilesize:infilesize)) {
									gprintf("\nsize is ok");
									int pick = WindowPrompt(tr(" Wad Saved as:"), tmptxt, tr("Install"),tr("Uninstall"),tr("Cancel"));
									//install or uninstall it
									if (pick==1)
										{
											HaltGui();
											w.Remove(&titleTxt);
											w.Remove(&cancelBtn);
											w.Remove(&wifiBtn);
											w.Remove(&optionBrowser3);
											ResumeGui();

											Wad_Install(file);

											HaltGui();
											w.Append(&titleTxt);
											w.Append(&cancelBtn);
											w.Append(&wifiBtn);
											w.Append(&optionBrowser3);
											ResumeGui();

										}
									if (pick==2)Wad_Uninstall(file);
								    }
								    else gprintf("\nBad size");
								    //close that beast, we're done with it
								    fclose (file);

								    //do we want to keep the file in the wad folder
								    if (WindowPrompt(tr("Delete ?"), tmptxt, tr("Delete"),tr("Keep"))!=0)
									remove(tmptxt);
								    }
								else {
								    WindowPrompt(tr("ERROR:"), tr("Not a WAD file."), tr("OK"));
								    }
							}
						}



			if (error || read != infilesize) {
			    WindowPrompt(tr("Error:"), tr("No data could be read."), tr("OK"));


			}
			if(temp)free(temp);
		}



		CloseConnection();
                ResumeNetworkWait();
        }

        if (cancelBtn.GetState() == STATE_CLICKED) {
            //break the loop and end the function
            exit = true;
            ret = -10;
        }
	else if (screenShotBtn.GetState() == STATE_CLICKED) {
			gprintf("\n\tscreenShotBtn clicked");
			screenShotBtn.ResetState();
			ScreenShot();
			gprintf("...It's easy, mmmmmmKay");
		    }
    }

    CloseConnection();
    if (IsNetworkInit())
        HaltNetworkThread();

    fclose(f);
    HaltGui();
    mainWindow->Remove(&w);
    ResumeGui();

    return ret;
}
Esempio n. 19
0
int trunk_binlog_compress_rollback()
{
	int result;
	int rollback_fd;
	char binlog_filename[MAX_PATH_SIZE];
	char rollback_filename[MAX_PATH_SIZE];
	struct stat fs;

	get_trunk_binlog_filename(binlog_filename);
	get_trunk_rollback_filename(rollback_filename);
	if (trunk_binlog_fd < 0)
	{
		if (access(rollback_filename, F_OK) == 0)
		{
			if (rename(rollback_filename, binlog_filename) != 0)
			{
				result = errno != 0 ? errno : EPERM;
				logError("file: "__FILE__", line: %d, "\
					"rename %s to %s fail, " \
					"errno: %d, error info: %s",
					__LINE__, rollback_filename,
					binlog_filename, result,
					STRERROR(result));
				return result;
			}
		}

		return 0;
	}

	if (stat(rollback_filename, &fs) != 0)
	{
		result = errno != 0 ? errno : ENOENT;
		if (result == ENOENT)
		{
			return 0;
		}
		logError("file: "__FILE__", line: %d, " \
			"stat file %s fail, errno: %d, error info: %s",
			__LINE__, rollback_filename,
			result, STRERROR(result));
		return result;
	}

	if (fs.st_size == 0)
	{
		unlink(rollback_filename);  //delete zero file directly
		return 0;
	}

	if ((result=trunk_binlog_close_writer(true)) != 0)
	{
		return result;
	}

	if ((rollback_fd=trunk_binlog_open_read(rollback_filename,
		false)) < 0)
	{
		return errno != 0 ? errno : ENOENT;
	}

	result = trunk_binlog_merge_file(rollback_fd);
	close(rollback_fd);
	if (result == 0)
	{
		if (unlink(rollback_filename) != 0)
		{
			result = errno != 0 ? errno : EPERM;
			logWarning("file: "__FILE__", line: %d, " \
				"unlink %s fail, " \
				"errno: %d, error info: %s",
				__LINE__, rollback_filename,
				result, STRERROR(result));
		}

		return trunk_binlog_open_writer(binlog_filename);
	}
	else
	{
		trunk_binlog_open_writer(binlog_filename);
		return result;
	}
}
Esempio n. 20
0
int
isc_movefile(const char *oldname, const char *newname) {
	return (rename(oldname, newname));
}
Esempio n. 21
0
int
commonio_close(struct commonio_db *db)
{
	char buf[1024];
	int errors = 0;
	struct stat sb;

	if (!db->isopen) {
		errno = EINVAL;
		return 0;
	}
	db->isopen = 0;

	if (!db->changed || db->readonly) {
		fclose(db->fp);
		db->fp = NULL;
		goto success;
	}

	memzero(&sb, sizeof sb);
	if (db->fp) {
		if (fstat(fileno(db->fp), &sb)) {
			fclose(db->fp);
			db->fp = NULL;
			goto fail;
		}

		/*
		 * Create backup file.
		 */
		snprintf(buf, sizeof buf, "%s-", db->filename);

		if (create_backup(buf, db->fp))
			errors++;

		if (fclose(db->fp))
			errors++;

		if (errors) {
			db->fp = NULL;
			goto fail;
		}
	} else {
		/*
		 * Default permissions for new [g]shadow files.
		 * (passwd and group always exist...)
		 */
		sb.st_mode = 0400;
		sb.st_uid = 0;
		sb.st_gid = 0;
	}

	snprintf(buf, sizeof buf, "%s+", db->filename);

	db->fp = fopen_set_perms(buf, "w", &sb);
	if (!db->fp)
		goto fail;

	if (write_all(db))
		errors++;

	if (fflush(db->fp))
		errors++;
#ifdef HAVE_FSYNC
	if (fsync(fileno(db->fp)))
		errors++;
#else
	sync();
#endif
	if (fclose(db->fp))
		errors++;

	db->fp = NULL;

	if (errors) {
		unlink(buf);
		goto fail;
	}

	if (rename(buf, db->filename))
		goto fail;

	nscd_need_reload = 1;

success:
	free_linked_list(db);
	return 1;

fail:
	free_linked_list(db);
	return 0;
}
Esempio n. 22
0
int
auth_finalize(void)
{
    char temp_name[1024];	/* large filename size */

    if (xauth_modified) {
	if (dieing) {
	    if (verbose) {
		/*
		 * called from a signal handler -- printf is *not* reentrant; also
		 * fileno() might not be reentrant, avoid it if possible, and use
		 * stderr instead of stdout
		 */
#ifdef STDERR_FILENO
		WRITES(STDERR_FILENO, "\nAborting changes to authority file ");
		WRITES(STDERR_FILENO, xauth_filename);
		WRITES(STDERR_FILENO, "\n");
#else
		WRITES(fileno(stderr), "\nAborting changes to authority file ");
		WRITES(fileno(stderr), xauth_filename);
		WRITES(fileno(stderr), "\n");
#endif
	    }
	} else if (!xauth_allowed) {
	    fprintf (stderr,
		     "%s:  %s not writable, changes ignored\n",
		     ProgramName, xauth_filename);
	} else {
	    if (verbose) {
		printf ("%s authority file %s\n",
			ignore_locks ? "Ignoring locks and writing" :
			"Writing", xauth_filename);
	    }
	    temp_name[0] = '\0';
	    if (write_auth_file (temp_name) == -1) {
		fprintf (stderr,
			 "%s:  unable to write authority file %s\n",
			 ProgramName, temp_name);
	    } else {
		(void) unlink (xauth_filename);
#if defined(WIN32) || defined(__UNIXOS2__)
		if (rename(temp_name, xauth_filename) == -1)
#else
		/* Attempt to rename() if link() fails, since this may be on a FS that does not support hard links */
		if (link (temp_name, xauth_filename) == -1 && rename(temp_name, xauth_filename) == -1)
#endif
		{
		    fprintf (stderr,
		     "%s:  unable to link authority file %s, use %s\n",
			     ProgramName, xauth_filename, temp_name);
		} else {
		    (void) unlink (temp_name);
		}
	    }
	}
    }

    if (xauth_locked) {
	XauUnlockAuth (xauth_filename);
    }
    (void) umask (original_umask);
    return 0;
}
Esempio n. 23
0
int main(int ac, char **av)
{
	int lc;			/* loop counter */
	char *msg;		/* message returned from parse_opts */

	/*
	 * parse standard options
	 */
	if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL)
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);

	/*
	 * perform global setup for test
	 */
	setup();

	/*
	 * check looping state if -c option given
	 */
	for (lc = 0; TEST_LOOPING(lc); lc++) {

		Tst_count = 0;

		/*
		 * generate sequence of events
		 */
		if (chmod(".", 0755) < 0) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "chmod(\".\", 0755) failed");
		}
		event_set[Tst_count].mask = IN_ISDIR | IN_ATTRIB;
		strcpy(event_set[Tst_count].name, "");
		Tst_count++;

		if ((fd = creat(FILE_NAME1, 0755)) == -1) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "creat(\"%s\", 755) failed",
				 FILE_NAME1);
		}

		event_set[Tst_count].mask = IN_CREATE;
		strcpy(event_set[Tst_count].name, FILE_NAME1);
		Tst_count++;
		event_set[Tst_count].mask = IN_OPEN;
		strcpy(event_set[Tst_count].name, FILE_NAME1);
		Tst_count++;

		if (close(fd) == -1) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "close(%s) failed", FILE_NAME1);
		}
		event_set[Tst_count].mask = IN_CLOSE_WRITE;
		strcpy(event_set[Tst_count].name, FILE_NAME1);
		Tst_count++;

		if (rename(FILE_NAME1, FILE_NAME2) == -1) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "rename(%s, %s) failed",
				 FILE_NAME1, FILE_NAME2);
		}
		event_set[Tst_count].mask = IN_MOVED_FROM;
		strcpy(event_set[Tst_count].name, FILE_NAME1);
		Tst_count++;
		event_set[Tst_count].mask = IN_MOVED_TO;
		strcpy(event_set[Tst_count].name, FILE_NAME2);
		Tst_count++;

		if (getcwd(fname1, BUF_SIZE) == NULL) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "getcwd(%p, %d) failed", fname1,
				 BUF_SIZE);
		}

		snprintf(fname2, BUF_SIZE, "%s.rename1", fname1);
		if (rename(fname1, fname2) == -1) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "rename(%s, %s) failed", fname1, fname2);
		}
		event_set[Tst_count].mask = IN_MOVE_SELF;
		strcpy(event_set[Tst_count].name, "");
		Tst_count++;

		if (unlink(FILE_NAME2) == -1) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "unlink(%s) failed", FILE_NAME2);
		}
		event_set[Tst_count].mask = IN_DELETE;
		strcpy(event_set[Tst_count].name, FILE_NAME2);
		Tst_count++;

		/*
		 * test that duplicate events will be coalesced into
		 * a single event. This test case should be last, that
		 * we can correct determine kernel bug which exist before
		 * 2.6.25. See comment below.
		 */
		snprintf(fname3, BUF_SIZE, "%s.rename2", fname1);
		if (rename(fname2, fname3) == -1) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "rename(%s, %s) failed", fname2, fname3);
		}

		if (rename(fname3, fname1) == -1) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "rename(%s, %s) failed", fname3, fname1);
		}
		event_set[Tst_count].mask = IN_MOVE_SELF;
		strcpy(event_set[Tst_count].name, "");
		Tst_count++;

		if (Tst_count != TST_TOTAL) {
			tst_brkm(TBROK, cleanup,
				 "Tst_count and TST_TOTAL are not equal");
		}

		Tst_count = 0;

		int len, i = 0, test_num = 0;
		if ((len = read(fd_notify, event_buf, EVENT_BUF_LEN)) == -1) {
			tst_brkm(TBROK|TERRNO, cleanup,
				 "read(%d, buf, %zu) failed",
				 fd_notify, EVENT_BUF_LEN);

		}

		while (i < len) {
			struct inotify_event *event;
			event = (struct inotify_event *)&event_buf[i];
			if (test_num >= TST_TOTAL) {
				if (tst_kvercmp(2, 6, 25) < 0
				    && event_set[TST_TOTAL - 1].mask ==
				    event->mask)
					tst_resm(TWARN,
						 "This may be kernel bug. "
						 "Before kernel 2.6.25, a kernel bug "
						 "meant that the kernel code that was "
						 "intended to coalesce successive identical "
						 "events (i.e., the two most recent "
						 "events could potentially be coalesced "
						 "if the older had not yet been read) "
						 "instead checked if the most recent event "
						 "could be coalesced with the oldest "
						 "unread event. This has been fixed by commit"
						 "1c17d18e3775485bf1e0ce79575eb637a94494a2.");
				tst_resm(TFAIL,
					 "get unnecessary event: "
					 "wd=%d mask=%x cookie=%u len=%u"
					 "name=\"%s\"", event->wd, event->mask,
					 event->cookie, event->len,
					 event->name);

			} else if ((event_set[test_num].mask == event->mask)
				   &&
				   (!strncmp
				    (event_set[test_num].name, event->name,
				     event->len))) {
				tst_resm(TPASS,
					 "get event: wd=%d mask=%x"
					 " cookie=%u len=%u name=\"%s\"",
					 event->wd, event->mask, event->cookie,
					 event->len, event->name);

			} else {
				tst_resm(TFAIL, "get event: wd=%d mask=%x "
					 "(expected %x) cookie=%u len=%u "
					 "name=\"%s\" (expected \"%s\") %d",
					 event->wd, event->mask,
					 event_set[test_num].mask,
					 event->cookie, event->len, event->name,
					 event_set[test_num].name,
					 strcmp(event_set[test_num].name,
						event->name));
			}
			test_num++;
			i += EVENT_SIZE + event->len;
		}

		for (; test_num < TST_TOTAL; test_num++) {
			tst_resm(TFAIL, "didn't get event: mask=%x ",
				 event_set[test_num].mask);
		}
	}

	/* cleanup and exit */
	cleanup();
	tst_exit();
}
Esempio n. 24
0
void CNetworkInterfaceLinux::SetSettings(NetworkAssignment& assignment, std::string& ipAddress, std::string& networkMask, std::string& defaultGateway, std::string& essId, std::string& key, EncMode& encryptionMode)
{
#if defined(TARGET_LINUX)
   FILE* fr = fopen("/etc/network/interfaces", "r");
   if (!fr)
   {
      // TODO
      return;
   }

   FILE* fw = fopen("/tmp/interfaces.temp", "w");
   if (!fw)
   {
      // TODO
      fclose(fr);
      return;
   }

   char* line = NULL;
   size_t linel = 0;
   std::string s;
   bool foundInterface = false;
   bool dataWritten = false;

   while (getdelim(&line, &linel, '\n', fr) > 0)
   {
      std::vector<std::string> tokens;

      s = line;
      StringUtils::TrimLeft(s, " \t");
      StringUtils::TrimRight(s," \n");

      // skip comments
      if (!foundInterface && (s.empty() || s[0] == '#'))
      {
        fprintf(fw, "%s", line);
        continue;
      }

      // look for "iface <interface name> inet"
      StringUtils::Tokenize(s, tokens, " ");
      if (tokens.size() == 2 &&
          StringUtils::EqualsNoCase(tokens[0], "auto") &&
          StringUtils::EqualsNoCase(tokens[1], GetName()))
      {
         continue;
      }
      else if (!foundInterface &&
          tokens.size() == 4 &&
          StringUtils::EqualsNoCase(tokens[0], "iface") &&
          StringUtils::EqualsNoCase(tokens[1], GetName()) &&
          StringUtils::EqualsNoCase(tokens[2], "inet"))
      {
         foundInterface = true;
         WriteSettings(fw, assignment, ipAddress, networkMask, defaultGateway, essId, key, encryptionMode);
         dataWritten = true;
      }
      else if (foundInterface &&
               tokens.size() == 4 &&
               StringUtils::EqualsNoCase(tokens[0], "iface"))
      {
        foundInterface = false;
        fprintf(fw, "%s", line);
      }
      else if (!foundInterface)
      {
        fprintf(fw, "%s", line);
      }
   }
   free(line);

   if (!dataWritten && assignment != NETWORK_DISABLED)
   {
      fprintf(fw, "\n");
      WriteSettings(fw, assignment, ipAddress, networkMask, defaultGateway, essId, key, encryptionMode);
   }

   fclose(fr);
   fclose(fw);

   // Rename the file
   if (rename("/tmp/interfaces.temp", "/etc/network/interfaces") < 0)
   {
      // TODO
      return;
   }

   std::string cmd = "/sbin/ifdown " + GetName();
   if (system(cmd.c_str()) != 0)
     CLog::Log(LOGERROR, "Unable to stop interface %s", GetName().c_str());
   else
     CLog::Log(LOGINFO, "Stopped interface %s", GetName().c_str());

   if (assignment != NETWORK_DISABLED)
   {
      cmd = "/sbin/ifup " + GetName();
      if (system(cmd.c_str()) != 0)
        CLog::Log(LOGERROR, "Unable to start interface %s", GetName().c_str());
      else
        CLog::Log(LOGINFO, "Started interface %s", GetName().c_str());
   }
#endif
}
Esempio n. 25
0
int default_create_and_write(uint64_t oid, const struct siocb *iocb)
{
	char path[PATH_MAX], tmp_path[PATH_MAX];
	int flags = prepare_iocb(oid, iocb, true);
	int ret, fd;
	uint32_t len = iocb->length;
	size_t obj_size;

	sd_debug("%"PRIx64, oid);
	get_store_path(oid, iocb->ec_index, path);
	get_store_tmp_path(oid, iocb->ec_index, tmp_path);
	fd = open(tmp_path, flags, sd_def_fmode);
	if (fd < 0) {
		if (errno == EEXIST) {
			/*
			 * This happens if node membership changes during object
			 * creation; while gateway retries a CREATE request,
			 * recovery process could also recover the object at the
			 * same time.  They should try to write the same date,
			 * so it is okay to simply return success here.
			 */
			sd_debug("%s exists", tmp_path);
			return SD_RES_SUCCESS;
		}

		sd_err("failed to open %s: %m", tmp_path);
		return err_to_sderr(path, oid, errno);
	}

	obj_size = get_store_objsize(oid);
	ret = prealloc(fd, obj_size);
	if (ret < 0) {
	          ret = err_to_sderr(path, oid, errno);
		  goto out;
	}

	ret = xpwrite(fd, iocb->buf, len, iocb->offset);
	if (ret != len) {
		sd_err("failed to write object. %m");
		ret = err_to_sderr(path, oid, errno);
		goto out;
	}

	/*
	 * Modern FS like ext4, xfs defaults to automatic syncing of files after
	 * replace-via-rename and replace-via-truncate operations. So rename
	 * without fsync() is actually safe.
	 */
	ret = rename(tmp_path, path);
	if (ret < 0) {
		sd_err("failed to rename %s to %s: %m", tmp_path, path);
		ret = err_to_sderr(path, oid, errno);
		goto out;
	}

	ret = SD_RES_SUCCESS;
	objlist_cache_insert(oid);
out:
	if (ret != SD_RES_SUCCESS && unlink(tmp_path) != 0)
		sd_err("failed to unlink %s: %m", tmp_path);
	close(fd);
	return ret;
}
Esempio n. 26
0
/*
 * Permanently drop the currently acquired replication slot which will be
 * released by the point this function returns.
 */
static void
ReplicationSlotDropAcquired(void)
{
	char		path[MAXPGPATH];
	char		tmppath[MAXPGPATH];
	ReplicationSlot *slot = MyReplicationSlot;

	Assert(MyReplicationSlot != NULL);

	/* slot isn't acquired anymore */
	MyReplicationSlot = NULL;

	/*
	 * If some other backend ran this code concurrently with us, we might try
	 * to delete a slot with a certain name while someone else was trying to
	 * create a slot with the same name.
	 */
	LWLockAcquire(ReplicationSlotAllocationLock, LW_EXCLUSIVE);

	/* Generate pathnames. */
	sprintf(path, "pg_replslot/%s", NameStr(slot->data.name));
	sprintf(tmppath, "pg_replslot/%s.tmp", NameStr(slot->data.name));

	/*
	 * Rename the slot directory on disk, so that we'll no longer recognize
	 * this as a valid slot.  Note that if this fails, we've got to mark the
	 * slot inactive before bailing out.  If we're dropping a ephemeral slot,
	 * we better never fail hard as the caller won't expect the slot to
	 * survive and this might get called during error handling.
	 */
	if (rename(path, tmppath) == 0)
	{
		/*
		 * We need to fsync() the directory we just renamed and its parent to
		 * make sure that our changes are on disk in a crash-safe fashion.  If
		 * fsync() fails, we can't be sure whether the changes are on disk or
		 * not.  For now, we handle that by panicking;
		 * StartupReplicationSlots() will try to straighten it out after
		 * restart.
		 */
		START_CRIT_SECTION();
		fsync_fname(tmppath, true);
		fsync_fname("pg_replslot", true);
		END_CRIT_SECTION();
	}
	else
	{
		volatile ReplicationSlot *vslot = slot;
		bool		fail_softly = slot->data.persistency == RS_EPHEMERAL;

		SpinLockAcquire(&slot->mutex);
		vslot->active = false;
		SpinLockRelease(&slot->mutex);

		ereport(fail_softly ? WARNING : ERROR,
				(errcode_for_file_access(),
				 errmsg("could not rename file \"%s\" to \"%s\": %m",
						path, tmppath)));
	}

	/*
	 * The slot is definitely gone.  Lock out concurrent scans of the array
	 * long enough to kill it.  It's OK to clear the active flag here without
	 * grabbing the mutex because nobody else can be scanning the array here,
	 * and nobody can be attached to this slot and thus access it without
	 * scanning the array.
	 */
	LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE);
	slot->active = false;
	slot->in_use = false;
	LWLockRelease(ReplicationSlotControlLock);

	/*
	 * Slot is dead and doesn't prevent resource removal anymore, recompute
	 * limits.
	 */
	ReplicationSlotsComputeRequiredXmin(false);
	ReplicationSlotsComputeRequiredLSN();

	/*
	 * If removing the directory fails, the worst thing that will happen is
	 * that the user won't be able to create a new slot with the same name
	 * until the next server restart.  We warn about it, but that's all.
	 */
	if (!rmtree(tmppath, true))
		ereport(WARNING,
				(errcode_for_file_access(),
				 errmsg("could not remove directory \"%s\"", tmppath)));

	/*
	 * We release this at the very end, so that nobody starts trying to create
	 * a slot while we're still cleaning up the detritus of the old one.
	 */
	LWLockRelease(ReplicationSlotAllocationLock);
}
Esempio n. 27
0
int
run_attr_tests(char *testfile)
{
    int ret = -1;
    char *res = NULL;
    struct stat buf;
    struct statfs sbuf;
    struct statvfs svbuf;

    assert(testfile);

    fprintf(stdout, "Testing chmod");
    ret = chmod(testfile, 0);
    check_err(ret, "chmod", 2);

    fprintf(stdout, "Testing chown");
    ret = chown(testfile, 0, 0);
    check_err(ret, "chown", 2);

    fprintf(stdout, "Testing link");
    ret = link(testfile, testfile);
    check_err(ret, "link", 2);

    fprintf(stdout, "Testing rename");
    ret = rename(testfile, testfile);
    check_err(ret, "rename", 2);

    fprintf(stdout, "Testing utimes");
    ret = utimes(testfile, NULL);
    check_err(ret, "utimes", 2);

    fprintf(stdout, "Testing utime");
    ret = utime(testfile, NULL);
    check_err(ret, "utime", 2);

    fprintf(stdout, "Testing unlink");
    ret = unlink(testfile);
    check_err(ret, "unlink", 2);

    fprintf(stdout, "Testing symlink");
    ret = symlink(testfile, testfile);
    check_err(ret, "symlink", 2);

    fprintf(stdout, "Testing readlink");
    ret = readlink(testfile, testfile, 0);
    check_err(ret, "readlink", 2);

    fprintf(stdout, "Testing realpath");
    ret = 0;
    res = realpath((const char *)testfile, testfile);
    if (!res)
        ret = -1;
    check_err(ret, "realpath", 2);

    fprintf(stdout, "Testing stat");
    ret = stat(testfile, &buf);
    check_err(ret, "stat", 1);

    fprintf(stdout, "Testing lstat");
    ret = lstat(testfile, &buf);
    check_err(ret, "lstat", 1);

    fprintf(stdout, "Testing statfs");
    ret = statfs(testfile, &sbuf);
    check_err(ret, "statfs", 2);

    fprintf(stdout, "Testing statvfs");
    ret = statvfs(testfile, &svbuf);
    check_err(ret, "statvfs", 1);

    fprintf(stdout, "Testing getxattr");
    ret = getxattr(testfile, NULL, NULL, 0);
    check_err(ret, "getxattr", 2);

    fprintf(stdout, "Testing lgetxattr");
    ret = lgetxattr(testfile, NULL, NULL, 0);
    check_err(ret, "lgetxattr", 1);

    fprintf(stdout, "Testing lchown");
    ret = lchown(testfile, 0, 0);
    check_err(ret, "lchown", 2);
    return 0;
}
Esempio n. 28
0
/*
 * Shared functionality between saving and creating a replication slot.
 */
static void
SaveSlotToPath(ReplicationSlot *slot, const char *dir, int elevel)
{
	char		tmppath[MAXPGPATH];
	char		path[MAXPGPATH];
	int			fd;
	ReplicationSlotOnDisk cp;
	bool		was_dirty;

	/* first check whether there's something to write out */
	{
		volatile ReplicationSlot *vslot = slot;

		SpinLockAcquire(&vslot->mutex);
		was_dirty = vslot->dirty;
		vslot->just_dirtied = false;
		SpinLockRelease(&vslot->mutex);
	}

	/* and don't do anything if there's nothing to write */
	if (!was_dirty)
		return;

	LWLockAcquire(slot->io_in_progress_lock, LW_EXCLUSIVE);

	/* silence valgrind :( */
	memset(&cp, 0, sizeof(ReplicationSlotOnDisk));

	sprintf(tmppath, "%s/state.tmp", dir);
	sprintf(path, "%s/state", dir);

	fd = OpenTransientFile(tmppath,
						   O_CREAT | O_EXCL | O_WRONLY | PG_BINARY,
						   S_IRUSR | S_IWUSR);
	if (fd < 0)
	{
		ereport(elevel,
				(errcode_for_file_access(),
				 errmsg("could not create file \"%s\": %m",
						tmppath)));
		return;
	}

	cp.magic = SLOT_MAGIC;
	INIT_CRC32C(cp.checksum);
	cp.version = SLOT_VERSION;
	cp.length = ReplicationSlotOnDiskV2Size;

	SpinLockAcquire(&slot->mutex);

	memcpy(&cp.slotdata, &slot->data, sizeof(ReplicationSlotPersistentData));

	SpinLockRelease(&slot->mutex);

	COMP_CRC32C(cp.checksum,
				(char *) (&cp) + SnapBuildOnDiskNotChecksummedSize,
				SnapBuildOnDiskChecksummedSize);
	FIN_CRC32C(cp.checksum);

	if ((write(fd, &cp, sizeof(cp))) != sizeof(cp))
	{
		int			save_errno = errno;

		CloseTransientFile(fd);
		errno = save_errno;
		ereport(elevel,
				(errcode_for_file_access(),
				 errmsg("could not write to file \"%s\": %m",
						tmppath)));
		return;
	}

	/* fsync the temporary file */
	if (pg_fsync(fd) != 0)
	{
		int			save_errno = errno;

		CloseTransientFile(fd);
		errno = save_errno;
		ereport(elevel,
				(errcode_for_file_access(),
				 errmsg("could not fsync file \"%s\": %m",
						tmppath)));
		return;
	}

	CloseTransientFile(fd);

	/* rename to permanent file, fsync file and directory */
	if (rename(tmppath, path) != 0)
	{
		ereport(elevel,
				(errcode_for_file_access(),
				 errmsg("could not rename file \"%s\" to \"%s\": %m",
						tmppath, path)));
		return;
	}

	/* Check CreateSlot() for the reasoning of using a crit. section. */
	START_CRIT_SECTION();

	fsync_fname(path, false);
	fsync_fname((char *) dir, true);
	fsync_fname("pg_replslot", true);

	END_CRIT_SECTION();

	/*
	 * Successfully wrote, unset dirty bit, unless somebody dirtied again
	 * already.
	 */
	{
		volatile ReplicationSlot *vslot = slot;

		SpinLockAcquire(&vslot->mutex);
		if (!vslot->just_dirtied)
			vslot->dirty = false;
		SpinLockRelease(&vslot->mutex);
	}

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

    size_t len = strlen(buf);

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

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

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

    delete[] buf;
    delete[] newbuf;
    return 0;
}
Esempio n. 30
0
void RenameHTML (void)
{
 char ch;

 int i;
 struct ffblk ffblk;
 int done;

 unsigned files_renamed = 0;

 done = findfirst("*.htm*",&ffblk,0);
// done = findfirst("f:\\zzz\\*.htm*",&ffblk,0);
 printf ("\n\r");

 while (!done)
 {
  Text.resize(0);
  FileName.resize(0);
  PageName.resize(0);
  DestName.resize(0);
  TitleName.resize(0);
  H1Name.resize(0);
  H2Name.resize(0);
  H3Name.resize(0);

//  FileName += "f:\\zzz\\";
  FileName += ffblk.ff_name;

  if (LoadFromFile (FileName) == -1)
  {
   done = findnext(&ffblk);
   continue;
  }

  if (Text.length() < 2) continue;

//  DestName += "f:\\zzz\\";

  FindTitle (TTB,TTE);
  TitleName  += Result;

  FindTitle (H1B,H1E);
  H1Name     += Result;

  FindTitle (H2B,H2E);
  H2Name     += Result;

  FindTitle (H3B,H3E);
  H3Name     += Result;

  if (TitleName.length() + H1Name.length() + H2Name.length() + H3Name.length() > 5)
  {

   if (TitleName.length() > 1) PageName += TitleName;
   if (H1Name.length() > 1)    PageName += '-'+H1Name;
   if (H2Name.length() > 1)    PageName += '-'+H2Name;
   if (H3Name.length() > 1)    PageName += '-'+H3Name;

/*
   printf ("\n\r------------------------------------------\n\r");
   printf ("Original File Name : %s\n\r",FileName.c_str());

   if (TitleName.length() > 1)
   {
    printf ("Title : %s\n\r\n\r",TitleName.c_str());
    PageName += TitleName;
   }

   if (H1Name.length() > 1)
   {
    printf ("Header 1 : %s\n\r",H1Name.c_str());
    printf ("to include press [ Enter ]\n\r");
    ch = getch();
    if (ch == '\xd') PageName += '-'+H1Name;
    else
    if (ch == 0) getch();
   }

   if (H2Name.length() > 1)
   {
    printf ("Header 2 : %s\n\r",H2Name.c_str());
    printf ("to include press [ Enter ]\n\r");
    ch = getch();
    if (ch == '\xd') PageName += '-'+H2Name;
    else
    if (ch == 0) getch();
   }

   if (H3Name.length() > 1)
   {
    printf ("Header 3 : %s\n\r",H3Name.c_str());
    printf ("to include press [ Enter ]\n\r");
    ch = getch();
    if (ch == '\xd') PageName += '-'+H3Name;
    else
    if (ch == 0) getch();
   }
*/
   if (PageName.length() > 240) PageName.resize(240);

   KillNotAllowed (PageName);
   DestName += PageName + ".hhttmmll";

//   printf ("New File Name      : %s\n\r",DestName.c_str());
//   printf ("----------------------------------------------\n\r");

   if (rename (FileName.c_str(),DestName.c_str()) == -1)
    printf ("Cannot rename \n\r'%s' to \n\r'%s' \n\r",FileName.c_str(),DestName.c_str());
   else
   ++files_renamed;
  }
  done = findnext(&ffblk);
 }
 printf ("\n\r[%d] file(s) renamed",files_renamed);
}