Exemple #1
0
int main(int argc, char *argv[])
{
	int i, devfd, c, readlen, writelen;
	int req_blocks, part1_offset;
	int ubl_size, uboot_size;
	struct rbl_header *rblp;
	unsigned int uboot_load_address, uboot_entry_point;

	uboot_load_address = uboot_entry_point = UBOOT_LOAD_ADDRESS;

	while ((c = getopt(argc, argv, "?hvd:u:b:l:e:")) >= 0) {
		switch (c) {
		case 'd':
			dev_name = optarg;
			break;
		case 'u':
			ubl_name = optarg;
			break;
		case 'l':
			uboot_load_address = strtoul(optarg, NULL, 16);
			break;
		case 'e':
			uboot_entry_point = strtoul(optarg, NULL, 16);
			break;
		case 'v':
			verbose++;
			break;
		case 'b':
			uboot_name = optarg;
			break;
		case 'h':
		case '?':
			usage();
			return 0;
		}
	}

	/* Open the SD/MMC Device in Read-Write Mode */
	devfd = open(dev_name, O_RDWR);
	if (devfd <= 0) {
		fprintf(stderr, "Open Device %s : %s\n",
				dev_name, strerror(errno));
		usage();
		exit(-1);
	}

	/* Read Master Boot Record - MBR */
	readlen = read(devfd, readbuf, BLOCK_SIZE);
	if (readlen < 0) {
		fprintf(stderr, "Read Device %s : %s\n",
				dev_name, strerror(errno));
	}

	if (verbose > 2) {
		printf("====================Master Boot "
				"Record====================\n");
		print_hex((uint8 *)readbuf, BLOCK_SIZE);
		printf("================================"
				"==========================\n");
	}

	/* Get UBL file size and round it to upper 512 byte boundary */
	ubl_size = get_file_size(ubl_name);
	if (ubl_size < 0) {
		close(devfd);
		return -1;
	}
	ubl_size = (ubl_size + BLOCK_SIZE - 1) & ~BLOCK_SIZE;
	verbose_printf("UBL Size %d\n", ubl_size);

	/* Get U-boot file size and round it to upper 512 byte boundary */
	uboot_size = get_file_size(uboot_name);
	if (uboot_size <= 0) {
		fprintf(stderr, "Invalid U-Boot Size %d\n", uboot_size);
		close(devfd);
		return -1;
	}
	uboot_size = (uboot_size + BLOCK_SIZE - 1) & ~BLOCK_SIZE;
	verbose_printf("U-Boot Size %d\n", uboot_size);

	/* Get first partition start address offset from Master Boot Record */
	part1_offset = get_le32((uint8 *)&readbuf[PART1_LBA_OFFSET]);
	verbose_printf("First partition starts at %d(%ld)\n", part1_offset,
			(part1_offset * BLOCK_SIZE));

	/* Add MBR + UBL Size + Uboot Size */
	req_blocks = UBL_START_BLOCK + (ubl_size / BLOCK_SIZE) +
		UBL_BLOCK_OFFSET + (uboot_size / BLOCK_SIZE) + 1;
	printf("Required Blocks %d, Available Blocks %d\n", req_blocks,
			part1_offset - 1);

	/* Return if the card does not have enough space for writing */
	if (req_blocks > part1_offset) {
		fprintf(stderr, "Not enough space left for flashing "
				"UBL and U-boot\n");
		fprintf(stderr, "Make sure that the First Partition Starts "
				"after %d sectors\n", req_blocks);
		close(devfd);
		return -1;
	}

	/* Generate UBL Signature */
	rblp = (struct rbl_header *)ubl_signature;
	memset(rblp, 0, sizeof(struct rbl_header));
	rblp->magic_num = UBL_MAGIC_NUM;
	rblp->entry_point = UBL_ENTRY_POINT;
	rblp->num_blocks = ubl_size / BLOCK_SIZE;
	rblp->start_block = UBL_START_BLOCK;

	if (verbose > 1) {
		printf("UBL Magic Number        : %08x\n", rblp->magic_num);
		printf("UBL Entry Point         : %08x\n", rblp->entry_point);
		printf("UBL Number of Blocks    : %08x\n", rblp->num_blocks);
		printf("UBL Starting Block      : %08x\n", rblp->start_block);
		printf("UBL Load Address        : %08x\n", rblp->load_address);
	}

	/* Write UBL Signature */
	verbose_printf("Writing UBL Signature\n");
	lseek(devfd, (BLOCK_SIZE * UBL_SIGN_START), SEEK_SET);
	for (i = UBL_SIGN_START; i < (UBL_SIGN_COUNT + UBL_SIGN_START); i++) {
		writelen = write(devfd, rblp, BLOCK_SIZE);
		if (writelen < BLOCK_SIZE) {
			close(devfd);
			return -1;
		}
	}

	/* Write UBL Binary */
	verbose_printf("Writing UBL\n");
	lseek(devfd, (BLOCK_SIZE * rblp->start_block), SEEK_SET);
	write_file(devfd, ubl_name);

	/* Generate U-boot signature */
	rblp = (struct rbl_header *)uboot_signature;
	memset(rblp, 0, sizeof(struct rbl_header));
	rblp->magic_num = UBOOT_MAGIC_NUM;
	rblp->entry_point = uboot_entry_point;
	rblp->num_blocks = (uboot_size / BLOCK_SIZE) + 1;
	rblp->start_block = UBL_START_BLOCK + (ubl_size / BLOCK_SIZE) +
		UBL_BLOCK_OFFSET;
	rblp->load_address = uboot_load_address;

	if (verbose > 1) {
		printf("U-Boot Magic Number     : %08x\n", rblp->magic_num);
		printf("U-Boot Entry Point      : %08x\n", rblp->entry_point);
		printf("U-Boot Number of Blocks : %08x\n", rblp->num_blocks);
		printf("U-Boot Starting Block   : %08x\n", rblp->start_block);
		printf("Load U-Boot Address     : %08x\n", rblp->load_address);
	}

	/* Write U-Boot Signature */
	verbose_printf("Writing U-Boot Signature\n");
	lseek(devfd, (BLOCK_SIZE * UBOOT_SIGN_START), SEEK_SET);
	for (i = UBOOT_SIGN_START; i < (UBOOT_SIGN_COUNT + UBOOT_SIGN_START);
			i++) {
		writelen = write(devfd, rblp, BLOCK_SIZE);
		if (writelen < BLOCK_SIZE) {
			close(devfd);
			return -1;
		}
	}

	/* Write U-Boot File */
	lseek(devfd, (BLOCK_SIZE * rblp->start_block), SEEK_SET);
	verbose_printf("Writing U-Boot\n");
	write_file(devfd, uboot_name);

	printf("Done...\n");
	close(devfd);
	return 0;
}
Exemple #2
0
int main()
{
    printf(
        "Going to try to delete files using various techiques.\n"
        "Note that the MoveFileEx method will fail (see source why)\n"
    );

    write_file("abc.txt", "DeleteFile");

    //
    // delete the file using the well-known DeleteFile function
    //

    printf("DeleteFile: %s (0x%08x)\n", DeleteFile("abc.txt") ?
        "SUCCESS" : "FAILURE", GetLastError());

    write_file("abc.txt", "MoveFileEx");

    //
    // delete the file using MoveFileEx, note that a NULL destination filename
    // is only supported when the MOVEFILE_DELAY_UNTIL_REBOOT flag is set.
    // (so this call will actually fail..)
    //

    printf("MoveFileEx: %s (0x%08x)\n", MoveFileEx("abc.txt", NULL, 0) ?
        "SUCCESS" : "FAILURE", GetLastError());

    write_file("abc.txt", "ZwDeleteFile");

    //
    // delete the file using ZwDeleteFile
    //

    UNICODE_STRING dir_fname, file_fname;
    OBJECT_ATTRIBUTES obj_dir, obj_file;
    IO_STATUS_BLOCK io_dir;
    HANDLE dir_handle;

    *(FARPROC *) &pRtlInitUnicodeString = GetProcAddress(
        GetModuleHandle("ntdll"), "RtlInitUnicodeString");
    *(FARPROC *) &pZwDeleteFile = GetProcAddress(
        GetModuleHandle("ntdll"), "ZwDeleteFile");
    *(FARPROC *) &pZwCreateFile = GetProcAddress(
        GetModuleHandle("ntdll"), "ZwCreateFile");
    *(FARPROC *) &pZwSetInformationFile = GetProcAddress(
        GetModuleHandle("ntdll"), "ZwSetInformationFile");

    // prepend the path with "\\??\\"
    wchar_t cur_dir[MAX_PATH] = L"\\??\\";
    GetCurrentDirectoryW(MAX_PATH-4, cur_dir+4);

    pRtlInitUnicodeString(&dir_fname, cur_dir);
    pRtlInitUnicodeString(&file_fname, L"abc.txt");

    InitializeObjectAttributes(&obj_dir, &dir_fname,
        OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);

    // open the directory
    NTSTATUS ret = pZwCreateFile(&dir_handle, FILE_TRAVERSE, &obj_dir,
        &io_dir, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN,
        FILE_DIRECTORY_FILE, NULL, 0);

    if(NT_SUCCESS(ret)) {
        InitializeObjectAttributes(&obj_file, &file_fname,
            OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, dir_handle, NULL);

        // delete the file
        ret = pZwDeleteFile(&obj_file);
        printf("ZwDeleteFile: %s (0x%08x)\n", NT_SUCCESS(ret) ?
            "SUCCESS" : "FAILURE", ret);
        CloseHandle(dir_handle);
    }
    else {
        printf("ZwDeleteFile: FAILURE (0x%08x)\n", ret);
    }

    write_file("abc.txt", "ZwSetInformationFile");

    //
    // delete the file using ZwSetInformationFile
    //

    IO_STATUS_BLOCK io_file;
    HANDLE file_handle;

    // prepend the path with "\\??\\" and append "abc.txt"
    wchar_t file_name[MAX_PATH] = L"\\??\\";
    GetCurrentDirectoryW(MAX_PATH-4, file_name+4);
    lstrcatW(file_name, L"\\abc.txt");

    pRtlInitUnicodeString(&file_fname, file_name);
    InitializeObjectAttributes(&obj_file, &file_fname,
        OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);

    // open the file with DELETE access rights
    ret = pZwCreateFile(&file_handle, DELETE, &obj_file, &io_file, NULL,
        FILE_ATTRIBUTE_NORMAL, 0, FILE_OPEN, 0, NULL, 0);
    if(NT_SUCCESS(ret)) {
        BOOLEAN disp_info = TRUE;
        ret = pZwSetInformationFile(file_handle, &io_file, &disp_info,
            sizeof(disp_info), FileDispositionInformation);
        CloseHandle(file_handle);

        printf("ZwSetInformationFile: %s (0x%08x)\n", NT_SUCCESS(ret) ?
            "SUCCESS" : "FAILURE", ret);
    }
    else {
        printf("ZwSetInformationFile: FAILURE (0x%08x)\n", ret);
    }
}
Exemple #3
0
int do_write(int nargs, char **args)
{
    return write_file(args[1], args[2]);
}
Exemple #4
0
int run_assembly()
{
#ifdef _WIN32
	struct _timeb time_start, time_end;
	_ftime(&time_start);
#else
	struct timeb time_start, time_end;
	ftime(&time_start);
#endif
	exit_code = EXIT_NORMAL;
	
	/*extern int generic_map[256];
	ZeroMemory(generic_map, 256);*/
	program_counter = 0x0000;
	stats_codesize = stats_datasize = stats_mintime = stats_maxtime = 0;
	last_label = NULL;
	error_occurred = false;
	listing_offset = 0;
	listing_for_line_done = false;
	line_start = NULL;
	old_line_num = 0;
	in_macro = 0;
	line_num = 0;
#ifdef USE_BUILTIN_FCREATE
	cur_buf = 0;
#endif
#ifdef USE_REUSABLES
	curr_reusable = 0;
	total_reusables = 0;
#endif
	
	expr_list = NULL;
	expr_list_tail = NULL;
	output_list = NULL;
	output_list_tail = NULL;

	assert(curr_input_file != NULL);

	//read in the input file
	if (!(mode & MODE_COMMANDLINE))
		input_contents = (char *) get_file_contents (curr_input_file);

	if (!input_contents) {
		puts ("Couldn't open input file");
		return EXIT_FATAL_ERROR;
	}
	
	out_ptr = output_contents;

	//along with the listing buffer, if required
	if ((mode & MODE_LIST)) {
		listing_buf = eb_init (LISTING_BUF_SIZE);
		listing_offset = 0;
		listing_on = true;
	}
	
	//find the path of the input file
	if (is_abs_path(curr_input_file)) {
		int i;

		strcpy(temp_path, curr_input_file);
	
		for (i = strlen(temp_path) - 1; 
			temp_path[i] != '\\' && temp_path[i] != '/' && i > 0; i--);
		if (i >= 0)
			temp_path[i] = '\0';
		else
			strcpy(temp_path, ".");
	} else {
#ifdef WIN32
		_getcwd(temp_path, sizeof (temp_path));
#else
		getcwd(temp_path, sizeof (temp_path));
#endif
	}

	//add the the input file's path to the include directories
	include_dirs = list_prepend (include_dirs, strdup (temp_path));

	printf ("Pass one... \n");

	int first_pass_session = StartSPASMErrorSession();
	run_first_pass ((char *) input_contents);
	ReplayFatalSPASMErrorSession(first_pass_session);
	EndSPASMErrorSession(first_pass_session);

	//free include dirs when done
	if ((mode & MODE_COMMANDLINE) == 0)
	{
		release_file_contents(input_contents);
		input_contents = NULL;
	}
	
	list_free (include_dirs, true, NULL);
	include_dirs = NULL;

	//...and if there's output, run the second pass and write it to the output file
	if (mode & MODE_SYMTABLE || mode & MODE_NORMAL || mode & MODE_LIST)
	{
		printf ("Pass two... \n");
		int second_pass_session = StartSPASMErrorSession();
		run_second_pass ();
		ReplaySPASMErrorSession(second_pass_session);
		EndSPASMErrorSession(second_pass_session);

		if (mode & MODE_SYMTABLE) {
			char* fileName = change_extension(output_filename, "lab");
			write_labels (fileName);
			free(fileName);
		}

		//run the output through the appropriate program export and write it to a file
		if (mode & MODE_NORMAL && output_filename != NULL)
		{
			write_file (output_contents, out_ptr - output_contents, output_filename);
		}

		//write the listing file if necessary
		if ((mode & MODE_LIST)) {
			FILE *file;
			char *name;

			//get file name
			name = change_extension (output_filename, "lst");
			file = fopen (name, "wb");
			if (!file) {
				printf ("Couldn't open listing file '%s'", name);
				free (name);
				return EXIT_FATAL_ERROR;
			}
			free (name);
			
			if (fwrite (listing_buf->start, 1, listing_offset, file) != listing_offset) {
				puts ("Error writing to listing file");
				fclose (file);
				return EXIT_FATAL_ERROR;
			}

			fclose (file);
			eb_free(listing_buf);
			listing_buf = NULL;
		}
		
		//free the output buffer and all the names of input files
		list_free(input_files, true, NULL);
		input_files = NULL;
	}

	//if there's info to be dumped, do that
	if (mode & MODE_CODE_COUNTER) {
		fprintf (stdout, "Size: %u\nMin. execution time: %u\nMax. execution time: %u\n",
		         stats_codesize, stats_mintime, stats_maxtime);
	}
	
	if (mode & MODE_STATS) {
		fprintf(stdout, "Number of labels: %u\nNumber of defines: %u\nCode size: %u\nData size: %u\nTotal size: %u\n",
		         get_num_labels (), get_num_defines (), stats_codesize, stats_datasize, stats_codesize + stats_datasize);
	}
	
#ifdef _WIN32
	_ftime(&time_end);
#else
	ftime(&time_end);
#endif
	int s_diff = (int) (time_end.time - time_start.time);
	int ms_diff = time_end.millitm - time_start.millitm;
	if (ms_diff < 0) {
		ms_diff += 1000;
		s_diff -= 1;
	} else if (ms_diff > 1000) {
		ms_diff -= 1000;
		s_diff += 1;
	}
	printf("Assembly time: %0.3f seconds\n", (float) s_diff + ((float) ms_diff / 1000.0f));
	return exit_code;
}
Exemple #5
0
_nc_write_entry(TERMTYPE *const tp)
{
#if USE_HASHED_DB

    char buffer[MAX_ENTRY_SIZE + 1];
    unsigned limit = sizeof(buffer);
    unsigned offset = 0;

#else /* !USE_HASHED_DB */

    struct stat statbuf;
    char filename[PATH_MAX];
    char linkname[PATH_MAX];
#if USE_SYMLINKS
    char symlinkname[PATH_MAX];
#if !HAVE_LINK
#undef HAVE_LINK
#define HAVE_LINK 1
#endif
#endif /* USE_SYMLINKS */

    static int call_count;
    static time_t start_time;	/* time at start of writes */

#endif /* USE_HASHED_DB */

    char name_list[MAX_TERMINFO_LENGTH];
    char *first_name, *other_names;
    char *ptr;
    char *term_names = tp->term_names;
    size_t name_size = strlen(term_names);

    if (name_size == 0) {
	_nc_syserr_abort("no terminal name found.");
    } else if (name_size >= sizeof(name_list) - 1) {
	_nc_syserr_abort("terminal name too long: %s", term_names);
    }

    _nc_STRCPY(name_list, term_names, sizeof(name_list));
    DEBUG(7, ("Name list = '%s'", name_list));

    first_name = name_list;

    ptr = &name_list[name_size - 1];
    other_names = ptr + 1;

    while (ptr > name_list && *ptr != '|')
	ptr--;

    if (ptr != name_list) {
	*ptr = '\0';

	for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
	    continue;

	if (*ptr == '\0')
	    other_names = ptr;
	else {
	    *ptr = '\0';
	    other_names = ptr + 1;
	}
    }

    DEBUG(7, ("First name = '%s'", first_name));
    DEBUG(7, ("Other names = '%s'", other_names));

    _nc_set_type(first_name);

#if USE_HASHED_DB
    if (write_object(tp, buffer + 1, &offset, limit - 1) != ERR) {
	DB *capdb = _nc_db_open(_nc_tic_dir(0), TRUE);
	DBT key, data;

	if (capdb != 0) {
	    buffer[0] = 0;

	    memset(&key, 0, sizeof(key));
	    key.data = term_names;
	    key.size = name_size;

	    memset(&data, 0, sizeof(data));
	    data.data = buffer;
	    data.size = offset + 1;

	    _nc_db_put(capdb, &key, &data);

	    buffer[0] = 2;

	    key.data = name_list;
	    key.size = strlen(name_list);

	    _nc_STRCPY(buffer + 1,
		       term_names,
		       sizeof(buffer) - 1);
	    data.size = name_size + 1;

	    _nc_db_put(capdb, &key, &data);

	    while (*other_names != '\0') {
		ptr = other_names++;
		assert(ptr < buffer + sizeof(buffer) - 1);
		while (*other_names != '|' && *other_names != '\0')
		    other_names++;

		if (*other_names != '\0')
		    *(other_names++) = '\0';

		key.data = ptr;
		key.size = strlen(ptr);

		_nc_db_put(capdb, &key, &data);
	    }
	}
    }
#else /* !USE_HASHED_DB */
    if (call_count++ == 0) {
	start_time = 0;
    }

    if (strlen(first_name) >= sizeof(filename) - (2 + LEAF_LEN))
	_nc_warning("terminal name too long.");

    _nc_SPRINTF(filename, _nc_SLIMIT(sizeof(filename))
		LEAF_FMT "/%s", first_name[0], first_name);

    /*
     * Has this primary name been written since the first call to
     * write_entry()?  If so, the newer write will step on the older,
     * so warn the user.
     */
    if (start_time > 0 &&
	stat(filename, &statbuf) >= 0
	&& statbuf.st_mtime >= start_time) {
#if HAVE_LINK && !USE_SYMLINKS
	/*
	 * If the file has more than one link, the reason for the previous
	 * write could be that the current primary name used to be an alias for
	 * the previous entry.  In that case, unlink the file so that we will
	 * not modify the previous entry as we write this one.
	 */
	if (statbuf.st_nlink > 1) {
	    _nc_warning("name redefined.");
	    unlink(filename);
	} else {
	    _nc_warning("name multiply defined.");
	}
#else
	_nc_warning("name multiply defined.");
#endif
    }

    check_writeable(first_name[0]);
    write_file(filename, tp);

    if (start_time == 0) {
	if (stat(filename, &statbuf) < 0
	    || (start_time = statbuf.st_mtime) == 0) {
	    _nc_syserr_abort("error obtaining time from %s/%s",
			     _nc_tic_dir(0), filename);
	}
    }
    while (*other_names != '\0') {
	ptr = other_names++;
	while (*other_names != '|' && *other_names != '\0')
	    other_names++;

	if (*other_names != '\0')
	    *(other_names++) = '\0';

	if (strlen(ptr) > sizeof(linkname) - (2 + LEAF_LEN)) {
	    _nc_warning("terminal alias %s too long.", ptr);
	    continue;
	}
	if (strchr(ptr, '/') != 0) {
	    _nc_warning("cannot link alias %s.", ptr);
	    continue;
	}

	check_writeable(ptr[0]);
	_nc_SPRINTF(linkname, _nc_SLIMIT(sizeof(linkname))
		    LEAF_FMT "/%s", ptr[0], ptr);

	if (strcmp(filename, linkname) == 0) {
	    _nc_warning("self-synonym ignored");
	} else if (stat(linkname, &statbuf) >= 0 &&
		   statbuf.st_mtime < start_time) {
	    _nc_warning("alias %s multiply defined.", ptr);
	} else if (_nc_access(linkname, W_OK) == 0)
#if HAVE_LINK
	{
	    int code;
#if USE_SYMLINKS
	    if (first_name[0] == linkname[0])
		strncpy(symlinkname, first_name, sizeof(symlinkname) - 1);
	    else {
		_nc_STRCPY(symlinkname, "../", sizeof(suymlinkname));
		strncat(symlinkname, filename, sizeof(symlinkname) - 4);
	    }
	    symlinkname[sizeof(symlinkname) - 1] = '\0';
#endif /* USE_SYMLINKS */
#if HAVE_REMOVE
	    code = remove(linkname);
#else
	    code = unlink(linkname);
#endif
	    if (code != 0 && errno == ENOENT)
		code = 0;
#if USE_SYMLINKS
	    if (symlink(symlinkname, linkname) < 0)
#else
	    if (link(filename, linkname) < 0)
#endif /* USE_SYMLINKS */
	    {
		/*
		 * If there wasn't anything there, and we cannot
		 * link to the target because it is the same as the
		 * target, then the source must be on a filesystem
		 * that uses caseless filenames, such as Win32, etc.
		 */
		if (code == 0 && errno == EEXIST)
		    _nc_warning("can't link %s to %s", filename, linkname);
		else if (code == 0 && (errno == EPERM || errno == ENOENT))
		    write_file(linkname, tp);
		else {
#if MIXEDCASE_FILENAMES
		    _nc_syserr_abort("can't link %s to %s", filename, linkname);
#else
		    _nc_warning("can't link %s to %s (errno=%d)", filename,
				linkname, errno);
#endif
		}
	    } else {
		DEBUG(1, ("Linked %s", linkname));
	    }
	}
#else /* just make copies */
	    write_file(linkname, tp);
#endif /* HAVE_LINK */
    }
#endif /* USE_HASHED_DB */
}
main ( )
{
        int i, res;
        char ch;
        char input[30];
        int nbytes;
        uint64_t dev_size;

        printf("Opening /dev/hv_cdev0 file\n");
        fd = open64("/dev/hv_cdev0", O_RDWR);
        if (fd == -1)
        {
                printf("Error in opening file \n");
                return(-1);
        }

        while(1) {
        	print_menu();

        	/* read user input and get rid of CR */
        	scanf ("%s%*c", &ch);
        	printf("Your input = %c\n\n", ch);

        	switch (ch) {
        		case '1':
            		read_file();
                    break;

                case '2':
                	write_file();
                    break;

                case '3':
                	printf("How many bytes to read? ");
                	fgets(input, sizeof(input), stdin);
                	printf("Your input = %d\n", atoi(input));
                	break;

                case '4':
                	printf("How many bytes to write? ");
                	fgets(input, sizeof(input), stdin);
                	printf("Your input = %d\n", atoi(input));
                	break;
                	
                case '6':
                	fflush(NULL); 	
                	mmap_file();
                	break;
                	
                case '7':
                	get_dev_size(&dev_size);
                	printf("mmls size: %llu\n", dev_size);
                	break;
                	
                case 'q':
                	goto exit;

                default:
                    printf("\nWrong choice \n");
                    break;
        	}
        }

 exit:
        close(fd);
        return 0;
}
Exemple #7
0
//-------- Begin of function GameFile::save_game --------//
//
// return : <int> 1 - saved successfully.
//                0 - not saved.
//
int GameFile::save_game(const char* fileName)
{
	char full_path[MAX_PATH+1];
	File   file;
	String errStr;

	power.win_opened=1;				// to disable power.mouse_handler()

	if( fileName )
		strcpy( file_name, fileName );

	int rc = 1;

	if (!misc.path_cat(full_path, sys.dir_config, file_name, MAX_PATH))
	{
		rc = 0;
		errStr = _("Path too long to the saved game");
	}

	if( rc )
	{
		rc = file.file_create(full_path, 0, 1); // 0=tell File don't handle error itself
																   // 1=allow the writing size and the read size to be different
		if( !rc )
			errStr = _("Error creating saved game file.");
	}

	if( rc )
	{
		save_process();      // process game data before saving the game

		rc = write_game_header(&file);    // write saved game header information

		if( !rc )
			errStr = _("Error creating saved game header.");

		if( rc )
		{
			rc = write_file(&file);

			if( !rc )
				errStr = _("Error writing saved game data.");
		}
	}

	file.file_close();

	power.win_opened=0;

	//------- when saving error ---------//

	if( !rc )
	{
		remove( file_name );         // delete the file as it is not complete

		#ifndef DEBUG
			errStr = _("Insufficient disk space ! The game is not saved.");		// use this message for all types of error message in the release version
		#endif

		box.msg( errStr );
	}

	return rc;
}
Exemple #8
0
static void menu(void)
{   int failed = 0, readoption = 1, alwaysstop = 0, showhidden = 0;
    char prmptbuf[80];
    char *tmpstr, *option, *version_id;
    char *terms = " \n";

    strcpy( buffer, schemamenu_init );
    tmpstr = strtok( buffer, " " );
    tmpstr = strtok( NULL, " " );
    tmpstr = strtok( NULL, " " );
    version_id = heapstr( tmpstr );

    while( readoption )
    {  NewScreen();
       failed = 0;

       printf( "%s    Schema Mapping Environment. V%s\n",
               FORMAT_LINE, version_id);
       printf( "%s    ---------------------------------\n\n", FORMAT_LINE);

       printf( "%sl ......... load file [filename [language]]\n",
               FORMAT_LINE);
       printf( "%sb ......... browse\n", FORMAT_LINE);
       printf( "%sudtoum .... UDINST_UMINST mapper\n", FORMAT_LINE);
       printf( "%setov ...... ELLA_VHDL mapper\n", FORMAT_LINE);
       printf( "%setol ...... ELLA_LAYOUT mapper\n", FORMAT_LINE);
       printf( "%svtol ...... VHDL_LAYOUT mapper\n", FORMAT_LINE);
       printf( "%slp ........ LAYOUT_PRINT\n", FORMAT_LINE);
       printf( "%slw ........ LAYOUT_WRITE [filename]\n", FORMAT_LINE);
       printf( "%swpk ....... write packed dump [filename [language]]\n",
               FORMAT_LINE);
       printf( "%swup ....... write unpacked dump [filename [language]]\n",
               FORMAT_LINE);
       printf( "%sq ......... quit\n", FORMAT_LINE);
       if( showhidden )
       {
          printf( "%sids ....... print ids table\n", FORMAT_LINE);
          printf( "%spause ..... toggle the pause state\n", FORMAT_LINE);
          printf( "%shidden .... toggle the hidden state\n", FORMAT_LINE);
          printf( "%sdiag ...... print diagnostics [filename] \n",
                  FORMAT_LINE);

       }

       sprintf( prmptbuf, "\n%s> ", FORMAT_LINE);
       while(( tmpstr = prompt( prmptbuf, buffer )) == NULL ||
               *tmpstr == NULL ){};

       option = strtok( tmpstr, terms );     
       Capitalise( option);

       if( equal(option, "L") )
       {  theclosure = menu_load( strtok( NULL, terms ), strtok( NULL, terms ));
          if( ExternalclosureClosure( theclosure) == NULL ) failed = 1;
       }
       else if ( equal(option, "B") )
       {  failed = menu_browse();
       }
       else if ( equal(option, "WPK") )
       {  failed = menu_write( strtok( NULL, terms ),
                               strtok( NULL, terms ), 1 ); 
       }
       else if ( equal(option, "WUP") )
       {  failed = menu_write( strtok( NULL, terms ),
                               strtok( NULL, terms ), 0 ); 
       }
       else if (equal(option, "UDTOUM"))
       {  Transformer *udinst_uminst;

          imgtable = ELLA_InitTable();
          udinst_uminst=
          Make_udinst_uminst( MakeNullTransformer( objtable, imgtable));
          update_closure( Transform( ExternalclosureClosure( theclosure),
                                      udinst_uminst));
          objtable = imgtable;
       }
       else if (equal(option, "ETOV"))
       {  Transformer *ella_vif;

          imgtable = VIF_InitTable();
          ella_vif = make_ella_vif( MakeNullTransformer( objtable, imgtable));
          update_closure( Transform( ExternalclosureClosure( theclosure),
                                     ella_vif));
          objtable = imgtable;
       }
       else if (equal(option, "ETOL"))
       {  Transformer *ella_layout;

          imgtable = LAY_InitTable();
          ella_layout = 
                   make_ella_layout( MakeNullTransformer( objtable, imgtable));
          update_closure( Transform( ExternalclosureClosure( theclosure),
                                     ella_layout));
               objtable = imgtable;
       }
       else if (equal(option, "VTOL"))
       {  Transformer *vif_layout;

          imgtable = LAY_InitTable();
          vif_layout = 
                   make_vif_layout( MakeNullTransformer( objtable, imgtable));
          update_closure( Transform( ExternalclosureClosure( theclosure),
                                     vif_layout));
          objtable = imgtable;
       }
       else if (equal(option, "LP"))
       {  menu_layout( stdout );
          failed = 1; /* We have not really failed, but need to hold the screen
                      */
       }
       else if (equal(option, "LW"))
       {  failed = write_file( strtok( NULL, terms ));
       }
       else if (equal(option, "Q"))
       {  readoption = 0;
          alwaysstop = 0;
       }
       else if ( equal(option, "IDS") )
       {  print_idstable();
          failed = 1; /* We have not really failed, but need to hold the screen
                      */
       }
       else if ( equal(option, "HIDDEN") )
       {  showhidden = 1 - showhidden;
       }
       else if ( equal(option, "PAUSE") )
       {  alwaysstop = 1 - alwaysstop;
       }
       else if ( equal(option, "DIAG") )
       {  tmpstr = strtok( NULL, terms );
          if( tmpstr == NULL )
          {  assemdiagfile = stdout;
             alwaysstop = 1;
          }
          else
          {  assemdiagfile = fopen( tmpstr, "w" );
          }
       }
       else
       {  printf( "Option %s not recognised.\n", option );
          failed = 1;
       }

       if( failed || alwaysstop )
       {  prompt( "Press RETURN to continue > ", buffer );
       }
    }
}
Exemple #9
0
int
cppath(int a_ctrl, char *a_srcPath, char *a_dstPath, mode_t a_mode)
{
	char		*linknam = (char *)NULL;
	int		dstFd;
	int		len;
	int		srcFd;
	long		status;
	struct stat	srcStatbuf;
	struct utimbuf	times;

	/* entry debugging info */

	echoDebug(DBG_CPPATH_ENTRY, a_ctrl, a_mode, a_srcPath, a_dstPath);

	/* open source file for reading */

	srcFd = open(a_srcPath, O_RDONLY);
	if (srcFd < 0) {
		progerr(ERR_OPEN_READ, a_srcPath,
				errno, strerror(errno));
		return (1);
	}

	/* obtain file status of source file */

	if (fstat(srcFd, &srcStatbuf) != 0) {
		progerr(ERR_FSTAT, srcFd, a_srcPath, errno, strerror(errno));
		(void) close(srcFd);
		return (1);
	}

	/*
	 * Determine the permissions mode for the destination:
	 * - if MODE_SET is specified:
	 * --> use a_mode (do not mask off any portion)
	 * --> If a_mode is unknown (? in the pkgmap), then the file gets
	 * --> installed with the default 0644 mode
	 * - if MODE_SRC is specified:
	 * --> use the mode of the source (srcStatbuf.st_mode) but mask off all
	 * --> non-access mode bits (remove SET?UID bits)
	 * - otherwise:
	 * --> use 0666
	 */

	if (a_ctrl & MODE_SET) {
		mode_t	usemode;

		usemode = (a_mode ^ BADMODE) ? a_mode : 0644;
		if (a_mode != usemode && usemode == 0644) {
			logerr(WRN_DEF_MODE, a_dstPath);
			a_mode = usemode;
		}
	} else if (a_ctrl & MODE_SRC) {
		a_mode = (srcStatbuf.st_mode & S_IAMB);
	} else {
		a_mode = 0666;
	}

	/*
	 * Get fd of newly created destination file or, if this
	 * is an overwrite,  a temporary file (linknam).
	 */

	dstFd = write_file(&linknam, a_ctrl, a_mode, a_dstPath);
	if (dstFd < 0) {
		(void) close(srcFd);
		return (1);
	}

	/*
	 * source and target files are open: copy data
	 */

	status = copyFile(srcFd, dstFd, a_srcPath, a_dstPath, &srcStatbuf, 0);

	(void) close(srcFd);
	(void) close(dstFd);

	if (status != 0) {
		progerr(ERR_INPUT, a_srcPath, errno, strerror(errno));
		if (linknam) {
			(void) remove(linknam);
		}
		return (1);
	}

	/*
	 * If this is an overwrite, rename temp over original
	 */

	if ((linknam != (char *)NULL) && (rename(linknam, a_dstPath) != 0)) {
		FILE	*logfp = (FILE *)NULL;
		char	busylog[PATH_MAX];

		/* output log message if busy else program error */

		if (errno == ETXTBSY) {
			logerr(MSG_PROCMV, linknam);
		} else {
			progerr(ERR_OUTPUT_WRITING, a_dstPath, errno,
				strerror(errno));
		}

		(void) remove(linknam);

		/* open the log file and append log entry */

		len = snprintf(busylog, sizeof (busylog),
				"%s/textbusy", get_PKGADM());
		if (len > sizeof (busylog)) {
			progerr(ERR_CREATE_PATH_2, get_PKGADM(),
				"textbusy");
		} else {
			logfp = fopen(busylog, "a");
			if (logfp == NULL) {
				progerr(ERR_LOG, busylog, errno,
					strerror(errno));
			} else {
				(void) fprintf(logfp, "%s\n", linknam);
				(void) fclose(logfp);
			}
		}
	}

	/* set access/modification times for target */

	times.actime = srcStatbuf.st_atime;
	times.modtime = srcStatbuf.st_mtime;

	if (utime(a_dstPath, &times) != 0) {
		progerr(ERR_MODTIM, a_dstPath, errno, strerror(errno));
		return (1);
	}

	/* success! */

	return (0);
}
void *thread_carol(void *threadid)
{
   int i;
   time_t now;

   printf("Thread Handling Carol Machines Created\n");
   while(1){
	sleep(20);
	//printf("thread sleep\n");

for(i = 0; i < 9; i++){
		
		// if we dont want to test this device we jump to the next one
		if(test_carol[i] != 1){
			continue;
		}
		if(carol_reboot_count[i]>10){
			test_carol[i]=0;
			write_file("Tired of rebooting carol ",i);
		}

		time(&now);
		if(carol[i] != NULL){
			//printf("carol[%d] != NULL\n", i);
			if(difftime(now, carol[i]) > MAX_TIME){
				carol_reboot_count[i]++;
				printf("\n\n\e[31mreboot carol%d\n",i);
				printf("\e[0m");
				write_file("Reboot carol", i);
				if(i == 0){ //carolxeon1
					system(CAROLXEON1_SW_OFF);
					sleep(20);
					system(CAROLXEON1_SW_ON);
				}
				if(i == 1){ //carolxeon2
					system(CAROLXEON2_SW_OFF);
					sleep(20);
					system(CAROLXEON2_SW_ON);
				}
				if(i == 2){ //carolk20
					system(CAROLK20_SW_OFF);
					sleep(20);
					system(CAROLK20_SW_ON);
				}
				if(i == 3){ //carolk40
					system(CAROLK40_SW_OFF);
					sleep(20);
					system(CAROLK40_SW_ON);
				}
				if(i == 4){ //carolapu1
					system(CAROLAPU1_SW_OFF);
					sleep(20);
					system(CAROLAPU1_SW_ON);
				}
				if(i == 5){ //carolapu2
					system(CAROLAPU2_SW_OFF);
					sleep(20);
					system(CAROLAPU2_SW_ON);
				}
				if(i == 6){ //carolk1a
					system(CAROLK1A_SW_OFF);
					system(FPGA_SW_OFF);
					sleep(20);
					system(CAROLK1A_SW_ON);
					system(FPGA_SW_ON);
				}
				if(i == 7){ //carolk1b
					system(CAROLK1B_SW_OFF);
					system(FPGA_SW_OFF);
					sleep(20);
					system(CAROLK1B_SW_ON);
					system(FPGA_SW_ON);
				}
				if(i == 8){ //carolk1c
					system(CAROLK1C_SW_OFF);
					system(FPGA_SW_OFF);
					sleep(20);
					system(CAROLK1C_SW_ON);
					system(FPGA_SW_ON);
				}
/*
				if(i == 0){//carol1
					system(CAROL1_SW_OFF);
					sleep(20);
					system(CAROL1_SW_ON);
				}
				if(i == 1){//carol3
					system(CAROL3_SW_OFF);
					sleep(20);
					system(CAROL3_SW_ON);
				}
				if(i == 2){//carolAPU1
					system(CAROLAPU1_SW_OFF);
					sleep(20);
					system(CAROLAPU1_SW_ON);
				}
*/

				carol[i] = NULL;
			}
		}
		if( difftime(now, last_conn[i]) > MAX_TIME_LAST_CONN ){
			carol_reboot_count[i]++;
			printf("\n\n\e[31mboot problem for carolID=%d\n",i);
			printf("\e[0m");
			write_file("Boot problem for carol", i);
			if(i == 0){ //carolxeon1
				system(CAROLXEON1_SW_OFF);
				sleep(20);
				system(CAROLXEON1_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 1){ //carolxeon2
				system(CAROLXEON2_SW_OFF);
				sleep(20);
				system(CAROLXEON2_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 2){ //carolk20
				system(CAROLK20_SW_OFF);
				sleep(20);
				system(CAROLK20_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 3){ //carolk40
				system(CAROLK40_SW_OFF);
				sleep(20);
				system(CAROLK40_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 4){ //carolapu1
				system(CAROLAPU1_SW_OFF);
				sleep(20);
				system(CAROLAPU1_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 5){ //carolapu2
				system(CAROLAPU2_SW_OFF);
				sleep(20);
				system(CAROLAPU2_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 6){ //carolk1a
				system(CAROLK1A_SW_OFF);
				system(FPGA_SW_OFF);
				sleep(20);
				system(CAROLK1A_SW_ON);
				system(FPGA_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 7){ //carolk1b
				system(CAROLK1B_SW_OFF);
				system(FPGA_SW_OFF);
				sleep(20);
				system(CAROLK1B_SW_ON);
				system(FPGA_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 8){ //carolk1c
				system(CAROLK1C_SW_OFF);
				system(FPGA_SW_OFF);
				sleep(20);
				system(CAROLK1C_SW_ON);
				system(FPGA_SW_ON);
				time(&last_conn[i]);
			}
/*
			if(i == 0){//carol1
				system(CAROL1_SW_OFF);
				sleep(20);
				system(CAROL1_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 1){//carol3
				system(CAROL3_SW_OFF);
				sleep(20);
				system(CAROL3_SW_ON);
				time(&last_conn[i]);
			}
			if(i == 2){//carol3
				system(CAROLAPU1_SW_OFF);
				sleep(20);
				system(CAROLAPU1_SW_ON);
				time(&last_conn[i]);
			}
*/

			carol[i] = NULL;
		}
	}
Exemple #11
0
void reload(GLOBAL *g, struct dns_module *dns)
{
    char *configfile = 0;
    char *configentries = strdup("");
    QueryHandle *res, *res1;
    int i, j, m, k=2, gc=0, nc=0, nh=0, dc=0, n=2;
    struct hostcache
    {
        char *name;
        unsigned long ipaddr;
    } *hosts = NULL;

    char **domains = (char **) malloc(sizeof(char*));

    struct net *nets = (struct net *) malloc(sizeof(struct net));
    char *netnames = strdup(dns->networks);
    char *netname = strdup(netnames);

    struct group *ugps = (struct group *) malloc(sizeof(struct group));
    char *groupnames = strdup(dns->customergroups);
    char *groupname = strdup(groupnames);

    while (n>1) {
        n = sscanf(netnames, "%s %[._a-zA-Z0-9- ]", netname, netnames);

        if (strlen(netname)) {
            res = g->db_pquery(g->conn, "SELECT name, address FROM networks WHERE UPPER(name)=UPPER('?')",netname);
            if (g->db_nrows(res)) {
                nets = (struct net *) realloc(nets, (sizeof(struct net) * (nc+1)));
                nets[nc].name = strdup(g->db_get_data(res,0,"name"));
                nets[nc].address = inet_addr(g->db_get_data(res,0,"address"));
                nc++;
            }
            g->db_free(&res);
        }
    }
    free(netname); free(netnames);

    while (k>1) {
        k = sscanf(groupnames, "%s %[._a-zA-Z0-9- ]", groupname, groupnames);

        if (strlen(groupname)) {
            res = g->db_pquery(g->conn, "SELECT name, id FROM customergroups WHERE UPPER(name)=UPPER('?')",groupname);

            if (g->db_nrows(res)) {
                ugps = (struct group *) realloc(ugps, (sizeof(struct group) * (gc+1)));
                ugps[gc].name = strdup(g->db_get_data(res,0,"name"));
                ugps[gc].id = atoi(g->db_get_data(res,0,"id"));
                gc++;
            }
            g->db_free(&res);
        }
    }
    free(groupname); free(groupnames);

    res = g->db_query(g->conn, "SELECT LOWER(name) AS name, ipaddr, ipaddr_pub, ownerid FROM nodes ORDER BY ipaddr");

    for (i=0; i<g->db_nrows(res); i++) {
        int ownerid      = atoi(g->db_get_data(res,i,"ownerid"));
        char *name       = g->db_get_data(res,i,"name");
        char *ipaddr     = g->db_get_data(res,i,"ipaddr");
        char *ipaddr_pub = g->db_get_data(res,i,"ipaddr_pub");

        // groups test
        if (gc) {
            if (!ownerid)
                continue;
            m = gc;
            res1 = g->db_pquery(g->conn, "SELECT customergroupid FROM customerassignments WHERE customerid=?", g->db_get_data(res,i,"ownerid"));
            for (k=0; k<g->db_nrows(res1); k++) {
                int groupid = atoi(g->db_get_data(res1, k, "customergroupid"));
                for(m=0; m<gc; m++)
                    if(ugps[m].id==groupid)
                        break;
                if(m!=gc) break;
            }
            g->db_free(&res1);
            if (m==gc)
                continue;
        }

        hosts = (struct hostcache*) realloc(hosts, sizeof(struct hostcache) * (nh + 1));
        hosts[nh].name = strdup(name);
        hosts[nh].ipaddr = inet_addr(ipaddr);
        nh++;

        if (ipaddr_pub) {
            hosts = (struct hostcache*) realloc(hosts, sizeof(struct hostcache) * (nh + 1));
            hosts[nh].name = strdup(name);
            hosts[nh].ipaddr = inet_addr(ipaddr_pub);
            nh++;
        }
    }
    g->db_free(&res);

    res = g->db_query(g->conn, "SELECT inet_ntoa(address) AS address, mask, domain, dns "
        "FROM networks WHERE domain <> ''");

    if (g->db_nrows(res)) {
        // Load main config file pattern
        configfile = load_file(dns->confpattern);

        for (i=0; i<g->db_nrows(res); i++) {
            int domainmatch  = 0;
            int reversematch = 0;

            char *e       = g->db_get_data(res,i,"address");
            char *d       = g->db_get_data(res,i,"mask");
            char *name    = g->db_get_data(res,i,"domain");
            char *dnsserv = g->db_get_data(res,i,"dns");

            unsigned long network = inet_addr(e);
            unsigned long netmask = inet_addr(d);

            // networks test
            if(nc) {
                for(j=0; j<nc; j++)
                    if(nets[j].address==network)
                        break;
                if(j==nc)
                    continue;
            }

            int prefixlen = 1; // in bytes!
            char *finfile, *ftmpfile;
            char *rinfile, *rtmpfile;
            char *forwardzone;
            char *reversezone;
            char *forwardhosts = strdup("");
            char *reversehosts = strdup("");
            char netpart[30];

            unsigned long ip = ntohl(network);
            unsigned long host_netmask = ntohl(netmask);

            if (host_netmask & 0x0001ffff) prefixlen = 2;
            if (host_netmask & 0x000001ff) prefixlen = 3;

            // Set netpart string for reverse zone
            switch (prefixlen) {
                case 1:
                    snprintf(netpart, 30, "%d", (int)((ip >> 24) & 0xff));
                    break;
                case 2:
                    snprintf(netpart, 30, "%d.%d", (int)((ip >> 16) & 0xff),(int)((ip >> 24) & 0xff));
                    break;
                case 3:
                default:
                    snprintf(netpart, 30, "%d.%d.%d", (int)((ip >> 8) & 0xff),(int)((ip >> 16) & 0xff),(int)((ip >> 24) & 0xff));
                    break;
            }

            // check if domain was processed yet
            for (j=0; j<dc; j++)
                if (strcmp(name, domains[j])==0) {
                    domainmatch = 1;
                    break;
                }

            if (!domainmatch) {
                // add domain to table
                dc++;
                domains = realloc(domains, sizeof(char*) * dc);
                domains[dc - 1] = strdup(name);

                finfile = dns->fpatterns;
            }
            else {
                finfile = dns->fzones;
            }

            // check if reverse-domain was processed yet
            for (j=0; j<dc; j++)
                if (strcmp(netpart, domains[j])==0) {
                    reversematch = 1;
                    break;
                }

            if (!reversematch) {
                // add domain to table
                dc++;
                domains = realloc(domains, sizeof(char*) * dc);
                domains[dc - 1] = strdup(netpart);

                rinfile = dns->rpatterns;
            }
            else {
                rinfile = dns->rzones;
            }

            // Create paths to zone patterns
            if (finfile[strlen(finfile) - 1] != '/')
                ftmpfile = g->str_concat(finfile, "/");
            else
                ftmpfile = strdup(finfile);

            if (rinfile[strlen(rinfile) - 1] != '/')
                rtmpfile = g->str_concat(rinfile, "/");
            else
                rtmpfile = strdup(rinfile);

            finfile = g->str_concat(ftmpfile, name);
            rinfile = g->str_concat(rtmpfile, netpart);

            // Load pattern files
            forwardzone = load_file(finfile);
            reversezone = load_file(rinfile);

            if (!forwardzone) forwardzone = load_file(dns->fgeneric);
            if (!reversezone) reversezone = load_file(dns->rgeneric);

            free(finfile);
            free(rinfile);
            free(ftmpfile);
            free(rtmpfile);

            // Patterns loaded, loop over hosts
            if (forwardzone && reversezone) {
                char serial[12];

                for (j=0; j<nh; j++) {
                    if ((hosts[j].ipaddr & netmask) == network) {
                        char hostpart[30];
                        char *tmphosts;

                        char *forwardhost = strdup(dns->forward);
                        char *reversehost = strdup(dns->reverse);

                        g->str_replace(&forwardhost, "%n", hosts[j].name);
                        g->str_replace(&reversehost, "%n", hosts[j].name);
                        g->str_replace(&forwardhost, "%i", inet_ntoa(hosts[j].ipaddr));
                        g->str_replace(&reversehost, "%i", inet_ntoa(hosts[j].ipaddr));
                        g->str_replace(&forwardhost, "%d", name);
                        g->str_replace(&reversehost, "%d", name);

                        ip = ntohl(hosts[j].ipaddr);

                        switch (prefixlen) {
                            case 1:
                                snprintf(hostpart, 30, "%d.%d.%d", (int)(ip & 0xff),(int)((ip >> 8) & 0xff),(int)((ip >> 24) & 0xff));
                                break;
                            case 2:
                                snprintf(hostpart, 30, "%d.%d", (int)(ip & 0xff),(int)((ip >> 8) & 0xff));
                                break;
                            case 3:
                            default:
                                snprintf(hostpart, 30, "%d", (int)(ip & 0xff));
                                break;
                        }

                        g->str_replace(&forwardhost, "%c", hostpart);
                        g->str_replace(&reversehost, "%c", hostpart);

                        tmphosts = strdup(forwardhosts);
                        free(forwardhosts);
                        forwardhosts = g->str_concat(tmphosts, forwardhost);
                        free(tmphosts);

                        tmphosts = strdup(reversehosts);
                        free(reversehosts);
                        reversehosts = g->str_concat(tmphosts, reversehost);
                        free(tmphosts);

                        free(forwardhost);
                        free(reversehost);
                    }
                }

                // Add hosts to zone file
                if (domainmatch) {
                    // Add existing domain content
                    char *tmphosts = strdup(forwardzone);
                    g->str_replace(&tmphosts, "%h", "");
                    free(forwardzone);
                    forwardzone = g->str_concat(tmphosts, forwardhosts);
                    free(tmphosts);
                }
                else {
                    g->str_replace(&forwardzone, "%h", forwardhosts);
                }

                // Add hosts to reverse-zone file
                if (reversematch) {
                    // Add existing domain content
                    char *tmphosts = strdup(reversezone);
                    g->str_replace(&tmphosts, "%h", "");
                    free(reversezone);
                    reversezone = g->str_concat(tmphosts, reversehosts);
                    free(tmphosts);
                }
                else {
                    g->str_replace(&reversezone, "%h", reversehosts);
                }

                free(forwardhosts);
                free(reversehosts);

                g->str_replace(&forwardzone, "%d", name);
                g->str_replace(&reversezone, "%d", name);

                snprintf(serial, 12, "%d", (int) time(NULL));

                g->str_replace(&forwardzone, "%s", serial);
                g->str_replace(&reversezone, "%s", serial);

                g->str_replace(&forwardzone, "%c", netpart);
                g->str_replace(&reversezone, "%c", netpart);

                g->str_replace(&forwardzone, "%v", dnsserv ? (dnsserv) : ((char*) "127.0.0.1"));
                g->str_replace(&reversezone, "%v", dnsserv ? (dnsserv) : ((char*) "127.0.0.1"));

                // Set output files paths
                finfile = dns->fzones;
                rinfile = dns->rzones;

                if (finfile[strlen(finfile) - 1] != '/')
                    ftmpfile = g->str_concat(finfile, "/");
                else
                    ftmpfile = finfile;

                if (rinfile[strlen(rinfile) - 1] != '/')
                    rtmpfile = g->str_concat(rinfile, "/");
                else
                    rtmpfile = rinfile;

                finfile = g->str_concat(ftmpfile, name);
                rinfile = g->str_concat(rtmpfile, netpart);

                // Write to output files
                if (write_file(finfile, forwardzone) < 0) {
                    syslog(LOG_WARNING, "[%s/dns] Unable to open output forward zone file '%s' for domain '%s', skipping forward zone for this domain.", dns->base.instance, finfile, name);
                }
                else if (!domainmatch) {
                    char *zone, *tmpconf;
                    zone = strdup(dns->confforward);
                    g->str_replace(&zone, "%n", name);
                    g->str_replace(&zone, "%c", netpart);
                    g->str_replace(&zone, "%i", inet_ntoa(network));
                    tmpconf = strdup(configentries);
                    free(configentries);
                    configentries = g->str_concat(tmpconf, zone);
                    free(tmpconf);
                    free(zone);
                }

                if (write_file(rinfile, reversezone) < 0)
                {
                    syslog(LOG_WARNING, "[%s/dns] Unable to open output reverse zone file '%s' for domain '%s', skipping reverse zone for this domain.", dns->base.instance, rinfile, name);
                }
                else if (!reversematch) {
                    char *zone, *tmpconf;
                    zone = strdup(dns->confreverse);
                    g->str_replace(&zone, "%n", name);
                    g->str_replace(&zone, "%c", netpart);
                    // Don't support %i here, it will break bind config if you have
                    // many networks with small mask that are subclasses of bigger one
                    // e.g. 192.168.0.0/27 and 192.168.0.32/27
                    // g->str_replace(&zone, "%i", inet_ntoa(network));
                    g->str_replace(&zone, "%i", netpart);
                    tmpconf = strdup(configentries);
                    free(configentries);
                    configentries = g->str_concat(tmpconf, zone);
                    free(tmpconf);
                    free(zone);
                }

                free(rtmpfile);
                free(ftmpfile);
                free(finfile);
                free(rinfile);
                free(forwardzone);
                free(reversezone);
            }
Exemple #12
0
int
main(int argc, char* argv[]) {
	/*init of all tabs and vars*/
	char* alphabet = "abcdefghijklmnopqrstuvwxyz";
	char* clef     = "notaverysmartkey";
	char* tab;
	int taillalpha = 26;
	int tailletab;
	int tailleclef;
	int* iclef;
	int* itab;
	Boolean casetwo      = FALSE;
	Boolean unknown_char = FALSE;

	/*test options */
	int c;

	while(1) {
		int option_index                    = 0;
		static struct option long_options[] = {{"alphabet", required_argument, 0, 'a'},
		                                       {"help", no_argument, 0, 'h'},
		                                       {"skip", no_argument, 0, 's'},
		                                       {"key", required_argument, 0, 'k'}};

		c = getopt_long(argc, argv, "a:hk:s", long_options, &option_index);
		if(c == -1) {
			break;
		}

		switch(c) {

			case 'a':
				printf("option a with value of '%s'\n", optarg);
				alphabet = file_to_string(optarg);
				break;

			case 'h':
				print_man(TRUE);
				return 0;
				break;

			case 's':
				printf("option c with value of '%s'\n", optarg);
				unknown_char = TRUE;
				break;

			case 'k':
				printf("option d with value '%s'\n", optarg);
				clef = file_to_string(optarg);
				break;

			default:
				printf("?? getopt returned character code 0%o ??\n", c);
				return 1;
				break;
		}
	}

	/*test args*/

	switch(argc - optind) {
		case 0:
			/*in no argument read tab from keyboard*/
			printf("pas d'argument entrer une chaine\n");
			tab = calloc(100, sizeof(char));
			fgets(tab, 99, stdin);
			break;
		case 1:
			/* if one argument then read file and put it in tab*/
			printf("arg 1 %s\n", argv[optind]);
			tab = file_to_string(argv[optind]);
			printf("tableau lue dans %s = %s\n", argv[optind], tab);
			break;
		case 2:
			/*if 2 argumpent read file an put it in tab then set casetow to true*/
			printf("arg2 %s\n", argv[optind - 1]);
			casetwo = TRUE;
			tab     = file_to_string(argv[optind]);
			break;
		default:
			print_man(TRUE);
			return 1;
			break;
	}

	if(unknown_char == TRUE) {
		/* remove uknow char if -s */
		printf("remove unknown char\n");
		rm_unknown_char(tab, alphabet);
	}

	tailletab  = strlen(tab);
	tailleclef = strlen(clef);
	taillalpha = strlen(alphabet);
	itab       = malloc(tailletab * sizeof(int));
	iclef      = malloc(tailleclef * sizeof(int));

	printf("taille clef %d\n", tailleclef);

	/*convert tab and key to int tab*/
	string_to_int(tab, alphabet, itab);
	string_to_int(clef, alphabet, iclef);

	/*test invalid char in the key*/
	testclef(iclef, tailleclef);

	/*decod tab with the key, minus done with a pointer to the fuction*/
	codclef(iclef, itab, tailletab, tailleclef, taillalpha, &addition);

	/*convert the final int tab to a char tab*/
	int_to_alpha(itab, tab, alphabet, tailletab);

	/*if a dest file have been specified write the result into the file elese print the result */
	if(casetwo == FALSE) {
		printf("message final: %s\n", tab);
	} else {
		/*argv[optind+1] = file name*/
		printf("ecriture de %s dans %s\n", tab, argv[optind + 1]);
		write_file(argv[optind + 1], tab);
	}

	/*free all alocations*/
	free(itab);
	free(iclef);
	free(tab);
	return 0;
}
Exemple #13
0
 inline void write_file(
     const std::string& path,
     const std::vector<unsigned char>& src)
 {
     write_file(path, src.data(), src.size());
 }
Exemple #14
0
void GetReplyFromJJ(char *InputText, int nMode, JJGui *jibber_ui)
{
	static char szUserInput[512], szLastInput[ 512 ];
	char *cPtr, szSeps[]=" \n";
	int  i, nResponse, nKeyWordGroup = 0, nTailOffset = 0, nCommand = (-1);

	// take a working copy of the string
	strcpy(szUserInput, InputText );

	// get the first word of the user input
	cPtr = strtok(InputText, szSeps);

	if (cPtr != NULL) {

		// see if the first word is in the list of known commands
		for (i=0; dCommands[i].Command != NULL; i++) {

			// check abbreviations and full command names
			if ((strcmp(dCommands[i].Abbrev, cPtr) == 0 ) || (strcmp(dCommands[i].Command, cPtr) == 0 )) {
				// a command has been found - get its number
				nCommand = dCommands[i].nCommand;
				break;
			}
		}

		// according to the number of the found command, do something
		if ( nCommand >= 0 ) {

			switch (nCommand) {
				// is it a command string?
				case COMMAND_TRON:
					// turn on the system trace function
					bShow = true;
					AppendText(jibber_ui, DIR_SYSTEM, "Process trace ON");
					break;

				case COMMAND_TROFF:
					// turn off the system trace function
					bShow = false;
					AppendText(jibber_ui, DIR_SYSTEM, "Process trace OFF");
					break;

				case COMMAND_SAVE:
					// save the conversation to a file
					write_file(jibber_ui);
					break;

				case COMMAND_TOPICS:
					// show the topics used so far in the current conversation
					DoListWalk(jibber_ui);
					break;

				case COMMAND_QUIT:
				case COMMAND_EXIT:
					// leave the program
					gtk_widget_destroy(jibber_ui->window);
					break;

				case COMMAND_HELP:
				case COMMAND_ABOUT:
					// display a help text
					AppendText(jibber_ui, DIR_SYSTEM, "Jibber Jabber %s :: Compiled on %s at %s.", JJ_VERSION, __DATE__, __TIME__);
					AppendText(jibber_ui, DIR_BLANK, "" );

					for (i=0; dCommands[i].Command != NULL; i++)
							AppendText(jibber_ui, DIR_SYSTEM, "%-10s - %s", dCommands[i].Help1, dCommands[i].Help2);

					AppendText(jibber_ui, DIR_BLANK, "" );
					break;

				// unknown command - do nothing
				default : break;
			}

			// we have executed a command, no further processing required
			return;
		}
	}

	if (nMode == NORMAL_MODE)
			AppendText(jibber_ui, DIR_IN, szUserInput);

	// force user input to uppercase
	SetToUppercase( szUserInput );

	// no user entry - pick a null input response
	if ( strlen( szUserInput ) == 0 )
			nKeyWordGroup = GetGroupFromTriggerPhrase("JJNULLINPUT", jibber_ui);

	// same user input as last time - pick a repeat response
	else if ( strcmp( szUserInput, szLastInput ) == 0 )
			nKeyWordGroup = GetGroupFromTriggerPhrase("JJREPEATEDINPUT", jibber_ui);

	// check it for keywords
	else {
		// take a copy for next time
		strcpy(szLastInput, szUserInput);

		// determine the keyword group from the content of the user entry
		nKeyWordGroup = GetKeyWordGroup( szUserInput, &nTailOffset, jibber_ui );
	}

	// did we find a keyword group? If we didn't, do further processing
	if ( !nKeyWordGroup ) {

		if ( Root != NULL ) {

			if ( bShow ) {

				AppendText(jibber_ui, DIR_SYSTEM, "Re-using previous seed statement: %s", End->UserInput);
			}

			//
			// also needs to be able to choose a new topic
			// instead of battering away at one recent topic
			//

			// re-use the last topic group
			GetReplyFromJJ(End->UserInput, SILENT_MODE, jibber_ui);
		}
		else {

			// if there is nothing to refer back to use a non-specific response
			nKeyWordGroup = GetGroupFromTriggerPhrase("JJNONSPECIFIC", jibber_ui);
		}
	}

	if ( !nKeyWordGroup )
			return;

	AppendText(jibber_ui, DIR_SYSTEM, "group: %d", nKeyWordGroup);

	// Check whether it is one of the specially handled categories, requiring
	// specific processing. If it is, deal with it. If not, handle it as normal
	nResponse = CheckForProcessedCategories( nKeyWordGroup );

	// get response from this keyword group
	if ( !nResponse )
			GetResponseFromGroup( nKeyWordGroup, szUserInput, nTailOffset, jibber_ui );
	else
			GetResponseFromProcessGroup( nKeyWordGroup, szUserInput, jibber_ui );

}	// end of GetReplyFromJJ
Exemple #15
0
void config_cache::read_cache(const std::string& file_path, config& cfg)
{
	static const std::string extension = ".gz";

	std::stringstream defines_string;
	defines_string << file_path;

	bool is_valid = true;

	for(const preproc_map::value_type& d : defines_map_) {
		//
		// Only WESNOTH_VERSION is allowed to be non-empty.
		//
		if((!d.second.value.empty() || !d.second.arguments.empty()) &&
		   d.first != "WESNOTH_VERSION")
		{
			is_valid = false;
			ERR_CACHE << "Invalid preprocessor define: " << d.first << '\n';
			break;
		}

		defines_string << " " << d.first;
	}

	// Do cache check only if define map is valid and
	// caching is allowed.
	const std::string& cache_path = filesystem::get_cache_dir();

	if(is_valid && !cache_path.empty()) {
		// Use a hash for a shorter display of the defines.
		const std::string fname = cache_path + "/" +
								  cache_file_prefix_ +
								  sha1_hash(defines_string.str()).display();
		const std::string fname_checksum = fname + ".checksum" + extension;

		filesystem::file_tree_checksum dir_checksum;

		if(!force_valid_cache_ && !fake_invalid_cache_) {
			try {
				if(filesystem::file_exists(fname_checksum)) {
					config checksum_cfg;

					DBG_CACHE << "Reading checksum: " << fname_checksum << "\n";
					read_file(fname_checksum, checksum_cfg);

					dir_checksum = filesystem::file_tree_checksum(checksum_cfg);
				}
			} catch(config::error&) {
				ERR_CACHE << "cache checksum is corrupt" << std::endl;
			} catch(filesystem::io_exception&) {
				ERR_CACHE << "error reading cache checksum" << std::endl;
			}
		}

		if(force_valid_cache_) {
			LOG_CACHE << "skipping cache validation (forced)\n";
		}

		if(filesystem::file_exists(fname + extension) && (force_valid_cache_ || (dir_checksum == filesystem::data_tree_checksum()))) {
			LOG_CACHE << "found valid cache at '" << fname << extension << "' with defines_map " << defines_string.str() << "\n";
			log_scope("read cache");

			try {
				read_file(fname + extension,cfg);
				const std::string define_file = fname + ".define" + extension;

				if(filesystem::file_exists(define_file)) {
					config_cache_transaction::instance().add_define_file(define_file);
				}

				return;
			} catch(config::error& e) {
				ERR_CACHE << "cache " << fname << extension << " is corrupt. Loading from files: "<< e.message << std::endl;
			} catch(filesystem::io_exception&) {
				ERR_CACHE << "error reading cache " << fname << extension << ". Loading from files" << std::endl;
			} catch (boost::iostreams::gzip_error& e) {
				//read_file -> ... -> read_gz can throw this exception.
				ERR_CACHE << "cache " << fname << extension << " is corrupt. Error code: " << e.error() << std::endl;
			}
		}

		LOG_CACHE << "no valid cache found. Writing cache to '" << fname << extension << " with defines_map "<< defines_string.str() << "'\n";

		// Now we need queued defines so read them to memory
		read_defines_queue();

		preproc_map copy_map(make_copy_map());

		read_configs(file_path, cfg, copy_map);
		add_defines_map_diff(copy_map);

		try {
			write_file(fname + extension, cfg);
			write_file(fname + ".define" + extension, copy_map);

			config checksum_cfg;

			filesystem::data_tree_checksum().write(checksum_cfg);
			write_file(fname_checksum, checksum_cfg);
		} catch(filesystem::io_exception&) {
			ERR_CACHE << "could not write to cache '" << fname << "'" << std::endl;
		}

		return;
	}

	LOG_CACHE << "Loading plain config instead of cache\n";

	preproc_map copy_map(make_copy_map());
	read_configs(file_path, cfg, copy_map);
	add_defines_map_diff(copy_map);
}
Exemple #16
0
static int run_dir_diff(const char *extcmd, int symlinks, const char *prefix,
                        int argc, const char **argv)
{
    char tmpdir[PATH_MAX];
    struct strbuf info = STRBUF_INIT, lpath = STRBUF_INIT;
    struct strbuf rpath = STRBUF_INIT, buf = STRBUF_INIT;
    struct strbuf ldir = STRBUF_INIT, rdir = STRBUF_INIT;
    struct strbuf wtdir = STRBUF_INIT;
    size_t ldir_len, rdir_len, wtdir_len;
    struct cache_entry *ce = xcalloc(1, sizeof(ce) + PATH_MAX + 1);
    const char *workdir, *tmp;
    int ret = 0, i;
    FILE *fp;
    struct hashmap working_tree_dups, submodules, symlinks2;
    struct hashmap_iter iter;
    struct pair_entry *entry;
    enum object_type type;
    unsigned long size;
    struct index_state wtindex;
    struct checkout lstate, rstate;
    int rc, flags = RUN_GIT_CMD, err = 0;
    struct child_process child = CHILD_PROCESS_INIT;
    const char *helper_argv[] = { "difftool--helper", NULL, NULL, NULL };
    struct hashmap wt_modified, tmp_modified;
    int indices_loaded = 0;

    workdir = get_git_work_tree();

    /* Setup temp directories */
    tmp = getenv("TMPDIR");
    xsnprintf(tmpdir, sizeof(tmpdir), "%s/git-difftool.XXXXXX", tmp ? tmp : "/tmp");
    if (!mkdtemp(tmpdir))
        return error("could not create '%s'", tmpdir);
    strbuf_addf(&ldir, "%s/left/", tmpdir);
    strbuf_addf(&rdir, "%s/right/", tmpdir);
    strbuf_addstr(&wtdir, workdir);
    if (!wtdir.len || !is_dir_sep(wtdir.buf[wtdir.len - 1]))
        strbuf_addch(&wtdir, '/');
    mkdir(ldir.buf, 0700);
    mkdir(rdir.buf, 0700);

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

    memset(&lstate, 0, sizeof(lstate));
    lstate.base_dir = ldir.buf;
    lstate.base_dir_len = ldir.len;
    lstate.force = 1;
    memset(&rstate, 0, sizeof(rstate));
    rstate.base_dir = rdir.buf;
    rstate.base_dir_len = rdir.len;
    rstate.force = 1;

    ldir_len = ldir.len;
    rdir_len = rdir.len;
    wtdir_len = wtdir.len;

    hashmap_init(&working_tree_dups,
                 (hashmap_cmp_fn)working_tree_entry_cmp, 0);
    hashmap_init(&submodules, (hashmap_cmp_fn)pair_cmp, 0);
    hashmap_init(&symlinks2, (hashmap_cmp_fn)pair_cmp, 0);

    child.no_stdin = 1;
    child.git_cmd = 1;
    child.use_shell = 0;
    child.clean_on_exit = 1;
    child.dir = prefix;
    child.out = -1;
    argv_array_pushl(&child.args, "diff", "--raw", "--no-abbrev", "-z",
                     NULL);
    for (i = 0; i < argc; i++)
        argv_array_push(&child.args, argv[i]);
    if (start_command(&child))
        die("could not obtain raw diff");
    fp = xfdopen(child.out, "r");

    /* Build index info for left and right sides of the diff */
    i = 0;
    while (!strbuf_getline_nul(&info, fp)) {
        int lmode, rmode;
        struct object_id loid, roid;
        char status;
        const char *src_path, *dst_path;
        size_t src_path_len, dst_path_len;

        if (starts_with(info.buf, "::"))
            die(N_("combined diff formats('-c' and '--cc') are "
                   "not supported in\n"
                   "directory diff mode('-d' and '--dir-diff')."));

        if (parse_index_info(info.buf, &lmode, &rmode, &loid, &roid,
                             &status))
            break;
        if (strbuf_getline_nul(&lpath, fp))
            break;
        src_path = lpath.buf;
        src_path_len = lpath.len;

        i++;
        if (status != 'C' && status != 'R') {
            dst_path = src_path;
            dst_path_len = src_path_len;
        } else {
            if (strbuf_getline_nul(&rpath, fp))
                break;
            dst_path = rpath.buf;
            dst_path_len = rpath.len;
        }

        if (S_ISGITLINK(lmode) || S_ISGITLINK(rmode)) {
            strbuf_reset(&buf);
            strbuf_addf(&buf, "Subproject commit %s",
                        oid_to_hex(&loid));
            add_left_or_right(&submodules, src_path, buf.buf, 0);
            strbuf_reset(&buf);
            strbuf_addf(&buf, "Subproject commit %s",
                        oid_to_hex(&roid));
            if (!oidcmp(&loid, &roid))
                strbuf_addstr(&buf, "-dirty");
            add_left_or_right(&submodules, dst_path, buf.buf, 1);
            continue;
        }

        if (S_ISLNK(lmode)) {
            char *content = read_sha1_file(loid.hash, &type, &size);
            add_left_or_right(&symlinks2, src_path, content, 0);
            free(content);
        }

        if (S_ISLNK(rmode)) {
            char *content = read_sha1_file(roid.hash, &type, &size);
            add_left_or_right(&symlinks2, dst_path, content, 1);
            free(content);
        }

        if (lmode && status != 'C') {
            ce->ce_mode = lmode;
            oidcpy(&ce->oid, &loid);
            strcpy(ce->name, src_path);
            ce->ce_namelen = src_path_len;
            if (checkout_entry(ce, &lstate, NULL))
                return error("could not write '%s'", src_path);
        }

        if (rmode) {
            struct working_tree_entry *entry;

            /* Avoid duplicate working_tree entries */
            FLEX_ALLOC_STR(entry, path, dst_path);
            hashmap_entry_init(entry, strhash(dst_path));
            if (hashmap_get(&working_tree_dups, entry, NULL)) {
                free(entry);
                continue;
            }
            hashmap_add(&working_tree_dups, entry);

            if (!use_wt_file(workdir, dst_path, &roid)) {
                ce->ce_mode = rmode;
                oidcpy(&ce->oid, &roid);
                strcpy(ce->name, dst_path);
                ce->ce_namelen = dst_path_len;
                if (checkout_entry(ce, &rstate, NULL))
                    return error("could not write '%s'",
                                 dst_path);
            } else if (!is_null_oid(&roid)) {
                /*
                 * Changes in the working tree need special
                 * treatment since they are not part of the
                 * index.
                 */
                struct cache_entry *ce2 =
                    make_cache_entry(rmode, roid.hash,
                                     dst_path, 0, 0);
                ce_mode_from_stat(ce2, rmode);

                add_index_entry(&wtindex, ce2,
                                ADD_CACHE_JUST_APPEND);

                add_path(&wtdir, wtdir_len, dst_path);
                add_path(&rdir, rdir_len, dst_path);
                if (ensure_leading_directories(rdir.buf))
                    return error("could not create "
                                 "directory for '%s'",
                                 dst_path);
                if (symlinks) {
                    if (symlink(wtdir.buf, rdir.buf)) {
                        ret = error_errno("could not symlink '%s' to '%s'", wtdir.buf, rdir.buf);
                        goto finish;
                    }
                } else {
                    struct stat st;
                    if (stat(wtdir.buf, &st))
                        st.st_mode = 0644;
                    if (copy_file(rdir.buf, wtdir.buf,
                                  st.st_mode)) {
                        ret = error("could not copy '%s' to '%s'", wtdir.buf, rdir.buf);
                        goto finish;
                    }
                }
            }
        }
    }

    if (finish_command(&child)) {
        ret = error("error occurred running diff --raw");
        goto finish;
    }

    if (!i)
        return 0;

    /*
     * Changes to submodules require special treatment.This loop writes a
     * temporary file to both the left and right directories to show the
     * change in the recorded SHA1 for the submodule.
     */
    hashmap_iter_init(&submodules, &iter);
    while ((entry = hashmap_iter_next(&iter))) {
        if (*entry->left) {
            add_path(&ldir, ldir_len, entry->path);
            ensure_leading_directories(ldir.buf);
            write_file(ldir.buf, "%s", entry->left);
        }
        if (*entry->right) {
            add_path(&rdir, rdir_len, entry->path);
            ensure_leading_directories(rdir.buf);
            write_file(rdir.buf, "%s", entry->right);
        }
    }

    /*
     * Symbolic links require special treatment.The standard "git diff"
     * shows only the link itself, not the contents of the link target.
     * This loop replicates that behavior.
     */
    hashmap_iter_init(&symlinks2, &iter);
    while ((entry = hashmap_iter_next(&iter))) {
        if (*entry->left) {
            add_path(&ldir, ldir_len, entry->path);
            ensure_leading_directories(ldir.buf);
            write_file(ldir.buf, "%s", entry->left);
        }
        if (*entry->right) {
            add_path(&rdir, rdir_len, entry->path);
            ensure_leading_directories(rdir.buf);
            write_file(rdir.buf, "%s", entry->right);
        }
    }

    strbuf_release(&buf);

    strbuf_setlen(&ldir, ldir_len);
    helper_argv[1] = ldir.buf;
    strbuf_setlen(&rdir, rdir_len);
    helper_argv[2] = rdir.buf;

    if (extcmd) {
        helper_argv[0] = extcmd;
        flags = 0;
    } else
        setenv("GIT_DIFFTOOL_DIRDIFF", "true", 1);
    rc = run_command_v_opt(helper_argv, flags);

    /*
     * If the diff includes working copy files and those
     * files were modified during the diff, then the changes
     * should be copied back to the working tree.
     * Do not copy back files when symlinks are used and the
     * external tool did not replace the original link with a file.
     *
     * These hashes are loaded lazily since they aren't needed
     * in the common case of --symlinks and the difftool updating
     * files through the symlink.
     */
    hashmap_init(&wt_modified, (hashmap_cmp_fn)path_entry_cmp,
                 wtindex.cache_nr);
    hashmap_init(&tmp_modified, (hashmap_cmp_fn)path_entry_cmp,
                 wtindex.cache_nr);

    for (i = 0; i < wtindex.cache_nr; i++) {
        struct hashmap_entry dummy;
        const char *name = wtindex.cache[i]->name;
        struct stat st;

        add_path(&rdir, rdir_len, name);
        if (lstat(rdir.buf, &st))
            continue;

        if ((symlinks && S_ISLNK(st.st_mode)) || !S_ISREG(st.st_mode))
            continue;

        if (!indices_loaded) {
            static struct lock_file lock;
            strbuf_reset(&buf);
            strbuf_addf(&buf, "%s/wtindex", tmpdir);
            if (hold_lock_file_for_update(&lock, buf.buf, 0) < 0 ||
                    write_locked_index(&wtindex, &lock, COMMIT_LOCK)) {
                ret = error("could not write %s", buf.buf);
                rollback_lock_file(&lock);
                goto finish;
            }
            changed_files(&wt_modified, buf.buf, workdir);
            strbuf_setlen(&rdir, rdir_len);
            changed_files(&tmp_modified, buf.buf, rdir.buf);
            add_path(&rdir, rdir_len, name);
            indices_loaded = 1;
        }

        hashmap_entry_init(&dummy, strhash(name));
        if (hashmap_get(&tmp_modified, &dummy, name)) {
            add_path(&wtdir, wtdir_len, name);
            if (hashmap_get(&wt_modified, &dummy, name)) {
                warning(_("both files modified: '%s' and '%s'."),
                        wtdir.buf, rdir.buf);
                warning(_("working tree file has been left."));
                warning("");
                err = 1;
            } else if (unlink(wtdir.buf) ||
                       copy_file(wtdir.buf, rdir.buf, st.st_mode))
                warning_errno(_("could not copy '%s' to '%s'"),
                              rdir.buf, wtdir.buf);
        }
    }

    if (err) {
        warning(_("temporary files exist in '%s'."), tmpdir);
        warning(_("you may want to cleanup or recover these."));
        exit(1);
    } else
        exit_cleanup(tmpdir, rc);

finish:
    free(ce);
    strbuf_release(&ldir);
    strbuf_release(&rdir);
    strbuf_release(&wtdir);
    strbuf_release(&buf);

    return ret;
}
Exemple #17
0
unsigned char WriteTextLine(unsigned int fhandle, char* buff) {
  unsigned int len = strlen((char const*)buff);

  write_file( fhandle, len, (char*)buff );
  return write_file( fhandle, 2, (char*)CRLF );
}
Exemple #18
0
/*
 * Send a file via the TFTP data session.
 */
void
tftp_send(int peer, uint16_t *block, struct tftp_stats *ts)
{
	struct tftphdr *rp;
	int size, n_data, n_ack, try;
	uint16_t oldblock;
	char sendbuffer[MAXPKTSIZE];
	char recvbuffer[MAXPKTSIZE];

	rp = (struct tftphdr *)recvbuffer;
	*block = 1;
	ts->amount = 0;
	do {
		if (debug&DEBUG_SIMPLE)
			tftp_log(LOG_DEBUG, "Sending block %d", *block);

		size = read_file(sendbuffer, segsize);
		if (size < 0) {
			tftp_log(LOG_ERR, "read_file returned %d", size);
			send_error(peer, errno + 100);
			goto abort;
		}

		for (try = 0; ; try++) {
			n_data = send_data(peer, *block, sendbuffer, size);
			if (n_data > 0) {
				if (try == maxtimeouts) {
					tftp_log(LOG_ERR,
					    "Cannot send DATA packet #%d, "
					    "giving up", *block);
					return;
				}
				tftp_log(LOG_ERR,
				    "Cannot send DATA packet #%d, trying again",
				    *block);
				continue;
			}

			n_ack = receive_packet(peer, recvbuffer,
			    MAXPKTSIZE, NULL, timeoutpacket);
			if (n_ack < 0) {
				if (n_ack == RP_TIMEOUT) {
					if (try == maxtimeouts) {
						tftp_log(LOG_ERR,
						    "Timeout #%d send ACK %d "
						    "giving up", try, *block);
						return;
					}
					tftp_log(LOG_WARNING,
					    "Timeout #%d on ACK %d",
					    try, *block);
					continue;
				}

				/* Either read failure or ERROR packet */
				if (debug&DEBUG_SIMPLE)
					tftp_log(LOG_ERR, "Aborting: %s",
					    rp_strerror(n_ack));
				goto abort;
			}
			if (rp->th_opcode == ACK) {
				ts->blocks++;
				if (rp->th_block == *block) {
					ts->amount += size;
					break;
				}

				/* Re-synchronize with the other side */
				(void) synchnet(peer);
				if (rp->th_block == (*block - 1)) {
					ts->retries++;
					continue;
				}
			}

		}
		oldblock = *block;
		(*block)++;
		if (oldblock > *block) {
			if (options[OPT_ROLLOVER].o_request == NULL) {
				/*
				 * "rollover" option not specified in
				 * tftp client.  Default to rolling block
				 * counter to 0.
				 */
				*block = 0;
			} else {
				*block = atoi(options[OPT_ROLLOVER].o_request);
			}

			ts->rollovers++;
		}
		gettimeofday(&(ts->tstop), NULL);
	} while (size == segsize);
abort:
	return;
}

/*
 * Receive a file via the TFTP data session.
 *
 * - It could be that the first block has already arrived while
 *   trying to figure out if we were receiving options or not. In
 *   that case it is passed to this function.
 */
void
tftp_receive(int peer, uint16_t *block, struct tftp_stats *ts,
    struct tftphdr *firstblock, size_t fb_size)
{
	struct tftphdr *rp;
	uint16_t oldblock;
	int n_data, n_ack, writesize, i, retry;
	char recvbuffer[MAXPKTSIZE];

	ts->amount = 0;

	if (firstblock != NULL) {
		writesize = write_file(firstblock->th_data, fb_size);
		ts->amount += writesize;
		for (i = 0; ; i++) {
			n_ack = send_ack(peer, *block);
			if (n_ack > 0) {
				if (i == maxtimeouts) {
					tftp_log(LOG_ERR,
					    "Cannot send ACK packet #%d, "
					    "giving up", *block);
					return;
				}
				tftp_log(LOG_ERR,
				    "Cannot send ACK packet #%d, trying again",
				    *block);
				continue;
			}

			break;
		}

		if (fb_size != segsize) {
			gettimeofday(&(ts->tstop), NULL);
			return;
		}
	}

	rp = (struct tftphdr *)recvbuffer;
	do {
		oldblock = *block;
		(*block)++;
		if (oldblock > *block) {
			if (options[OPT_ROLLOVER].o_request == NULL) {
				/*
				 * "rollover" option not specified in
				 * tftp client.  Default to rolling block
				 * counter to 0.
				 */
				*block = 0;
			} else {
				*block = atoi(options[OPT_ROLLOVER].o_request);
			}

			ts->rollovers++;
		}

		for (retry = 0; ; retry++) {
			if (debug&DEBUG_SIMPLE)
				tftp_log(LOG_DEBUG,
				    "Receiving DATA block %d", *block);

			n_data = receive_packet(peer, recvbuffer,
			    MAXPKTSIZE, NULL, timeoutpacket);
			if (n_data < 0) {
				if (retry == maxtimeouts) {
					tftp_log(LOG_ERR,
					    "Timeout #%d on DATA block %d, "
					    "giving up", retry, *block);
					return;
				}
				if (n_data == RP_TIMEOUT) {
					tftp_log(LOG_WARNING,
					    "Timeout #%d on DATA block %d",
					    retry, *block);
					send_ack(peer, oldblock);
					continue;
				}

				/* Either read failure or ERROR packet */
				if (debug&DEBUG_SIMPLE)
					tftp_log(LOG_DEBUG, "Aborting: %s",
					    rp_strerror(n_data));
				goto abort;
			}
			if (rp->th_opcode == DATA) {
				ts->blocks++;

				if (rp->th_block == *block)
					break;

				tftp_log(LOG_WARNING,
				    "Expected DATA block %d, got block %d",
				    *block, rp->th_block);

				/* Re-synchronize with the other side */
				(void) synchnet(peer);
				if (rp->th_block == (*block-1)) {
					tftp_log(LOG_INFO, "Trying to sync");
					*block = oldblock;
					ts->retries++;
					goto send_ack;	/* rexmit */
				}

			} else {
				tftp_log(LOG_WARNING,
				    "Expected DATA block, got %s block",
				    packettype(rp->th_opcode));
			}
		}

		if (n_data > 0) {
			writesize = write_file(rp->th_data, n_data);
			ts->amount += writesize;
			if (writesize <= 0) {
				tftp_log(LOG_ERR,
				    "write_file returned %d", writesize);
				if (writesize < 0)
					send_error(peer, errno + 100);
				else
					send_error(peer, ENOSPACE);
				goto abort;
			}
		}

send_ack:
		for (i = 0; ; i++) {
			n_ack = send_ack(peer, *block);
			if (n_ack > 0) {

				if (i == maxtimeouts) {
					tftp_log(LOG_ERR,
					    "Cannot send ACK packet #%d, "
					    "giving up", *block);
					return;
				}

				tftp_log(LOG_ERR,
				    "Cannot send ACK packet #%d, trying again",
				    *block);
				continue;
			}

			break;
		}
		gettimeofday(&(ts->tstop), NULL);
	} while (n_data == segsize);

	/* Don't do late packet management for the client implementation */
	if (acting_as_client)
		return;

	for (i = 0; ; i++) {
		n_data = receive_packet(peer, (char *)rp, pktsize,
		    NULL, timeoutpacket);
		if (n_data <= 0)
			break;
		if (n_data > 0 &&
		    rp->th_opcode == DATA &&	/* and got a data block */
		    *block == rp->th_block)	/* then my last ack was lost */
			send_ack(peer, *block);	/* resend final ack */
	}

abort:
	return;
}
Exemple #19
0
int main(int args_num,char *args[])
{
    //modify output file name
    char output[1000];
    if(args_num==4){
        int i=0;
        for(i=0;i<strlen(args[3]);i++){
            if(args[3][i]=='.'){
                output[i]='\0';
                break;
            }
            output[i]=args[3][i];
        }
    }
    // open files
    char *file_dir = malloc(sizeof(char) * 1000);
    FILE* file1;
    FILE* file2;
    FILE* file3;
    FILE* file4;
    //open file 1
    if(args_num>=2){
        getcwd(file_dir,1000);
        strcat(file_dir,"/");
        strcat(file_dir,args[1]);
        file1=fopen(file_dir,"r");
        if(!file1){
            getcwd(file_dir,1000);
            strcat(file_dir,"/a.txt");
            file1=fopen(file_dir,"r");
        }
    }
    else{
        getcwd(file_dir,1000);
        strcat(file_dir,"/a.txt");
        file1=fopen(file_dir,"r");
    }
    //open file 2
    if(args_num>=3){
        getcwd(file_dir,1000);
        strcat(file_dir,"/");
        strcat(file_dir,args[2]);
        file2=fopen(file_dir,"r");
        if(!file2){
            getcwd(file_dir,1000);
            strcat(file_dir,"/b.txt");
            file2=fopen(file_dir,"r");
        }
    }
    else{
        getcwd(file_dir,1000);
        strcat(file_dir,"/b.txt");
        file2=fopen(file_dir,"r");
    }
    //open file 3 and 4
     if(args_num==4){
        getcwd(file_dir,1000);
        strcat(file_dir,"/");
        strcat(file_dir,output);
        strcat(file_dir,"_1");
        file3=fopen(file_dir,"w");

        getcwd(file_dir,1000);
        strcat(file_dir,"/");
        strcat(file_dir,output);
        strcat(file_dir,"_2");
        file4 = fopen(file_dir,"w");

        if(!file3 || !file4){
            getcwd(file_dir,1000);
            strcat(file_dir,"/c_1.out");
            file3=fopen(file_dir,"w");

            getcwd(file_dir,1000);
            strcat(file_dir,"/c_2.out");
            file4=fopen(file_dir,"w");
        }
    }
    else{
       getcwd(file_dir,1000);
        strcat(file_dir,"/c_1.out");
        file3=fopen(file_dir,"w");

        getcwd(file_dir,1000);
        strcat(file_dir,"/c_2.out");
        file4=fopen(file_dir,"w");
    }
    if(!file1 || !file2){
        printf("Error in input files.\n");
        exit(0);
    }
    //read file 1
    read_file1(file1);
    //read file 2
    read_file2(file2);
    // check for multiplication condition
    if(m1!=n2){
        printf("m1 does not equal n2, can not do multiplication.\n");
        exit(0);
    }
    //allocate matrix3 and matrix4
    matrix_allocate(&matrix3,n1,m2);
    //method 1
    int i,j;
    pthread_t threads[n1][m2];
    clock_t start=clock();

    int flag1=1,flag2=1;
    for(i=0;i<n1;i++){
        int return_code= pthread_create(&threads[i][0],NULL,method1,(void *)i);
        if(return_code){
            //error occured creating thread
            flag1=0;
            break;
        }
    }
    //join threads to continue with method2
    int k;
    for(k=0;k<i;k++){
        pthread_join(threads[k][0],NULL);
    }
    //output1
    if(flag1){
        clock_t mthd1=clock();
        printf("Method 1\n");
        printf("Number of threads = %d\n",n1);
        printf("Execution time = %lf milliseconds\n",(double) (mthd1-start)/CLOCKS_PER_SEC*1000.0);
        write_file(file3);
    }
    else
        printf("Error occured in method 1.\n");

    //initialize matrix3
    for(i=0;i<n1;i++){
        for(j=0;j<m2;j++)
            matrix3[i][j]=0;
    }
    //method 2
    clock_t start2 = clock();
    for(i=0;i<n1;i++){
        for(j=0;j<m2;j++){
            int return_code= pthread_create(&threads[i][j],NULL,method2,(void *)(i*m2+j));
            if(return_code){
                flag2=0;
                break;
            }
        }
    }
    int w;
    for(w=0;w<i;w++){
        for(k=0;k<j;k++){
            pthread_join(threads[w][k],NULL);
        }
    }
    //output 2
    if(flag2){
        clock_t mthd2=clock();
        printf("Method 2\n");
        printf("Number of threads = %d\n",n1*m2);
        printf("Execution time = %lf milliseconds\n",(double)(mthd2-start2)/CLOCKS_PER_SEC*1000.0);
        write_file(file4);
    }
    else
        printf("Error occured in method 2.\n");


    //close files
    fclose(file1);
    fclose(file2);
    fclose(file3);
    fclose(file4);
    return 0;
}
Exemple #20
0
/*
 * Write user-specified files/dirs to opened archive.
 */
static void
write_archive(struct archive *a, struct bsdtar *bsdtar)
{
	const char *arg;
	struct archive_entry *entry, *sparse_entry;

	/* Choose a suitable copy buffer size */
	bsdtar->buff_size = 64 * 1024;
	while (bsdtar->buff_size < (size_t)bsdtar->bytes_per_block)
	  bsdtar->buff_size *= 2;
	/* Try to compensate for space we'll lose to alignment. */
	bsdtar->buff_size += 16 * 1024;

	/* Allocate a buffer for file data. */
	if ((bsdtar->buff = malloc(bsdtar->buff_size)) == NULL)
		lafe_errc(1, 0, "cannot allocate memory");

	if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
		lafe_errc(1, 0, "cannot create link resolver");
	archive_entry_linkresolver_set_strategy(bsdtar->resolver,
	    archive_format(a));
	if ((bsdtar->diskreader = archive_read_disk_new()) == NULL)
		lafe_errc(1, 0, "Cannot create read_disk object");
	archive_read_disk_set_standard_lookup(bsdtar->diskreader);

	if (bsdtar->names_from_file != NULL)
		archive_names_from_file(bsdtar, a);

	while (*bsdtar->argv) {
		arg = *bsdtar->argv;
		if (arg[0] == '-' && arg[1] == 'C') {
			arg += 2;
			if (*arg == '\0') {
				bsdtar->argv++;
				arg = *bsdtar->argv;
				if (arg == NULL) {
					lafe_warnc(0, "%s",
					    "Missing argument for -C");
					bsdtar->return_value = 1;
					goto cleanup;
				}
				if (*arg == '\0') {
					lafe_warnc(0,
					    "Meaningless argument for -C: ''");
					bsdtar->return_value = 1;
					goto cleanup;
				}
			}
			set_chdir(bsdtar, arg);
		} else {
			if (*arg != '/' && (arg[0] != '@' || arg[1] != '/'))
				do_chdir(bsdtar); /* Handle a deferred -C */
			if (*arg == '@') {
				if (append_archive_filename(bsdtar, a,
				    arg + 1) != 0)
					break;
			} else
				write_hierarchy(bsdtar, a, arg);
		}
		bsdtar->argv++;
	}

	entry = NULL;
	archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
	while (entry != NULL) {
		write_file(bsdtar, a, entry);
		archive_entry_free(entry);
		entry = NULL;
		archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
	}

	if (archive_write_close(a)) {
		lafe_warnc(0, "%s", archive_error_string(a));
		bsdtar->return_value = 1;
	}

cleanup:
	/* Free file data buffer. */
	free(bsdtar->buff);
	archive_entry_linkresolver_free(bsdtar->resolver);
	bsdtar->resolver = NULL;
	archive_read_free(bsdtar->diskreader);
	bsdtar->diskreader = NULL;

	if (bsdtar->option_totals) {
		fprintf(stderr, "Total bytes written: %s\n",
		    tar_i64toa(archive_position_compressed(a)));
	}

	archive_write_free(a);
}
void CREATE_CPP_CODE_SAVED_DESIGNS ( void )
{
    SQL_QUERY f_query (G_YONETIM_DB);
    SQL_QUERY s_query (G_YONETIM_DB);

    f_query.PREPARE_SELECT("ynt_belge_tasarimlari",
                           "tasarim_id, belge_id, tasarim_adi, html_str,       "
                           "belge_width, belge_height,row_count, row_space_mm, "
                           "row_space_satir, belge_satir_sayisi,               "
                           "belge_toplam_karakter_sayisi, kopya_sayisi,        "
                           "kopya_konumu, printer_type, line_headers_visible", "", "" );

    if ( f_query.SELECT() EQ 0 ) {
        return;
    }

    QString belgeler_code_str    = "BELGELER_STRUCT belgeler[] = {\n";
    QString degiskenler_code_str = "BELGE_DEGISKENLERI_STRUCT belgeler_degiskenleri[] = {\n";

    int eklenecek_belge_sayisi = 0;
    bool degiskenler_eklendi = false;

    while ( f_query.NEXT() EQ true ) {
        /////////////////////////////// DEGISKENLER

        s_query.PREPARE_SELECT("ynt_belge_degiskenleri",
                               "degisken_id,font_size,align,pos_x,pos_y,size_vertical, "
                               "size_horizontal,text,is_visible_variable,grup_enum, monospace_mi, "
                               "text_size, font_family, is_bold, is_under_line, is_italic, is_strikeout, satir, soldan_bosluk ",
                               "tasarim_id = :tasarim_id","");

        s_query.SET_VALUE(":tasarim_id" , f_query.VALUE("tasarim_id").toString() );

        if ( s_query.SELECT()  EQ 0) {
            continue;
        }

        int tasarim_sayisi = 0;

        while ( s_query.NEXT() EQ true ) {
            if ( tasarim_sayisi NE 0 OR degiskenler_eklendi EQ true) {
                degiskenler_code_str.append(",\n");
            }

            degiskenler_code_str.append("\t{ ");
            degiskenler_code_str.append(QString ("\"%1\",\"%2\",\"%3\",\"%4\",%5,"
                                                 "\"%6\",\"%7\",\"%8\",\"%9\",\"%10\","
                                                 "%11, %12, %13, \"%14\", %15, %16, %17, %18, %19, %20")
                                        .arg(s_query.VALUE("degisken_id").toString())
                                        .arg(s_query.VALUE("font_size").toString())
                                        .arg(s_query.VALUE("align").toString())
                                        .arg(s_query.VALUE("is_visible_variable").toString())
                                        .arg(s_query.VALUE("grup_enum").toString())
                                        .arg(s_query.VALUE("size_vertical").toString())
                                        .arg(s_query.VALUE("size_horizontal").toString())
                                        .arg(s_query.VALUE("pos_x").toString())
                                        .arg(s_query.VALUE("pos_y").toString())
                                        .arg(s_query.VALUE("text").toString())
                                        .arg(QVariant(eklenecek_belge_sayisi).toString())
                                        .arg(s_query.VALUE("monospace_mi").toString())
                                        .arg(s_query.VALUE("text_size").toString())
                                        .arg(s_query.VALUE("font_family").toString())
                                        .arg(s_query.VALUE("is_bold").toInt())
                                        .arg(s_query.VALUE("is_under_line").toInt())
                                        .arg(s_query.VALUE("is_italic").toInt())
                                        .arg(s_query.VALUE("is_strikeout").toInt())
                                        .arg(s_query.VALUE("satir").toInt())
                                        .arg(s_query.VALUE("soldan_bosluk").toInt())

                                        );

            degiskenler_code_str.append(" }");
            degiskenler_eklendi = true;
            tasarim_sayisi++;
        }

        ////////////////////////////////////////////

        if ( eklenecek_belge_sayisi NE 0) {
            belgeler_code_str.append(",\n");
        }

        belgeler_code_str.append("\t{ ");
        belgeler_code_str.append(QString ("\"%1\",\"%2\",\"%3\",\"%4\",\"%6\",\"%8\",\"%9\",\"%10\",\""
                                          "%11\",%12,\"%13\",\"%14\",\"%15\",\"%16\",\"%17\"")
                                    .arg(f_query.VALUE("belge_id").toString())
                                    .arg(f_query.VALUE("row_count").toString())
                                    .arg(f_query.VALUE("row_space_satir").toString())
                                    .arg(f_query.VALUE("belge_satir_sayisi").toString())
                                    .arg(f_query.VALUE("belge_toplam_karakter_sayisi").toString())
                                    .arg(f_query.VALUE("kopya_sayisi").toString())
                                    .arg(f_query.VALUE("kopya_konumu").toString())
                                    .arg(f_query.VALUE("printer_type").toString())
                                    .arg(f_query.VALUE("line_headers_visible").toString())
                                    .arg(QVariant(tasarim_sayisi).toString())
                                    .arg(f_query.VALUE("belge_width").toString())
                                    .arg(f_query.VALUE("belge_height").toString())
                                    .arg(f_query.VALUE("row_space_mm").toString())
                                    .arg(f_query.VALUE("tasarim_adi").toString())
                                    .arg(f_query.VALUE("html_str").toString()) );

        belgeler_code_str.append(" }");

        eklenecek_belge_sayisi++;
    }

    belgeler_code_str.append(",\n{ \"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",-1,\"\",\"\",\"\",\"\",\"\" }");
    belgeler_code_str.append("\n};\n\n");

    degiskenler_code_str.append(",\n{ \"\",\"\",\"\",\"\",-1,\"\",\"\",\"\",\"\",\"\", -1, 0, 0, \"\", 0, 0, 0, 0, 0, 0 }");
    degiskenler_code_str.append("\n};\n\n");
    //degiskenler_code_str.append(QString("int eklenecek_belge_sayisi = %1;").arg(eklenecek_belge_sayisi));

    QFile degiskenler_file ("e9_default_belge_degiskenleri.h");

    if (!degiskenler_file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return;
    }

    QString header_begin = "#ifndef E9_DEFAULT_BELGE_DEGISKENLERI_H \n"
                           "#define E9_DEFAULT_BELGE_DEGISKENLERI_H \n\n";


    QString header_end   = "\n #endif";


    QTextStream write_file (&degiskenler_file);
    write_file << header_begin;
    write_file << belgeler_code_str;
    write_file << degiskenler_code_str;
    write_file << header_end;

    degiskenler_file.close();

    ADAK_INFO (QObject::tr("e9_default_belge.h was rebuilt."),NULL,NULL);//e9_default_belge.h yeniden oluşturuldu.
}
Exemple #22
0
/*
 * Add the file or dir hierarchy named by 'path' to the archive
 */
static void
write_hierarchy(struct bsdtar *bsdtar, struct archive *a, const char *path)
{
	struct archive_entry *entry = NULL, *spare_entry = NULL;
	struct tree *tree;
	char symlink_mode = bsdtar->symlink_mode;
	dev_t first_dev = 0;
	int dev_recorded = 0;
	int tree_ret;

	tree = tree_open(path);

	if (!tree) {
		lafe_warnc(errno, "%s: Cannot open", path);
		bsdtar->return_value = 1;
		return;
	}

	while ((tree_ret = tree_next(tree)) != 0) {
		int r;
		const char *name = tree_current_path(tree);
		const struct stat *st = NULL; /* info to use for this entry */
		const struct stat *lst = NULL; /* lstat() information */
		int descend;

		if (tree_ret == TREE_ERROR_FATAL)
			lafe_errc(1, tree_errno(tree),
			    "%s: Unable to continue traversing directory tree",
			    name);
		if (tree_ret == TREE_ERROR_DIR) {
			lafe_warnc(errno,
			    "%s: Couldn't visit directory", name);
			bsdtar->return_value = 1;
		}
		if (tree_ret != TREE_REGULAR)
			continue;

		/*
		 * If this file/dir is excluded by a filename
		 * pattern, skip it.
		 */
		if (lafe_excluded(bsdtar->matching, name))
			continue;

		/*
		 * Get lstat() info from the tree library.
		 */
		lst = tree_current_lstat(tree);
		if (lst == NULL) {
			/* Couldn't lstat(); must not exist. */
			lafe_warnc(errno, "%s: Cannot stat", name);
			/* Return error if files disappear during traverse. */
			bsdtar->return_value = 1;
			continue;
		}

		/*
		 * Distinguish 'L'/'P'/'H' symlink following.
		 */
		switch(symlink_mode) {
		case 'H':
			/* 'H': After the first item, rest like 'P'. */
			symlink_mode = 'P';
			/* 'H': First item (from command line) like 'L'. */
			/* FALLTHROUGH */
		case 'L':
			/* 'L': Do descend through a symlink to dir. */
			descend = tree_current_is_dir(tree);
			/* 'L': Follow symlinks to files. */
			archive_read_disk_set_symlink_logical(bsdtar->diskreader);
			/* 'L': Archive symlinks as targets, if we can. */
			st = tree_current_stat(tree);
			if (st != NULL)
				break;
			/* If stat fails, we have a broken symlink;
			 * in that case, don't follow the link. */
			/* FALLTHROUGH */
		default:
			/* 'P': Don't descend through a symlink to dir. */
			descend = tree_current_is_physical_dir(tree);
			/* 'P': Don't follow symlinks to files. */
			archive_read_disk_set_symlink_physical(bsdtar->diskreader);
			/* 'P': Archive symlinks as symlinks. */
			st = lst;
			break;
		}

		if (bsdtar->option_no_subdirs)
			descend = 0;

		/*
		 * Are we about to cross to a new filesystem?
		 */
		if (!dev_recorded) {
			/* This is the initial file system. */
			first_dev = lst->st_dev;
			dev_recorded = 1;
		} else if (lst->st_dev == first_dev) {
			/* The starting file system is always acceptable. */
		} else if (descend == 0) {
			/* We're not descending, so no need to check. */
		} else if (bsdtar->option_dont_traverse_mounts) {
			descend = 0;
		} else {
			/* We're prepared to cross a mount point. */

			/* XXX TODO: check whether this filesystem is
			 * synthetic and/or local.  Add a new
			 * --local-only option to skip non-local
			 * filesystems.  Skip synthetic filesystems
			 * regardless.
			 *
			 * The results should be cached, since
			 * tree.c doesn't usually visit a directory
			 * and the directory contents together.  A simple
			 * move-to-front list should perform quite well.
			 *
			 * This is going to be heavily OS dependent:
			 * FreeBSD's statfs() in conjunction with getvfsbyname()
			 * provides all of this; NetBSD's statvfs() does
			 * most of it; other systems will vary.
			 */
		}

		/*
		 * In -u mode, check that the file is newer than what's
		 * already in the archive; in all modes, obey --newerXXX flags.
		 */
		if (!new_enough(bsdtar, name, st)) {
			if (!descend)
				continue;
			if (bsdtar->option_interactive &&
			    !yes("add '%s'", name))
				continue;
			tree_descend(tree);
			continue;
		}

		archive_entry_free(entry);
		entry = archive_entry_new();

		archive_entry_set_pathname(entry, name);
		archive_entry_copy_sourcepath(entry,
		    tree_current_access_path(tree));

		/* Populate the archive_entry with metadata from the disk. */
		/* XXX TODO: Arrange to open a regular file before
		 * calling this so we can pass in an fd and shorten
		 * the race to query metadata.  The linkify dance
		 * makes this more complex than it might sound. */
#if defined(_WIN32) && !defined(__CYGWIN__)
		/* TODO: tree.c uses stat(), which is badly broken
		 * on Windows.  To fix this, we should
		 * deprecate tree_current_stat() and provide a new
		 * call tree_populate_entry(t, entry).  This call
		 * would use stat() internally on POSIX and
		 * GetInfoByFileHandle() internally on Windows.
		 * This would be another step towards a tree-walker
		 * that can be integrated deep into libarchive.
		 * For now, just set st to NULL on Windows;
		 * archive_read_disk_entry_from_file() should
		 * be smart enough to use platform-appropriate
		 * ways to probe file information.
		 */
		st = NULL;
#endif
		r = archive_read_disk_entry_from_file(bsdtar->diskreader,
		    entry, -1, st);
		if (bsdtar->uid >= 0) {
			archive_entry_set_uid(entry, bsdtar->uid);
			if (!bsdtar->uname)
				archive_entry_set_uname(entry,
				    archive_read_disk_uname(bsdtar->diskreader,
					bsdtar->uid));
		}
		if (bsdtar->gid >= 0) {
			archive_entry_set_gid(entry, bsdtar->gid);
			if (!bsdtar->gname)
				archive_entry_set_gname(entry,
				    archive_read_disk_gname(bsdtar->diskreader,
					bsdtar->gid));
		}
		if (bsdtar->uname)
			archive_entry_set_uname(entry, bsdtar->uname);
		if (bsdtar->gname)
			archive_entry_set_gname(entry, bsdtar->gname);
		if (r != ARCHIVE_OK)
			lafe_warnc(archive_errno(bsdtar->diskreader),
			    "%s", archive_error_string(bsdtar->diskreader));
		if (r < ARCHIVE_WARN)
			continue;

		/* XXX TODO: Just use flag data from entry; avoid the
		 * duplicate check here. */

		/*
		 * If this file/dir is flagged "nodump" and we're
		 * honoring such flags, skip this file/dir.
		 */
#if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
		/* BSD systems store flags in struct stat */
		if (bsdtar->option_honor_nodump &&
		    (lst->st_flags & UF_NODUMP))
			continue;
#endif

#if defined(EXT2_IOC_GETFLAGS) && defined(EXT2_NODUMP_FL)
		/* Linux uses ioctl to read flags. */
		if (bsdtar->option_honor_nodump) {
			int fd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY);
			if (fd >= 0) {
				unsigned long fflags;
				int r = ioctl(fd, EXT2_IOC_GETFLAGS, &fflags);
				close(fd);
				if (r >= 0 && (fflags & EXT2_NODUMP_FL))
					continue;
			}
		}
#endif

#ifdef __APPLE__
		if (bsdtar->enable_copyfile) {
			/* If we're using copyfile(), ignore "._XXX" files. */
			const char *bname = strrchr(name, '/');
			if (bname == NULL)
				bname = name;
			else
				++bname;
			if (bname[0] == '.' && bname[1] == '_')
				continue;
		} else {
			/* If not, drop the copyfile() data. */
			archive_entry_copy_mac_metadata(entry, NULL, 0);
		}
#endif

		/*
		 * If the user vetoes this file/directory, skip it.
		 * We want this to be fairly late; if some other
		 * check would veto this file, we shouldn't bother
		 * the user with it.
		 */
		if (bsdtar->option_interactive &&
		    !yes("add '%s'", name))
			continue;

		if (descend)
			tree_descend(tree);

		/*
		 * Rewrite the pathname to be archived.  If rewrite
		 * fails, skip the entry.
		 */
		if (edit_pathname(bsdtar, entry))
			continue;

		/* Display entry as we process it.
		 * This format is required by SUSv2. */
		if (bsdtar->verbose)
			safe_fprintf(stderr, "a %s",
			    archive_entry_pathname(entry));

		/* Non-regular files get archived with zero size. */
		if (archive_entry_filetype(entry) != AE_IFREG)
			archive_entry_set_size(entry, 0);

		archive_entry_linkify(bsdtar->resolver, &entry, &spare_entry);

		while (entry != NULL) {
			write_file(bsdtar, a, entry);
			archive_entry_free(entry);
			entry = spare_entry;
			spare_entry = NULL;
		}

		if (bsdtar->verbose)
			fprintf(stderr, "\n");
	}
	archive_entry_free(entry);
	tree_close(tree);
}
Exemple #23
0
int main(int argc, char* argv[])
{
    if(argc == 1)
    {
        char *input = "acaacg$";
        unsigned int len = strlen(input);
        char* input_3bit = (char*) malloc(len*sizeof(int));
        for(unsigned int i = 0; i < len; i++)
            write_bp_3bit(input_3bit, i, input[i]);
        unsigned int* sa = ss_mm_3bit(input_3bit, len);
        char* bwt = compute_bwt_3bit(input_3bit, sa, len, len);
        for(unsigned int i = 0; i < len; i++)
        {
            char bp = get_bp_3bit(bwt, i);
            printf("%c", bp);
        }
        printf("\n");
        free(input_3bit);
        free(bwt);
        return 0;
    }
    else if(argc == 3)
    {
        // initialize parameter
        unsigned int genome_size = 3000000;
        unsigned int sample_size = 10;
        if(argv[2][0] == 't' || argv[2][0] == 'T')
        {
            genome_size = GENOME_SIZE;
            sample_size = SAMPLE_SIZE;
        }

        // generate output file names
        unsigned int fnlen = strlen(argv[1]);
        char* psafn = (char*) malloc((fnlen+5)*sizeof(char));
        strcpy(psafn, argv[1]);
        psafn[fnlen] = '_'; psafn[fnlen+1] = 'p'; psafn[fnlen+2] = 's';
        psafn[fnlen+3] = 'a'; psafn[fnlen+4] = '\0';
        char *safn = (char*) malloc((fnlen+4)*sizeof(char));
        strcpy(safn, argv[1]);
        safn[fnlen] = '_'; safn[fnlen+1] = 's'; safn[fnlen+2] = 'a';
        safn[fnlen+3] = '\0';
        char *bwtfn = (char*) malloc((fnlen+5)*sizeof(char));
        strcpy(bwtfn, argv[1]);
        bwtfn[fnlen] = '_'; bwtfn[fnlen+1] = 'b'; bwtfn[fnlen+2] = 'w';
        bwtfn[fnlen+3] = 't'; bwtfn[fnlen+4] = '\0';

        // read input file
        char *genome_file;
        printf("started to read in file...\n");
        unsigned int gfsz = read_file(argv[1], &genome_file);
        printf("genome file read in...\n");

        // compute complete suffix array
        printf("started to generate suffix array...\n");
        unsigned int* sa = ss_mm_3bit(genome_file, genome_size+1);
        printf("complete suffix array generated...\n");
        write_file(safn, (char*)sa, ((size_t)(genome_size+1))*((size_t)sizeof(int)));
        printf("complete suffix array saved to disk...\n");

        // compute bwt
        printf("started to generate bwt...");
        char* bwt = compute_bwt_3bit(genome_file, sa, genome_size+1, gfsz);
        write_file(bwtfn, bwt, (size_t)gfsz);
        printf("bwt saved to disk...\n");

        // verify result
        for(unsigned int i = 0; i < genome_size+1; i++)
        {
            char bp = get_bp_3bit(bwt, i);
            if(bp == '*')
            {
                printf("%d: Error!!!\n", i);
                return 0;
            }
        }
        printf("result verified...\n");

        // compute partial suffix array
        unsigned int *sa_pt = compute_partial_sa(sa,genome_size,sample_size);
        printf("partial suffix array generated...\n");
        write_file(psafn, (char*)sa_pt, (genome_size/sample_size)*sizeof(int));
        printf("partial suffix array saved to disk...\n");
    }
    else
    {
        printf("Usage 1: [PROGRAM NAME]\n");
        printf("Usage 2: [PROGRAM NAME] [FILE NAME] [USE LARGE]\n");
        return 0;
    }
}
int
main(int argc, char *argv[])
{
    int ch, oflags;
    char fname[FILENAME_MAX];
    char *endp;

    quiet = 0;
    mode = ' ';

    while ((ch = getopt(argc, argv, "irwlpdqfh:")) != -1) {
        switch (ch) {
        case 'q':
            quiet = 1;
            break;
        case 'f':
            /* Legacy. Do nothing. */
            break;
        case 'i':
            mode = 'i';
            break;
        case 'h':
            volhdr_size = strtol(optarg, &endp, 0);
            if (*endp != '\0' || errno != 0)
                errx(1, "incorrect volume header size: %s",
                     optarg);
            break;
        case 'r':
            mode = 'r';
            break;
        case 'w':
            mode = 'w';
            break;
        case 'l':
            mode = 'l';
            break;
        case 'd':
            mode = 'd';
            break;
        case 'p':
            mode = 'p';
            break;
        default:
            usage();
        }
    }
    argc -= optind;
    argv += optind;

    if (mode == 'r' || mode == 'w' || mode == 'l') {
        if (argc != 3)
            usage();
        vfilename = argv[0];
        ufilename = argv[1];
        argc -= 2;
        argv += 2;
    } else if (mode == 'd') {
        if (argc != 2)
            usage();
        vfilename = argv[0];
        argc--;
        argv++;
    } else if (mode == 'p') {
        if (argc != 5)
            usage();
        partno = strtol(argv[0], &endp, 0);
        if (*endp != '\0' || errno != 0 ||
                partno < 0 || partno > SGI_SIZE_VOLDIR)
            errx(1, "invalid partition number: %s", argv[0]);
        partfirst = strtol(argv[1], &endp, 0);
        if (*endp != '\0' || errno != 0)
            errx(1, "invalid partition start: %s", argv[1]);
        partblocks = strtol(argv[2], &endp, 0);
        if (*endp != '\0' || errno != 0)
            errx(1, "invalid partition size: %s", argv[2]);
        parttype = strtol(argv[3], &endp, 0);
        if (*endp != '\0' || errno != 0)
            errx(1, "invalid partition type: %s", argv[3]);
        argc -= 4;
        argv += 4;
    }
    if (argc != 1)
        usage();

    oflags = ((mode == 'i' || mode == 'w' || mode == 'l' || mode == 'd'
               || mode == 'p') ? O_RDWR : O_RDONLY);

    /* Open raw device. */
    if ((fd = open(argv[0], oflags)) < 0) {
        snprintf(fname, sizeof(fname), "/dev/r%s%c",
                 argv[0], 'a' + getrawpartition());
        if ((fd = open(fname, oflags)) < 0)
            err(1, "open %s", fname);
    }

    /* Get disklabel for device. */
    if (ioctl(fd, DIOCGDINFO, &lbl) == -1)
        err(1, "ioctl DIOCGDINFO");

    /* Allocate a buffer that matches the device sector size. */
    bufsize = lbl.d_secsize;
    if (bufsize < sizeof(struct sgilabel))
        errx(1, "sector size is smaller than SGI volume header!\n");
    if ((buf = malloc(bufsize)) == NULL)
        err(1, "failed to allocate buffer");

    /* Read SGI volume header. */
    if (read(fd, buf, bufsize) != bufsize)
        err(1, "read volhdr");
    volhdr = (struct sgilabel *)buf;

    if (mode == 'i') {
        init_volhdr();
        exit(0);
    }

    if (betoh32(volhdr->magic) != SGILABEL_MAGIC)
        errx(2, "no Volume Header found, magic=%x.  Use -i first.",
             betoh32(volhdr->magic));

    if (mode == 'r')
        read_file();
    else if (mode == 'w')
        write_file();
    else if (mode == 'l')
        link_file();
    else if (mode == 'd')
        delete_file();
    else if (mode == 'p')
        modify_partition();
    else if (!quiet)
        display_vol();

    exit (0);
}
Exemple #25
0
static void write_f3s(ffs_sort_t *sort, int block_size){

	block_info_t		*block_info;
	uint32_t			size_of_entry;
	ffs_sort_t			*sort_temp_ptr;
	uint16_t			unit_flags;

	//
	//	setup generic buffer
	//

	if ((blk_buffer_ptr = (char *)malloc(0x4000)) == NULL)
		mk_flash_exit("malloc failed: %s\n",strerror(errno));	

	//
	//	create a temporary file
	//

	tmp_name = mk_tmpfile();
	
	if ((flashimage = open(tmp_name,O_BINARY | O_RDWR | O_CREAT | O_TRUNC,
				S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) == -1)
			mk_flash_exit("create of %s failed: %s\n",tmp_name,strerror(errno));

	unit_flags = ((~F3S_UNIT_MASK | F3S_UNIT_READY) & ~F3S_UNIT_NO_LOGI);
	block_info = init_block(block_size, unit_flags);

	//
	// first block requires a boot record
	//

	write_boot_record (block_info, spare_blocks,sort);

	//
	// write the initialized block to the file.  each entry will be written  
	// to disk individually.
	//
	// check if this entry has been written to the file yet
	// run through the list until we get to the end
	//

	while(sort){
		if (!(sort->status & FFS_SORT_ENTRY_SET)){

			switch(sort->mode & S_IFMT){

			case S_IFDIR:
				if(verbose)
					fprintf(debug_fp,"writing directory entry -> %s\n",sort->name);
				block_info = write_dir_entry(sort, block_info);
				break;
			case S_IFREG:
				if(verbose)
					fprintf(debug_fp,"writing file entry      -> %s ",sort->name);
				block_info = write_file(sort,block_info);
				break;	        
			case S_IFLNK:
				if(verbose)
					fprintf(debug_fp,"writing link entry      -> %s ",sort->name);
				block_info = write_lnk(sort,block_info);
				break;	        
			case S_IFIFO:
				if(verbose)
					fprintf(debug_fp,"writing fifo entry      -> %s\n",sort->name);
				block_info = write_dir_entry(sort, block_info);
				break;
			} 
		}

		//
		// check for a child, only a directory can have a child  
		//

		if (!sort->child && (sort->mode & (S_IFDIR|S_IFIFO))){


		//
		//	directory entry under f3s can not have a NULL first extent.  The extent pointer must
		//  refer to an extent that in turn points to 0 sized data.
		//

			child_extent(sort,0,block_info);
		
		}      

		if (sort->child && (sort->mode & S_IFDIR)){

			// 
			//child			
			//	

			if ((sort_temp_ptr = find_child(sort)) == NULL)
				mk_flash_exit("find_child failed\n");
		

			size_of_entry = sizeof(f3s_dirent_t) + F3S_NAME_ALIGN(strlen(sort_temp_ptr->name)+1) + sizeof(f3s_stat_t);
			sort_temp_ptr->size_of_entry = size_of_entry;

			if (block_info->available_space < (size_of_entry + sizeof(f3s_head_t)))
		        block_info = init_block(block_size, unit_flags);

			child_extent(sort,sort_temp_ptr->size_of_entry,block_info);

			
			//
			//check the mode of our child
			//

			switch(sort_temp_ptr->mode & S_IFMT){
			
			case S_IFDIR:
				if(verbose)
					fprintf(debug_fp,"writing directory entry -> %s\n",sort_temp_ptr->name);

				block_info = write_dir_entry(sort_temp_ptr, block_info);
				break;

			case S_IFREG:
				if(verbose)
					fprintf(debug_fp,"writing file entry      -> %s ",sort_temp_ptr->name);

				block_info = write_file(sort_temp_ptr,block_info);
			    break;
				
			case S_IFLNK:
				if(verbose)
					fprintf(debug_fp,"writing link entry      -> %s ",sort_temp_ptr->name);

				block_info = write_lnk(sort_temp_ptr,block_info);
				break;
			
			case S_IFIFO:
				if(verbose)
					fprintf(debug_fp,"writing FIFO entry      -> %s\n",sort_temp_ptr->name);

				block_info = write_dir_entry(sort_temp_ptr, block_info);
				break;

			}			
       	}

		//
		//check for a sibling
		//

		if (sort->sibling){
	     	if ((sort_temp_ptr = find_sibling(sort)) == NULL)
				mk_flash_exit("find_sibling failed\n");
				
		
			size_of_entry = sizeof(f3s_dirent_t) + F3S_NAME_ALIGN(strlen(sort_temp_ptr->name)+1) + sizeof(f3s_stat_t);
			sort_temp_ptr->size_of_entry = size_of_entry;

			if (block_info->available_space < (size_of_entry + sizeof(f3s_head_t)))
			       block_info = init_block(block_size, unit_flags);
			sibling_extent(sort,sort_temp_ptr->size_of_entry,block_info);
          		

			switch(sort_temp_ptr->mode & S_IFMT){
				
			case S_IFDIR:
				if(verbose)
					fprintf(debug_fp,"writing directory entry -> %s\n",sort_temp_ptr->name);

				block_info = write_dir_entry(sort_temp_ptr, block_info);
				break;
						
			case S_IFREG:
				if(verbose)
					fprintf(debug_fp,"writing file entry      -> %s ",sort_temp_ptr->name);

				block_info = write_file(sort_temp_ptr,block_info);
				break;

			case S_IFLNK:
				if(verbose)
					fprintf(debug_fp,"writing link entry      -> %s ",sort_temp_ptr->name);

				block_info = write_lnk(sort_temp_ptr,block_info);
				break;

			case S_IFIFO:
				if(verbose)
					fprintf(debug_fp,"writing fifo entry      -> %s\n",sort_temp_ptr->name);

				block_info = write_dir_entry(sort_temp_ptr, block_info);
				break;
						
			}
		}
		sort=sort->next;
	}	

	//
	//	write out the rest of the filesystem.  This includes the spare block(s) and formatting
	//	additional blocks
	//

	spare_block_alloc(block_info);
	
	//
	//	free our malloc buffer
	//

	free(blk_buffer_ptr);
}
Exemple #26
0
int
cmd(string str) {
    string line;
    string file1;
    string file2;
    int localdest;
    if(this_player()->GetForced()) {
	write("Someone has tried forcing you to cp " + str);
	return 1;
    }
    localdest = 0;    /* Assume it's not a local destination */
    if (!str || sscanf(str, "%s %s", file1, file2) != 2) {
	if (str && sscanf(str, "%s", file1)) {
	    file2 = "";     // Check to see if it's a one arg
	    localdest = 1;  // cp function.  Assume localdest.
	} else {
	    help();
	    return 1;
	}
    }
    /* check for last parameter == "." */
    if (file2 == ".") {
	localdest = 1;     /* It's a local destination */
	file2 = "";
    }
    /* Given the player's current working directory and the path(s)
       for the file, construct the new full path for both files */
    file1 = absolute_path(this_player()->query_cwd(), file1);
    file2 = absolute_path(this_player()->query_cwd(), file2);

    /* This used to give and lstat error, fixed 930208 by Plura */
    if(file_size(file1) < 1)
    {
	notify_fail("cp: couldn't find "+file1+"\n");
	return 0;
    }

    /* Check if the destination is a directory */
    if (!localdest) {
	if (file_size(file2) == -2)
	    localdest = 1;
    }
    if (localdest) {
	/* Extract the root file name from the source and use
	   it for the destination.  file2 should be just a
	   directory path at this point so that the rootname can
	   be appended. */
	string newroot;
	string path;
	string rootname;
	rootname = file1;
	while(sscanf(rootname, "%s/%s", path, newroot) == 2) {
	    rootname = newroot;
	}
	file2 = file2 + "/" + rootname;
    }
    if(file_size(file1) == -2)   /*Plura 930120*/
    {
	notify_fail("cp: "+file1+" is a directory.\n");
	return 0;
    }
    if(file_size(file2) > 0)  /* Plura 930120 */
    {
	notify_fail("cp: "+file2+" already exists.\n");
	return 0;
    }
    if (file1 == file2) {
	notify_fail("cp: can not copy a file on top of itself!\n");
	return 0;
    }
    if(!master()->valid_read(file1, this_player(), "cp"))
    {
	notify_fail(file1 + ": Permission denied.\n");
	return 0;
    }
    if(!master()->valid_write(file2, this_player(), "cp"))
    {
	notify_fail(file2 + ": Permission denied.\n");
	return 0;
    }
    line = read_file(file1);
    if (line == 0) {
	/* Uhoh.  Can't read source file. */
	notify_fail("cp: file not found: " + file1 + "\n");
	return 0;
    }
    if (file_size(file2) == -2)
    {
	notify_fail("Tried to overwrite the directory "+ file2 + "\n");
	return 0;
    }
    rm(file2);
    write_file(file2, line);
    message("system", "Copied: " + file1 + " to " + file2, this_player());
    return 1;
}
Exemple #27
0
int do_hostname(int nargs, char **args)
{
    return write_file("/proc/sys/kernel/hostname", args[1]);
}
int main()
{
  ON::Begin();

  // uuid used to get user data via ON_Object::GetUserData()
  const ON_UUID my_user_data_uuid = MyUserData::m_MyUserData_class_id.Uuid();

  // We'll attach a MyUserData user data to a point.  In general,
  // you can attach user data to any class derived from ON_Object.
  ON_Point point(0.0,0.0,0.0);

  // User data must be created by a call to new
  MyUserData* ud = new MyUserData();
  ud->m_my_int = 1;
  ud->m_my_line.from.Set(0.0,0.0,0.0);
  ud->m_my_line.to.Set(1.0,1.0,1.0);
  ud->m_my_string = "my user data";

  // This attaches the user data to point.  When the point is destroied,
  // the user data will be destroyed.  
  //
  point.AttachUserData(ud);

  // Use ON_Object::GetUserData() to get user data.
  MyUserData* original_ud = MyUserData::Cast( point.GetUserData( my_user_data_uuid ) );

  printf("original_ud->m_userdata_copycount = %d\n",original_ud->m_userdata_copycount);

  // When the point is copied, the user data will be copied if 
  // ud->m_userdata_copycount > 0.
  //
  ON_Point copy_of_point = point;

  // Use ON_Object::GetUserData() to get user data.
  MyUserData* copy_of_ud = MyUserData::Cast( copy_of_point.GetUserData( my_user_data_uuid ) );

  if ( 0 == copy_of_ud )
    printf("ON_UserData::m_copy_count must be > 0 for user data to be copied.\n");
  else
    printf("copy_of_ud->m_userdata_copycount = %d\n",copy_of_ud->m_userdata_copycount);

  // When the point is transformed, the virtual ON_UserData::Transform()
  // is called to transform the point.


  // When the point is saved to a file, the virtual ON_Object::Write() is
  // called to write the attached user data.
  const char* filename = "point_with_user_Data.3dm";
  write_file( filename, point );

  // When the point is read from a file, the virtual ON_Object::Read() is
  // called to read the user data.
  ON_Object* object_from_file = 0;
  read_file( filename, object_from_file );

  if ( 0 != object_from_file )
  {
    // Use ON_Object::GetUserData() to get user data.
    MyUserData* ud_from_file = MyUserData::Cast( object_from_file->GetUserData( my_user_data_uuid ) );

    printf("ud_from_file->m_userdata_copycount = %d\n",ud_from_file->m_userdata_copycount);

    // Clean up
    delete object_from_file;
    object_from_file = 0;
  }

  ON::End();

  return 0;
}
Exemple #29
0
void log_file(string file, string text)
{
	write_file(LOG_DIR + file, text);
}
Exemple #30
0
/**
 *
 * @param argc
 * @param argv
 * @return
 */
int main(int argc, char* argv[])

{
	/* install interrupt handler */
	struct sigaction sa = {.sa_flags = 0, .sa_handler = sigint_handler};
	sigemptyset(&sa.sa_mask);
	if (sigaction(SIGINT, &sa, NULL) == -1) {
		msg_error("failed to install SIGINT handler\n");
		return -1;
	}

	/* command line options */
	static const struct option long_options[] = {
			 {"help", 0, 0, 'h'},
			 {"write", 0, 0, 'w'},
			 {"read", 0, 0, 'r'},
			 {0, 0, 0, 0},
	};
	static const char short_options[] = "hwr";

	/* parse command line options */
	int opt;
	opterr = 0;

	while ( (opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) {
		switch(opt) {
		case 'h':
			display_usage();
			exit (0);

		case 'w':
			copy_write = true;
			break;

		case 'r':
			copy_read = true;
			break;

		case '?':
			msg_error("unknown sp-noncached option: %c\n", optopt);
			display_usage();
			exit (-1);
		}
	}
	if (optind >= argc) {
		msg_error("Not enough parameters given.\n");
		display_usage();
		exit (1);
	}
	if ((copy_read && copy_write) || (!copy_read && !copy_write)) {
		msg_error("Either copy or write option must be given.\n");
		display_usage();
		exit (1);
	}
	if (copy_write) {
		write_file(argv[optind]);
	}
	else if (copy_read) {
		while (optind < argc) {
			read_file(argv[optind++]);
		}
	}
	if (copy_abort) {
		if (signal(SIGINT, SIG_DFL) == SIG_ERR) {
			exit (1);
		}
		raise(SIGINT);
		exit (1);
	}
	return 0;
}