Beispiel #1
0
void
ini_write(const char *path, const char *title, INITBL *tbl, UINT count, BOOL create)
{
	char	work[512];
	INITBL	*p;
	INITBL	*pterm;
	FILEH	fh;
	BOOL	set;

	fh = FILEH_INVALID;
	if (!create) {
		fh = file_open(path);
		if (fh != FILEH_INVALID)
			file_seek(fh, 0L, FSEEK_END);
	}
	if (fh == FILEH_INVALID) {
		fh = file_create(path);
		if (fh == FILEH_INVALID)
			return;
	}

	milstr_ncpy(work, "[", sizeof(work));
	milstr_ncat(work, title, sizeof(work));
	milstr_ncat(work, "]\n", sizeof(work));
	file_write(fh, work, strlen(work));

	p = tbl;
	pterm = tbl + count;
	while (p < pterm) {
		if (!(p->itemtype & INIFLAG_RO) || read_iniread_flag(p)) {
			work[0] = '\0';
			set = SUCCESS;
			switch (p->itemtype & INITYPE_MASK) {
			case INITYPE_STR:
				iniwrsetstr(work, sizeof(work), (char *)p->value);
				break;

			case INITYPE_BOOL:
				milstr_ncpy(work, (*((UINT8 *)p->value)) ? str_true : str_false, sizeof(work));
				break;

			case INITYPE_BITMAP:
				milstr_ncpy(work, inigetbmp((UINT8 *)p->value, p->arg) ? str_true : str_false, sizeof(work));
				break;

			case INITYPE_ARGH8:
				iniwrsetargh8(work, sizeof(work), p);
				break;

			case INITYPE_SINT8:
				g_snprintf(work, sizeof(work), "%d", *((char *)p->value));
				break;

			case INITYPE_SINT16:
				g_snprintf(work, sizeof(work), "%d", *((SINT16 *)p->value));
				break;

			case INITYPE_SINT32:
				g_snprintf(work, sizeof(work), "%d", *((SINT32 *)p->value));
				break;

			case INITYPE_UINT8:
				g_snprintf(work, sizeof(work), "%u", *((UINT8 *)p->value));
				break;

			case INITYPE_UINT16:
				g_snprintf(work, sizeof(work), "%u", *((UINT16 *)p->value));
				break;

			case INITYPE_UINT32:
				g_snprintf(work, sizeof(work), "%u", *((UINT32 *)p->value));
				break;

			case INITYPE_HEX8:
				g_snprintf(work, sizeof(work), "%x", *((UINT8 *)p->value));
				break;

			case INITYPE_HEX16:
				g_snprintf(work, sizeof(work), "%x", *((UINT16 *)p->value));
				break;

			case INITYPE_HEX32:
				g_snprintf(work, sizeof(work), "%x", *((UINT32 *)p->value));
				break;

			case INITYPE_KB:
				if (*(UINT8 *)p->value == KEY_KEY101)
					milstr_ncpy(work, "101", sizeof(work));
				else
					milstr_ncpy(work, "106", sizeof(work));
				break;

			case INITYPE_SNDDRV:
				g_snprintf(work, sizeof(work), "%s", snddrv_num2drv(*(UINT8 *)p->value));
				break;

			case INITYPE_INTERP:
				g_snprintf(work, sizeof(work), "%s", iniwrinterp(*(UINT8 *)p->value));
				break;

			default:
				set = FAILURE;
				break;
			}
			if (set == SUCCESS) {
				file_write(fh, p->item, strlen(p->item));
				file_write(fh, " = ", 3);
				file_write(fh, work, strlen(work));
				file_write(fh, "\n", 1);
			}
		}
		p++;
	}
	file_close(fh);
}
Beispiel #2
0
GRAPH * gr_read_pcx( const char * filename )
{
    PCXheader header ;
    file *    file ;
    int       width, height, x, y, p, count ;
    GRAPH *   bitmap ;
    uint8_t *   ptr, ch ;

    file = file_open( filename, "rb" ) ;
    if ( !file ) return NULL ;

    file_read( file, &header, sizeof( header ) ) ;

    /* Arrange the data for big-endian machines */
    ARRANGE_WORD( &header.Xmax );
    ARRANGE_WORD( &header.Xmin );
    ARRANGE_WORD( &header.Ymax );
    ARRANGE_WORD( &header.Ymin );
    ARRANGE_WORD( &header.BytesPerLine );
    ARRANGE_WORD( &header.PaletteInfo );
    ARRANGE_WORD( &header.HDpi );
    ARRANGE_WORD( &header.VDpi );
    ARRANGE_WORD( &header.HscreenSize );
    ARRANGE_WORD( &header.VscreenSize );

    width  = header.Xmax - header.Xmin + 1 ;
    height = header.Ymax - header.Ymin + 1 ;

    bitmap = bitmap_new( 0, width, height, ( header.BitsPerPixel == 8 ) ? 8 : 16 ) ;
    if ( !bitmap )
    {
        file_close( file );
        return NULL;
    }

    if ( width > header.BytesPerLine )
    {
        bitmap_destroy( bitmap );
        file_close( file );
        return NULL;
    }

    if ( header.BitsPerPixel == 8 )
    {
        for ( y = 0 ; y < height ; y++ )
            for ( p = 0 ; p < header.NPlanes ; p++ )
            {
                ptr = ( uint8_t * )bitmap->data + bitmap->pitch * y ;
                for ( x = 0 ; x < header.BytesPerLine ; )
                {
                    if ( file_read( file, &ch, 1 ) < 1 )
                    {
                        bitmap_destroy( bitmap );
                        file_close( file );
                        return NULL;
                    }
                    if (( ch & 0xC0 ) == 0xC0 )
                    {
                        count = ( ch & 0x3F ) ;
                        file_read( file, &ch, 1 ) ;
                    }
                    else
                    {
                        count = 1 ;
                    }
                    while ( count-- )
                    {
                        *ptr = ch ;
                        x++ ;
                        ptr += header.NPlanes ;
                    }
                }
            }

        if ( file_read( file, &ch, 1 ) == 1 && ch == 0x0c )
        {
            uint8_t colors[256 * 3] ;
            if ( file_read( file, colors, sizeof( colors ) ) )
            {
                bitmap->format->palette = pal_new_rgb(( uint8_t * )colors );
                pal_refresh( bitmap->format->palette );

                if ( !sys_pixel_format->palette )
                {
                    sys_pixel_format->palette = pal_new( bitmap->format->palette );
/*                    pal_use( bitmap->format->palette ); */
                    palette_changed = 1 ;
                }
            }
        }
    }
    else
    {
        bitmap_destroy( bitmap );
        file_close( file );
        return NULL;
    }

    bitmap->modified = 0 ;
    bitmap_analize( bitmap );

    return bitmap ;
}
Beispiel #3
0
/*
 * Hack -- Dump a character description file
 *
 * XXX XXX XXX Allow the "full" flag to dump additional info,
 * and trigger its usage from various places in the code.
 */
errr file_character(const char *path, bool full)
{
	int i, x, y;

	byte a;
	char c;

	ang_file *fp;

	struct store *st_ptr = &stores[STORE_HOME];

	char o_name[80];

	byte (*old_xchar_hook)(byte c) = Term.xchar_hook;

	char buf[1024];

	/* We use either ascii or system-specific encoding */
 	int encoding = OPT(xchars_to_file) ? SYSTEM_SPECIFIC : ASCII;

	/* Unused parameter */
	(void)full;


	/* Open the file for writing */
	fp = file_open(path, MODE_WRITE, FTYPE_TEXT);
	if (!fp) return (-1);

	/* Display the requested encoding -- ASCII or system-specific */
 	if (!OPT(xchars_to_file)) Term.xchar_hook = null;

	/* Begin dump */
	file_putf(fp, "  [%s Character Dump]\n\n", buildid);


	/* Display player */
	display_player(0);

	/* Dump part of the screen */
	for (y = 1; y < 23; y++)
	{
		/* Dump each row */
		for (x = 0; x < 79; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x, y, &a, &c));

			/* Dump it */
			buf[x] = c;
		}

		/* Back up over spaces */
		while ((x > 0) && (buf[x-1] == ' ')) --x;

		/* Terminate */
		buf[x] = '\0';

		/* End the row */
		x_file_putf(fp, encoding, "%s\n", buf);
	}

	/* Skip a line */
	file_putf(fp, "\n");

	/* Display player */
	display_player(1);

	/* Dump part of the screen */
	for (y = 11; y < 20; y++)
	{
		/* Dump each row */
		for (x = 0; x < 39; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x, y, &a, &c));

			/* Dump it */
			buf[x] = c;
		}

		/* Back up over spaces */
		while ((x > 0) && (buf[x-1] == ' ')) --x;

		/* Terminate */
		buf[x] = '\0';

		/* End the row */
		x_file_putf(fp, encoding, "%s\n", buf);
	}

	/* Skip a line */
	file_putf(fp, "\n");

	/* Dump part of the screen */
	for (y = 11; y < 20; y++)
	{
		/* Dump each row */
		for (x = 0; x < 39; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x + 40, y, &a, &c));

			/* Dump it */
			buf[x] = c;
		}

		/* Back up over spaces */
		while ((x > 0) && (buf[x-1] == ' ')) --x;

		/* Terminate */
		buf[x] = '\0';

		/* End the row */
		x_file_putf(fp, encoding, "%s\n", buf);
	}

	/* Skip some lines */
	file_putf(fp, "\n\n");


	/* If dead, dump last messages -- Prfnoff */
	if (p_ptr.is_dead)
	{
		i = messages_num();
		if (i > 15) i = 15;
		file_putf(fp, "  [Last Messages]\n\n");
		while (i-- > 0)
		{
			x_file_putf(fp, encoding, "> %s\n", message_str((s16b)i));
		}
		x_file_putf(fp, encoding, "\nKilled by %s.\n\n", p_ptr.died_from);
	}


	/* Dump the equipment */
	file_putf(fp, "  [Character Equipment]\n\n");
	for (i = INVEN_WIELD; i < ALL_INVEN_TOTAL; i++)
	{
		if (i == INVEN_TOTAL)
		{
			file_putf(fp, "\n\n  [Character Quiver]\n\n");
			continue;
		}
		object_desc(o_name, sizeof(o_name), &p_ptr.inventory[i],
				ODESC_PREFIX | ODESC_FULL);

		x_file_putf(fp, encoding, "%c) %s\n", index_to_label(i), o_name);
		if (p_ptr.inventory[i].kind)
			object_info_chardump(fp, &p_ptr.inventory[i], 5, 72);
	}

	/* Dump the inventory */
	file_putf(fp, "\n\n  [Character Inventory]\n\n");
	for (i = 0; i < INVEN_PACK; i++)
	{
		if (!p_ptr.inventory[i].kind) break;

		object_desc(o_name, sizeof(o_name), &p_ptr.inventory[i],
					ODESC_PREFIX | ODESC_FULL);

		x_file_putf(fp, encoding, "%c) %s\n", index_to_label(i), o_name);
		object_info_chardump(fp, &p_ptr.inventory[i], 5, 72);
	}
	file_putf(fp, "\n\n");


	/* Dump the Home -- if anything there */
	if (st_ptr.stock_num)
	{
		/* Header */
		file_putf(fp, "  [Home Inventory]\n\n");

		/* Dump all available items */
		for (i = 0; i < st_ptr.stock_num; i++)
		{
			object_desc(o_name, sizeof(o_name), &st_ptr.stock[i],
						ODESC_PREFIX | ODESC_FULL);
			x_file_putf(fp, encoding, "%c) %s\n", I2A(i), o_name);

			object_info_chardump(fp, &st_ptr.stock[i], 5, 72);
		}

		/* Add an empty line */
		file_putf(fp, "\n\n");
	}

	/* Dump character history */
	dump_history(fp);
	file_putf(fp, "\n\n");

	/* Dump options */
	file_putf(fp, "  [Options]\n\n");

	/* Dump options */
	for (i = OPT_BIRTH; i < OPT_BIRTH + N_OPTS_BIRTH; i++)
	{
		if (option_name(i))
		{
			file_putf(fp, "%-45s: %s (%s)\n",
			        option_desc(i),
			        op_ptr.opt[i] ? "yes" : "no ",
			        option_name(i));
		}
	}

	/* Skip some lines */
	file_putf(fp, "\n\n");

	/* Return to standard display */
 	Term.xchar_hook = old_xchar_hook;

	file_close(fp);


	/* Success */
	return (0);
}
Beispiel #4
0
/*
 * open device
 */
static int looper_open(struct block_device *bdev, fmode_t mode) {
  printk(KERN_INFO "looper: executing open");
  filp = file_open(filename, 0, 0);
  return 0;
}
/*
 * @brief Flush all packets in exception instance to files for debugging
 * @param
 *     None
 * @return
 *     This function returns KAL_SUCCESS always.
 */
KAL_INT32 eemcs_expt_flush()
{
    KAL_UINT32 pkts = 0;
    KAL_UINT32 i = 0;
//    struct sk_buff *skb = NULL;

	/* Flush all port skb from expt skb list  */
	for (i = 0; i < CCCI_PORT_NUM; i++) {
		pkts = atomic_read(&g_except_inst.port[i].pkt_cnt);

		/* No data in port */
		if (pkts == 0)
			continue;

		DBGLOG(EXPT, DBG, "free %d skb in port%d expt list", pkts, i);
		skb_queue_purge(&g_except_inst.port[i].skb_list);
		atomic_set(&g_except_inst.port[i].pkt_cnt, 0);
	}

	/* Flush all rx skb from expt skb list  */
	for (i = 0; i < SDIO_RX_Q_NUM; i++) {
		pkts = atomic_read(&g_except_inst.rxq[i].pkt_cnt);

		/* No data in port */
		if (pkts == 0)
			continue;

		DBGLOG(EXPT, DBG, "free %d skb in rxq%d expt list", pkts, i);
		skb_queue_purge(&g_except_inst.rxq[i].skb_list);
		atomic_set(&g_except_inst.rxq[i].pkt_cnt, 0);
	}

	/* Flush all tx skb from expt skb list  */
	for (i = 0; i < SDIO_TX_Q_NUM; i++) {
		pkts = atomic_read(&g_except_inst.txq[i].pkt_cnt);

		/* No data in port */
		if (pkts == 0)
			continue;

		DBGLOG(EXPT, DBG, "free %d skb in txq%d expt list", pkts, i);
		skb_queue_purge(&g_except_inst.txq[i].skb_list);
		atomic_set(&g_except_inst.txq[i].pkt_cnt, 0);
	}

#if 0    
    char log_file[NAME_MAX] = {0};
    struct file *fp = NULL;
    KAL_UINT32 pkts = 0;
    KAL_UINT32 i = 0, j = 0;
    struct sk_buff *skb = NULL;

    DEBUG_LOG_FUNCTION_ENTRY;
    /* Flush all DL packets to a file */
    for (i = 0; i < SDIO_RX_Q_NUM; i++) {
        pkts = atomic_read(&g_except_inst.rxq[i].pkt_cnt);
        DBGLOG(EXPT, DBG, "[EXPT] %d packets in DL SWQ %d", pkts, i);
        /* No data in Rx Q */
        if (pkts == 0)
            continue;

        sprintf(log_file, "%s/eemcs_expt_rx-%02d_%d.bak", EEMCS_EXCEPTION_LOG_PATH, g_except_inst.rxq[i].id, pkts);
        fp = file_open(log_file, O_RDWR | O_CREAT | O_TRUNC, 0777);
        if (fp == NULL) {
            DBGLOG(EXPT, ERR, "[EXPT] Failed to open file %s", log_file);
            continue;
        }
        // Write packets number
        file_write(fp, (char*)&pkts, sizeof(KAL_UINT32));
        /* Write each skb in list */
        for (j = 0; j < pkts; j++) {
            skb = skb_dequeue(&g_except_inst.rxq[i].skb_list);
            if (skb == NULL) {
                DBGLOG(EXPT, WAR, "[EXPT] Failed to read skb from RX list %d", i);
            } else {
                hif_dl_pkt_handle_complete(i);
                // Write skb data length
                file_write(fp, (char*)&skb->len, sizeof(unsigned int));
                // Write skb data
                file_write(fp, skb->data, skb->len);
                atomic_dec(&g_except_inst.rxq[i].pkt_cnt);
            }
        }
        file_close(fp);
        DBGLOG(EXPT, TRA, "[EXPT] All unhandled DL packets in Q are saved to %s", log_file);
    }
    /* Flush all UL packets to a file */
    for (i = 0; i < SDIO_TX_Q_NUM; i++) {
        pkts = atomic_read(&g_except_inst.txq[i].pkt_cnt);
        DBGLOG(EXPT, DBG, "[EXPT] %d packets in UL SWQ %d", pkts, i);
        /* No data in Tx Q */
        if (pkts == 0)
            continue;

        sprintf(log_file, "%s/eemcs_expt_tx-%02d_%d.bak", EEMCS_EXCEPTION_LOG_PATH, g_except_inst.txq[i].id, pkts);
        fp = file_open(log_file, O_RDWR | O_CREAT | O_TRUNC, 0777);
        if (fp == NULL) {
            DBGLOG(EXPT, ERR, "[EXPT] Failed to open file %s", log_file);
            continue;
        }
        // Write packets number
        file_write(fp, (char*)&pkts, sizeof(KAL_UINT32));
        /* Write each skb in list */
        for (j = 0; j < pkts; j++) {
            skb = skb_dequeue(&g_except_inst.txq[i].skb_list);
            if (skb == NULL) {
                DBGLOG(EXPT, WAR, "[EXPT] Failed to read skb from TX list %d", i);
            } else {
                // Write skb data length
                file_write(fp, (char*)&skb->len, sizeof(unsigned int));
                // Write skb data
                file_write(fp, skb->data, skb->len);
                atomic_dec(&g_except_inst.txq[i].pkt_cnt);
            }
        }
        file_close(fp);
        DBGLOG(EXPT, TRA, "[EXPT] All unhandled UL packets in Q are saved to %s", log_file);
    }
    /* Flush all port packets to a file */
    for (i = 0; i < CCCI_CDEV_NUM; i++) {
        pkts = atomic_read(&g_except_inst.port[i].pkt_cnt);
        DBGLOG(EXPT, DBG, "[EXPT] %d packets in port %d", pkts, i);
        /* No data in port */
        if (pkts == 0)
            continue;

        sprintf(log_file, "%s/eemcs_expt_port-%02d_%d.bak", EEMCS_EXCEPTION_LOG_PATH, i, pkts);
        fp = file_open(log_file, O_RDWR | O_CREAT, 0777);
        if (fp == NULL) {
            DBGLOG(EXPT, ERR, "[EXPT] Failed to open file %s", log_file);
            continue;
        }
        // Write packets number
        file_write(fp, (char*)&pkts, sizeof(KAL_UINT32));
        /* Write each skb in list */
        for (j = 0; j < pkts; j++) {
            skb = skb_dequeue(&g_except_inst.port[i].skb_list);
            if (skb == NULL) {
                DBGLOG(EXPT, WAR, "[EXPT] Failed to read skb from port list %d", i);
            } else {
                // Write skb data length
                file_write(fp, (char*)&skb->len, sizeof(unsigned int));
                // Write skb data
                file_write(fp, skb->data, skb->len);
                atomic_dec(&g_except_inst.port[i].pkt_cnt);
            }
        }
        file_close(fp);
        DBGLOG(EXPT, TRA, "[EXPT] All unhandled UL packets in port are saved to %s", log_file);
    }
    DBGLOG(EXPT, TRA, "[EXPT] eemcs_expt_flush() Finished !!");

    DEBUG_LOG_FUNCTION_LEAVE;
#else
    DEBUG_LOG_FUNCTION_ENTRY;
    DEBUG_LOG_FUNCTION_LEAVE;
#endif
    return KAL_SUCCESS;
}
Beispiel #6
0
static int bios_check(int flag)
{
	int i, err, count = 0, check_max = DEBUG_BIOS;
	char *fname;

	if (!flag) ui_popup_reset();

	video_copy_rect(show_frame, draw_frame, &full_rect, &full_rect);
	video_flip_screen(1);

	for (i = 0; i < BIOS_MAX; i++)
		bios_exist[i] = 0;

#ifdef ADHOC
	if (flag == 2)
	{
		neogeo_bios = -1;
		check_max = ASIA_AES;
	}
#endif

	for (i = 0; i <= check_max; i++)
	{
		if (file_open(bios_zip, NULL, bios_crc[i], NULL) >= 0)
		{
			count++;
			bios_exist[i] = 1;
			file_close();
		}
	}

	if (count == 0)
	{
		if (!flag)
			ui_popup(TEXT(BIOS_NOT_FOUND));
		else
			fatalerror(TEXT(BIOS_NOT_FOUND));
		return 0;
	}

	fname = (char *)sfix_name;
	if ((err = file_open(bios_zip, NULL, sfix_crc, fname)) >= 0)
	{
		file_close();
	}
	else
	{
		bios_error(sfix_name, err, flag);
		return 0;
	}

	fname = (char *)lorom_name;
	if ((err = file_open(bios_zip, NULL, lorom_crc, fname)) >= 0)
	{
		file_close();
	}
	else
	{
		bios_error(lorom_name, err, flag);
		return 0;
	}

	return 1;
}
Beispiel #7
0
/* Opens and returns a new file for the same inode as FILE.
   Returns a null pointer if unsuccessful. */
struct file *
file_reopen (struct file *file) 
{
  return file_open (inode_reopen (file->inode));
}
Beispiel #8
0
int main(int argc, char* argv[]) {
	// Declarations for getopt
	extern int optind;
	extern char* optarg;
	int ch;
	char* format = "hanf:l:";
	FILE* fd;
	char* filename = "Dimefile";
	char* output_file = "dime.log";
	bool execute = true;
	bool execute_all = false;
	bool output = false;

	// Part 2.2.1: Use getopt code to take input appropriately.
	while((ch = getopt(argc, argv, format)) != -1) {
		switch(ch) {
			case 'f':
				filename = strdup(optarg);
				break;
			case 'a': //execute all targets
				execute_all = true;
				break;
			case 'l': //change output
				output_file = strdup(optarg);
				output = true;
				
			case 'n':
				execute = false;
				break;
			case 'h':
				dime_usage(argv[0]);
				break;
			case '?':
				exit(0);
		}
	}
	argc -= optind;
	argv += optind;

	//Setup the logfile
	fd = file_open(output_file, "w+");//Always appends. Switch to w+ to overwrite
	int dup_result;
	if((dup_result = dup2(fileno(fd), fileno(DEBUG))) != fileno(DEBUG))
	{
		fprintf(DEBUG, "\nError in redirecting output [%d] \n", dup_result);
		fclose(fd);
		exit(0);
	}


	parse_file(filename);
	fprintf(DEBUG, "\n\n----------------DONE PARSING-------------\n\n");
	print_targets();

	//Execute depending on the flags	
	int i;
	if(execute_all)
	{
		TARGET* curr_tar = root;
		while(curr_tar != NULL)
		{
			fprintf(stdout, "\nExecuting Target[%s]\n", curr_tar->name);
			execute_target(curr_tar->name, execute);
			fprintf(stdout, "Execution Done..Maybe[%s]\n", curr_tar->name);
			curr_tar = curr_tar->next;
		}
	}
	else //Just execute a single target
	{
		//execute commands/print out commands for a given target	
		for(i = 0; i < argc; i++)
		{
			char* target = argv[i];
			if(find(target) == NULL) { fprintf(stdout, "Bad Target\n"); exit(0); }
			fprintf(stdout, "\nExecuting Target[%s]\n", target);
			execute_target(target, execute);
			fprintf(stdout, "\nExecution Done..Maybe[%s]\n", target);
			
		}
	}
	fprintf(DEBUG, "-------------------Exiting Main program---------------------\n");
	fclose(fd);
	return 0;
}
/* Opens a file and prepares a ftap struct.
   If "do_random" is TRUE, it opens the file twice; the second open
   allows the application to do random-access I/O without moving
   the seek offset for sequential I/O, which is used by Wireshark
   so that it can do sequential I/O to a capture file that's being
   written to as new packets arrive independently of random I/O done
   to display protocol trees for packets when they're selected. */
ftap* ftap_open_offline(const char *filename, int *err, char **err_info,
			gboolean do_random)
{
	int	fd;
	ws_statb64 statb;
	ftap	*fth;
	unsigned int	i;
	gboolean use_stdin = FALSE;
	gchar *extension;

	/* open standard input if filename is '-' */
	if (strcmp(filename, "-") == 0)
		use_stdin = TRUE;

	/* First, make sure the file is valid */
	if (use_stdin) {
		if (ws_fstat64(0, &statb) < 0) {
			*err = errno;
			return NULL;
		}
	} else {
		if (ws_stat64(filename, &statb) < 0) {
			*err = errno;
			return NULL;
		}
	}
	if (S_ISFIFO(statb.st_mode)) {
		/*
		 * Opens of FIFOs are allowed only when not opening
		 * for random access.
		 *
		 * XXX - currently, we do seeking when trying to find
		 * out the file type, so we don't actually support
		 * opening FIFOs.  However, we may eventually
		 * do buffering that allows us to do at least some
		 * file type determination even on pipes, so we
		 * allow FIFO opens and let things fail later when
		 * we try to seek.
		 */
		if (do_random) {
			*err = FTAP_ERR_RANDOM_OPEN_PIPE;
			return NULL;
		}
	} else if (S_ISDIR(statb.st_mode)) {
		/*
		 * Return different errors for "this is a directory"
		 * and "this is some random special file type", so
		 * the user can get a potentially more helpful error.
		 */
		*err = EISDIR;
		return NULL;
	} else if (! S_ISREG(statb.st_mode)) {
		*err = FTAP_ERR_NOT_REGULAR_FILE;
		return NULL;
	}

	/*
	 * We need two independent descriptors for random access, so
	 * they have different file positions.  If we're opening the
	 * standard input, we can only dup it to get additional
	 * descriptors, so we can't have two independent descriptors,
	 * and thus can't do random access.
	 */
	if (use_stdin && do_random) {
		*err = FTAP_ERR_RANDOM_OPEN_STDIN;
		return NULL;
	}

	errno = ENOMEM;
	fth = (ftap *)g_malloc0(sizeof(ftap));

	/* Open the file */
	errno = FTAP_ERR_CANT_OPEN;
	if (use_stdin) {
		/*
		 * We dup FD 0, so that we don't have to worry about
		 * a file_close of wth->fh closing the standard
		 * input of the process.
		 */
		fd = ws_dup(0);
		if (fd < 0) {
			*err = errno;
			g_free(fth);
			return NULL;
		}
#ifdef _WIN32
		if (_setmode(fd, O_BINARY) == -1) {
			/* "Shouldn't happen" */
			*err = errno;
			g_free(fth);
			return NULL;
		}
#endif
		if (!(fth->fh = file_fdopen(fd))) {
			*err = errno;
			ws_close(fd);
			g_free(fth);
			return NULL;
		}
	} else {
		if (!(fth->fh = file_open(filename))) {
			*err = errno;
			g_free(fth);
			return NULL;
		}
	}

	if (do_random) {
		if (!(fth->random_fh = file_open(filename))) {
			*err = errno;
			file_close(fth->fh);
			g_free(fth);
			return NULL;
		}
	} else
		fth->random_fh = NULL;

	/* initialization */
	fth->file_encap = FTAP_ENCAP_UNKNOWN;
	fth->subtype_sequential_close = NULL;
	fth->subtype_close = NULL;
    fth->priv = NULL;

    init_magic_number_open_routines();
	init_heuristic_open_info();
	if (fth->random_fh) {
		fth->fast_seek = g_ptr_array_new();

		file_set_random_access(fth->fh, FALSE, fth->fast_seek);
		file_set_random_access(fth->random_fh, TRUE, fth->fast_seek);
	}

	/* Try all file types that support magic numbers */
	for (i = 0; i < magic_number_open_routines_arr->len; i++) {
		/* Seek back to the beginning of the file; the open routine
		   for the previous file type may have left the file
		   position somewhere other than the beginning, and the
		   open routine for this file type will probably want
		   to start reading at the beginning.

		   Initialize the data offset while we're at it. */
		if (file_seek(fth->fh, 0, SEEK_SET, err) == -1) {
			/* I/O error - give up */
			ftap_close(fth);
			return NULL;
		}

		switch ((*magic_number_open_routines[i])(fth, err, err_info)) {

		case -1:
			/* I/O error - give up */
			ftap_close(fth);
			return NULL;

		case 0:
			/* No I/O error, but not that type of file */
			break;

		case 1:
			/* We found the file type */
			goto success;
		}
	}

	/* Does this file's name have an extension? */
	extension = get_file_extension(filename);
	if (extension != NULL) {
		/* Yes - try the heuristic types that use that extension first. */
		for (i = 0; i < heuristic_open_info_arr->len; i++) {
			/* Does this type use that extension? */
			if (heuristic_uses_extension(i, extension)) {
				/* Yes. */
				if (file_seek(fth->fh, 0, SEEK_SET, err) == -1) {
					/* I/O error - give up */
					g_free(extension);
					ftap_close(fth);
					return NULL;
				}

				switch ((*heuristic_open_info[i].open_routine)(fth,
				    err, err_info)) {

				case -1:
					/* I/O error - give up */
					g_free(extension);
					ftap_close(fth);
					return NULL;

				case 0:
					/* No I/O error, but not that type of file */
					break;

				case 1:
					/* We found the file type */
					g_free(extension);
					goto success;
				}
			}
		}

		/* Now try the ones that don't use it. */
		for (i = 0; i < heuristic_open_info_arr->len; i++) {
			/* Does this type use that extension? */
			if (!heuristic_uses_extension(i, extension)) {
				/* No. */
				if (file_seek(fth->fh, 0, SEEK_SET, err) == -1) {
					/* I/O error - give up */
					g_free(extension);
					ftap_close(fth);
					return NULL;
				}

				switch ((*heuristic_open_info[i].open_routine)(fth,
				    err, err_info)) {

				case -1:
					/* I/O error - give up */
					g_free(extension);
					ftap_close(fth);
					return NULL;

				case 0:
					/* No I/O error, but not that type of file */
					break;

				case 1:
					/* We found the file type */
					g_free(extension);
					goto success;
				}
			}
		}
		g_free(extension);
	} else {
		/* No - try all the heuristics types in order. */
		for (i = 0; i < heuristic_open_info_arr->len; i++) {
			if (file_seek(fth->fh, 0, SEEK_SET, err) == -1) {
				/* I/O error - give up */
				ftap_close(fth);
				return NULL;
			}

			switch ((*heuristic_open_info[i].open_routine)(fth,
			    err, err_info)) {

			case -1:
				/* I/O error - give up */
				ftap_close(fth);
				return NULL;

			case 0:
				/* No I/O error, but not that type of file */
				break;

			case 1:
				/* We found the file type */
				goto success;
			}
		}
	}

    /* Well, it's not one of the types of file we know about. */
	ftap_close(fth);
	*err = FTAP_ERR_FILE_UNKNOWN_FORMAT;
	return NULL;

success:
	fth->frame_buffer = (struct Buffer *)g_malloc(sizeof(struct Buffer));
	buffer_init(fth->frame_buffer, 1500);

	return fth;
}
Beispiel #10
0
void ini_write(const char *path, const char *title,
								const INITBL *tbl, UINT count, BOOL create) {

	FILEH		fh;
const INITBL	*p;
const INITBL	*pterm;
	BOOL		set;
	char		work[512];

	fh = FILEH_INVALID;
	if (!create) {
		fh = file_open(path);
		if (fh != FILEH_INVALID) {
			file_seek(fh, 0, FSEEK_END);
		}
	}
	if (fh == FILEH_INVALID) {
		fh = file_create(path);
	}
	if (fh == FILEH_INVALID) {
		return;
	}
	milstr_ncpy(work, "[", sizeof(work));
	milstr_ncat(work, title, sizeof(work));
	milstr_ncat(work, "]\r", sizeof(work));
	file_write(fh, work, strlen(work));

	p = tbl;
	pterm = tbl + count;
	while(p < pterm) {
		work[0] = '\0';
		set = SUCCESS;
		switch(p->itemtype) {
			case INITYPE_STR:
				iniwrsetstr(work, sizeof(work), (char *)p->value);
				break;

			case INITYPE_BOOL:
				milstr_ncpy(work, (*((BYTE *)p->value))?str_true:str_false,
																sizeof(work));
				break;

			case INITYPE_BYTEARG:
				iniwrsetarg8(work, sizeof(work), (BYTE *)p->value, p->size);
				break;

			case INITYPE_SINT8:
				SPRINTF(work, "%d", *((char *)p->value));
				break;

			case INITYPE_SINT16:
				SPRINTF(work, "%d", *((SINT16 *)p->value));
				break;

			case INITYPE_SINT32:
				SPRINTF(work, "%d", *((SINT32 *)p->value));
				break;

			case INITYPE_UINT8:
				SPRINTF(work, "%u", *((BYTE *)p->value));
				break;

			case INITYPE_UINT16:
				SPRINTF(work, "%u", *((UINT16 *)p->value));
				break;

			case INITYPE_UINT32:
				SPRINTF(work, "%u", *((UINT32 *)p->value));
				break;

			case INITYPE_HEX8:
				SPRINTF(work, "%x", *((BYTE *)p->value));
				break;

			case INITYPE_HEX16:
				SPRINTF(work, "%x", *((UINT16 *)p->value));
				break;

			case INITYPE_HEX32:
				SPRINTF(work, "%x", *((UINT32 *)p->value));
				break;

			default:
				set = FAILURE;
				break;
		}
		if (set == SUCCESS) {
			file_write(fh, p->item, strlen(p->item));
			file_write(fh, " = ", 3);
			file_write(fh, work, strlen(work));
			file_write(fh, "\r", 1);
		}
		p++;
	}
	file_close(fh);
}
/* Opens a file and prepares a wtap struct.
   If "do_random" is TRUE, it opens the file twice; the second open
   allows the application to do random-access I/O without moving
   the seek offset for sequential I/O, which is used by Wireshark
   so that it can do sequential I/O to a capture file that's being
   written to as new packets arrive independently of random I/O done
   to display protocol trees for packets when they're selected. */
wtap* wtap_open_offline(const char *filename, int *err, char **err_info,
			gboolean do_random)
{
	struct stat statb;
	wtap	*wth;
	unsigned int	i;
	gboolean use_stdin = FALSE;

	/* open standard input if filename is '-' */
	if (strcmp(filename, "-") == 0)
		use_stdin = TRUE;

	/* First, make sure the file is valid */
	if (use_stdin) {
		if (fstat(0, &statb) < 0) {
			*err = errno;
			return NULL;
		}
	} else {
		if (ws_stat(filename, &statb) < 0) {
			*err = errno;
			return NULL;
		}
	}
	if (S_ISFIFO(statb.st_mode)) {
		/*
		 * Opens of FIFOs are allowed only when not opening
		 * for random access.
		 *
		 * XXX - currently, we do seeking when trying to find
		 * out the file type, so we don't actually support
		 * opening FIFOs.  However, we may eventually
		 * do buffering that allows us to do at least some
		 * file type determination even on pipes, so we
		 * allow FIFO opens and let things fail later when
		 * we try to seek.
		 */
		if (do_random) {
			*err = WTAP_ERR_RANDOM_OPEN_PIPE;
			return NULL;
		}
	} else if (S_ISDIR(statb.st_mode)) {
		/*
		 * Return different errors for "this is a directory"
		 * and "this is some random special file type", so
		 * the user can get a potentially more helpful error.
		 */
		*err = EISDIR;
		return NULL;
	} else if (! S_ISREG(statb.st_mode)) {
		*err = WTAP_ERR_NOT_REGULAR_FILE;
		return NULL;
	}

	/*
	 * We need two independent descriptors for random access, so
	 * they have different file positions.  If we're opening the
	 * standard input, we can only dup it to get additional
	 * descriptors, so we can't have two independent descriptors,
	 * and thus can't do random access.
	 */
	if (use_stdin && do_random) {
		*err = WTAP_ERR_RANDOM_OPEN_STDIN;
		return NULL;
	}

	errno = ENOMEM;
	wth = (wtap *)g_malloc(sizeof(wtap));
	if (wth == NULL) {
		*err = errno;
		return NULL;
	}

	/* Open the file */
	errno = WTAP_ERR_CANT_OPEN;
	if (use_stdin) {
		/*
		 * We dup FD 0, so that we don't have to worry about
		 * an fclose or gzclose of wth->fh closing the standard
		 * input of the process.
		 */
		wth->fd = ws_dup(0);
#ifdef _WIN32
		_setmode(wth->fd, O_BINARY);
#endif
	} else
		wth->fd = ws_open(filename, O_RDONLY|O_BINARY, 0000 /* no creation so don't matter */);
	if (wth->fd < 0) {
		*err = errno;
		g_free(wth);
		return NULL;
	}
	if (!(wth->fh = filed_open(wth->fd, "rb"))) {
		*err = errno;
		ws_close(wth->fd);
		g_free(wth);
		return NULL;
	}

	if (do_random) {
		if (!(wth->random_fh = file_open(filename, "rb"))) {
			*err = errno;
			file_close(wth->fh);
			g_free(wth);
			return NULL;
		}
	} else
		wth->random_fh = NULL;

	/* initialization */
	wth->file_encap = WTAP_ENCAP_UNKNOWN;
	wth->data_offset = 0;
	wth->subtype_sequential_close = NULL;
	wth->subtype_close = NULL;
	wth->tsprecision = WTAP_FILE_TSPREC_USEC;
	wth->priv = NULL;

	init_open_routines();

	/* Try all file types */
	for (i = 0; i < open_routines_arr->len; i++) {
		/* Seek back to the beginning of the file; the open routine
		   for the previous file type may have left the file
		   position somewhere other than the beginning, and the
		   open routine for this file type will probably want
		   to start reading at the beginning.

		   Initialize the data offset while we're at it. */
		if (file_seek(wth->fh, 0, SEEK_SET, err) == -1) {
			/* I/O error - give up */
			if (wth->random_fh != NULL)
				file_close(wth->random_fh);
			file_close(wth->fh);
			g_free(wth);
			return NULL;
		}
		wth->data_offset = 0;

		switch ((*open_routines[i])(wth, err, err_info)) {

		case -1:
			/* I/O error - give up */
			if (wth->random_fh != NULL)
				file_close(wth->random_fh);
			file_close(wth->fh);
			g_free(wth);
			return NULL;

		case 0:
			/* No I/O error, but not that type of file */
			break;

		case 1:
			/* We found the file type */
			goto success;
		}
	}

	/* Well, it's not one of the types of file we know about. */
	if (wth->random_fh != NULL)
		file_close(wth->random_fh);
	file_close(wth->fh);
	g_free(wth);
	*err = WTAP_ERR_FILE_UNKNOWN_FORMAT;
	return NULL;

success:
	wth->frame_buffer = (struct Buffer *)g_malloc(sizeof(struct Buffer));
	buffer_init(wth->frame_buffer, 1500);
	return wth;
}
Beispiel #12
0
gpio *
libsoc_gpio_request (unsigned int gpio_id, gpio_mode mode)
{
  gpio *new_gpio;
  char tmp_str[STR_BUF];
  int shared = 0;

  if (mode != LS_GPIO_SHARED && mode != LS_GPIO_GREEDY && mode != LS_GPIO_WEAK)
    {
      libsoc_gpio_debug (__func__, gpio_id,
			 "mode was not set, or invalid,"
			 " setting mode to LS_GPIO_SHARED");
      mode = LS_GPIO_SHARED;
    }

  libsoc_gpio_debug (__func__, gpio_id, "requested gpio");

  sprintf (tmp_str, "/sys/class/gpio/gpio%d/value", gpio_id);

  if (file_valid (tmp_str))
    {
      libsoc_gpio_debug (__func__, gpio_id, "GPIO already exported");

      switch (mode)
	{
	case LS_GPIO_WEAK:
	  {
	    return NULL;
	  }

	case LS_GPIO_SHARED:
	  {
	    shared = 1;
	    break;
	  }

	default:
	  {
	    break;
	  }
	}
    }
  else
    {
      int fd = file_open ("/sys/class/gpio/export", O_SYNC | O_WRONLY);

      if (fd < 0)
	return NULL;

      sprintf (tmp_str, "%d", gpio_id);

      if (file_write (fd, tmp_str, STR_BUF) < 0)
	return NULL;

      if (file_close (fd))
	return NULL;

      sprintf (tmp_str, "/sys/class/gpio/gpio%d", gpio_id);

      if (!file_valid (tmp_str))
	{
	  libsoc_gpio_debug (__func__, gpio_id,
			     "gpio did not export correctly");
	  perror ("libsoc-gpio-debug");
	  return NULL;
	}
    }

  new_gpio = malloc (sizeof (gpio));
  if (new_gpio == NULL)
    return NULL;

  sprintf (tmp_str, "/sys/class/gpio/gpio%d/value", gpio_id);

  new_gpio->value_fd = file_open (tmp_str, O_SYNC | O_RDWR);

  if (new_gpio->value_fd < 0)
    {
      free(new_gpio);
      return NULL;
    }

  new_gpio->gpio = gpio_id;
  new_gpio->shared = shared;
  new_gpio->callback = NULL;

  // Set up a pollfd in case we are used for polling later
  new_gpio->pfd.fd = new_gpio->value_fd;
  new_gpio->pfd.events = POLLPRI;
  new_gpio->pfd.revents = 0;

  return new_gpio;
}
Beispiel #13
0
void load_elf(const char* fn, elf_info* info)
{
  file_t* file = file_open(fn, O_RDONLY, 0);
  if (IS_ERR_VALUE(file))
    goto fail;

  Elf_Ehdr eh;
  ssize_t ehdr_size = file_pread(file, &eh, sizeof(eh), 0);
  if (ehdr_size < (ssize_t)sizeof(eh) ||
      !(eh.e_ident[0] == '\177' && eh.e_ident[1] == 'E' &&
        eh.e_ident[2] == 'L'    && eh.e_ident[3] == 'F'))
    goto fail;

#if __riscv_xlen == 64
  assert(IS_ELF64(eh));
#else
  assert(IS_ELF32(eh));
#endif

#ifndef __riscv_compressed
  assert(!(eh.e_flags & EF_RISCV_RVC));
#endif

  size_t phdr_size = eh.e_phnum * sizeof(Elf_Phdr);
  if (phdr_size > info->phdr_size)
    goto fail;
  ssize_t ret = file_pread(file, (void*)info->phdr, phdr_size, eh.e_phoff);
  if (ret < (ssize_t)phdr_size)
    goto fail;
  info->phnum = eh.e_phnum;
  info->phent = sizeof(Elf_Phdr);
  Elf_Phdr* ph = (typeof(ph))info->phdr;

  // compute highest VA in ELF
  uintptr_t max_vaddr = 0;
  for (int i = 0; i < eh.e_phnum; i++)
    if (ph[i].p_type == PT_LOAD && ph[i].p_memsz)
      max_vaddr = MAX(max_vaddr, ph[i].p_vaddr + ph[i].p_memsz);
  max_vaddr = ROUNDUP(max_vaddr, RISCV_PGSIZE);

  // don't load dynamic linker at 0, else we can't catch NULL pointer derefs
  uintptr_t bias = 0;
  if (eh.e_type == ET_DYN)
    bias = RISCV_PGSIZE;

  info->entry = eh.e_entry + bias;
  int flags = MAP_FIXED | MAP_PRIVATE;
  for (int i = eh.e_phnum - 1; i >= 0; i--) {
    if(ph[i].p_type == PT_LOAD && ph[i].p_memsz) {
      uintptr_t prepad = ph[i].p_vaddr % RISCV_PGSIZE;
      uintptr_t vaddr = ph[i].p_vaddr + bias;
      if (vaddr + ph[i].p_memsz > info->brk_min)
        info->brk_min = vaddr + ph[i].p_memsz;
      int flags2 = flags | (prepad ? MAP_POPULATE : 0);
      int prot = get_prot(ph[i].p_flags);
      if (__do_mmap(vaddr - prepad, ph[i].p_filesz + prepad, prot | PROT_WRITE, flags2, file, ph[i].p_offset - prepad) != vaddr - prepad)
        goto fail;
      memset((void*)vaddr - prepad, 0, prepad);
      if (!(prot & PROT_WRITE))
        if (do_mprotect(vaddr - prepad, ph[i].p_filesz + prepad, prot))
          goto fail;
      size_t mapped = ROUNDUP(ph[i].p_filesz + prepad, RISCV_PGSIZE) - prepad;
      if (ph[i].p_memsz > mapped)
        if (__do_mmap(vaddr + mapped, ph[i].p_memsz - mapped, prot, flags|MAP_ANONYMOUS, 0, 0) != vaddr + mapped)
          goto fail;
    }
  }

  file_decref(file);
  return;

fail:
  panic("couldn't open ELF program: %s!", fn);
}
Beispiel #14
0
// Open req->req_path in mode req->req_omode, storing the Fd page and
// permissions to return to the calling environment in *pg_store and
// *perm_store respectively.
int
serve_open(envid_t envid, struct Fsreq_open *req,
	   void **pg_store, int *perm_store)
{
	char path[MAXPATHLEN];
	struct File *f;
	int fileid;
	int r;
	struct OpenFile *o;
//cprintf("serve_open 6666666\n");
	if (debug)
		cprintf("serve_open %08x %s 0x%x\n", envid, req->req_path, req->req_omode);
//cprintf("\nserve_open %08x %s 0x%x\n", envid, req->req_path, req->req_omode);
	// Copy in the path, making sure it's null-terminated
	memmove(path, req->req_path, MAXPATHLEN);
//cprintf("\nserve_open 8888888\n");
	path[MAXPATHLEN-1] = 0;
//cprintf("\nserve_open 77777777\n");
	// Find an open file ID
	if ((r = openfile_alloc(&o)) < 0) {
		if (debug)
			cprintf("openfile_alloc failed: %e", r);
		return r;
	}
	fileid = r;
	
	// Open the file
	if (req->req_omode & O_CREAT) {
		if ((r = file_create(path, &f)) < 0) {
			if (!(req->req_omode & O_EXCL) && r == -E_FILE_EXISTS)
				goto try_open;
			if (debug)
				cprintf("file_create failed: %e", r);
			return r;
		}
	} else {
try_open:
		//cprintf("Opening file for read in open_file\n");
		if ((r = file_open(path, &f)) < 0) {
			if (debug)
				cprintf("file_open failed: %e", r);
			return r;
		}
	}

	// Truncate
	if (req->req_omode & O_TRUNC) {
		if ((r = file_set_size(f, 0)) < 0) {
			if (debug)
				cprintf("file_set_size failed: %e", r);
			return r;
		}
	}

	// Save the file pointer
	o->o_file = f;

	// Fill out the Fd structure
	o->o_fd->fd_file.id = o->o_fileid;
	o->o_fd->fd_omode = req->req_omode & O_ACCMODE;
	o->o_fd->fd_dev_id = devfile.dev_id;
	o->o_mode = req->req_omode;
	
	if (debug)
		cprintf("sending success, page %08x\n", (uintptr_t) o->o_fd);

	// Share the FD page with the caller
	*pg_store = o->o_fd;
	*perm_store = PTE_P|PTE_U|PTE_W|PTE_SHARE;		//lab7
	return 0;
}
Beispiel #15
0
FILEH DOSIOCALL file_open_c(const OEMCHAR *path) {

    file_cpyname(curfilep, path,
                 NELEMENTS(curpath) - (int)(curfilep - curpath));
    return(file_open(curpath));
}
Beispiel #16
0
/* Take an html screenshot */
void html_screenshot(const char *name, int mode)
{
	int y, x;
	int wid, hgt;

	int a = TERM_WHITE;
	int oa = TERM_WHITE;
	int fg_colour = TERM_WHITE;
	int bg_colour = TERM_DARK;
	wchar_t c = L' ';

	const char *new_color_fmt = (mode == 0) ?
					"<font color=\"#%02X%02X%02X\" style=\"background-color: #%02X%02X%02X\">"
				 	: "[COLOR=\"#%02X%02X%02X\"]";
	const char *change_color_fmt = (mode == 0) ?
					"</font><font color=\"#%02X%02X%02X\" style=\"background-color: #%02X%02X%02X\">"
					: "[/COLOR][COLOR=\"#%02X%02X%02X\"]";
	const char *close_color_fmt = mode ==  0 ? "</font>" : "[/COLOR]";

	ang_file *fp;
	char buf[1024];


	path_build(buf, sizeof(buf), ANGBAND_DIR_USER, name);
	fp = file_open(buf, MODE_WRITE, FTYPE_TEXT);

	/* Oops */
	if (!fp)
	{
		plog_fmt("Cannot write the '%s' file!", buf);
		return;
	}

	/* Retrieve current screen size */
	Term_get_size(&wid, &hgt);

	if (mode == 0)
	{
		file_putf(fp, "<!DOCTYPE html><html><head>\n");
		file_putf(fp, "  <meta='generator' content='%s'>\n", buildid);
		file_putf(fp, "  <title>%s</title>\n", name);
		file_putf(fp, "</head>\n\n");
		file_putf(fp, "<body style='color: #fff; background: #000;'>\n");
		file_putf(fp, "<pre>\n");
	}
	else 
	{
		file_putf(fp, "[CODE][TT][BC=black][COLOR=white]\n");
	}

	/* Dump the screen */
	for (y = 0; y < hgt; y++)
	{
		for (x = 0; x < wid; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x, y, &a, &c));

			/* Set the foreground and background */
			fg_colour = a % MAX_COLORS;
			switch (a / MAX_COLORS)
			{
				case BG_BLACK:
					bg_colour = TERM_DARK;
					break;
				case BG_SAME:
					bg_colour = fg_colour;
					break;
				case BG_DARK:
					bg_colour = TERM_SHADE;
					break;
				default:
				assert((a >= BG_BLACK) && (a < BG_MAX * MAX_COLORS));
			}

			/* Color change */
			if (oa != a)
			{
				/* From the default white to another color */
				if (oa == TERM_WHITE)
				{
					file_putf(fp, new_color_fmt,
							angband_color_table[fg_colour][1],
							angband_color_table[fg_colour][2],
							angband_color_table[fg_colour][3],
							angband_color_table[bg_colour][1],
							angband_color_table[bg_colour][2],
							angband_color_table[bg_colour][3]);
				}

				/* From another color to the default white */
				else if (fg_colour == TERM_WHITE &&
						bg_colour == TERM_DARK)
				{
					file_putf(fp, close_color_fmt);
				}

				/* Change colors */
				else
				{
					file_putf(fp, change_color_fmt,
							angband_color_table[fg_colour][1],
							angband_color_table[fg_colour][2],
							angband_color_table[fg_colour][3],
							angband_color_table[bg_colour][1],
							angband_color_table[bg_colour][2],
							angband_color_table[bg_colour][3]);
				}

				/* Remember the last color */
				oa = a;
			}

			/* Write the character and escape special HTML characters */
			if (mode == 0) write_html_escape_char(fp, c);
			else
			{
				char mbseq[MB_LEN_MAX+1] = {0};
				wctomb(mbseq, c);
				file_putf(fp, "%s", mbseq);
			}
		}

		/* End the row */
		file_putf(fp, "\n");
	}

	/* Close the last font-color tag if necessary */
	if (oa != TERM_WHITE) file_putf(fp, close_color_fmt);

	if (mode == 0)
	{
		file_putf(fp, "</pre>\n");
		file_putf(fp, "</body>\n");
		file_putf(fp, "</html>\n");
	}
	else 
	{
		file_putf(fp, "[/COLOR][/BC][/TT][/CODE]\n");
	}

	/* Close it */
	file_close(fp);
}
Beispiel #17
0
/*
 * Attempt to save the player in a savefile
 */
bool savefile_save(const char *path)
{
        ang_file *file;
        int count = 0;
        char new_savefile[1024];
        char old_savefile[1024];

        /* New savefile */
        strnfmt(old_savefile, sizeof(old_savefile), "%s%u.old", path,Rand_simple(1000000));
        while (file_exists(old_savefile) && (count++ < 100)) {
                strnfmt(old_savefile, sizeof(old_savefile), "%s%u%u.old", path,Rand_simple(1000000),count);
        }
        count = 0;
        /* Make sure that the savefile doesn't already exist */
        /*safe_setuid_grab();
        file_delete(new_savefile);
        file_delete(old_savefile);
        safe_setuid_drop();*/

        /* Open the savefile */
        safe_setuid_grab();
        strnfmt(new_savefile, sizeof(new_savefile), "%s%u.new", path,Rand_simple(1000000));
        while (file_exists(new_savefile) && (count++ < 100)) {
                strnfmt(new_savefile, sizeof(new_savefile), "%s%u%u.new", path,Rand_simple(1000000),count);
        }
        file = file_open(new_savefile, MODE_WRITE, FTYPE_SAVE);
        safe_setuid_drop();

	if (file)
	{
		file_write(file, (char *) &savefile_magic, 4);
		file_write(file, (char *) &savefile_name, 4);

		character_saved = try_save(file);
		file_close(file);
	}

	if (character_saved)
	{
		bool err = FALSE;

		safe_setuid_grab();

		if (file_exists(savefile) && !file_move(savefile, old_savefile))
			err = TRUE;

		if (!err)
		{
			if (!file_move(new_savefile, savefile))
				err = TRUE;

			if (err)
				file_move(old_savefile, savefile);
			else
				file_delete(old_savefile);
		} 

		safe_setuid_drop();

                return err ? FALSE : TRUE;
        }

        /* Delete temp file if the save failed */
        if (file)
        {
                /* file is no longer valid, but it still points to a non zero
                 * value if the file was created above */
                safe_setuid_grab();
                file_delete(new_savefile);
                safe_setuid_drop();
        }
        return FALSE;
}
Beispiel #18
0
/*
 * Hack -- Dump a character description file
 *
 * XXX XXX XXX Allow the "full" flag to dump additional info,
 * and trigger its usage from various places in the code.
 */
errr file_character(const char *path, bool full)
{
	int i, x, y;

	int a;
	wchar_t c;

	ang_file *fp;

	struct store *st_ptr = &stores[STORE_HOME];

	char o_name[80];

	char buf[1024];
	char *p;

	/* Unused parameter */
	(void)full;


	/* Open the file for writing */
	fp = file_open(path, MODE_WRITE, FTYPE_TEXT);
	if (!fp) return (-1);

	/* Begin dump */
	file_putf(fp, "  [%s Character Dump]\n\n", buildid);


	/* Display player */
	display_player(0);

	/* Dump part of the screen */
	for (y = 1; y < 23; y++)
	{
		p = buf;
		/* Dump each row */
		for (x = 0; x < 79; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x, y, &a, &c));

			/* Dump it */
			p += wctomb(p, c);
		}

		/* Back up over spaces */
		while ((p > buf) && (p[-1] == ' ')) --p;

		/* Terminate */
		*p = '\0';

		/* End the row */
		x_file_putf(fp, "%s\n", buf);
	}

	/* Skip a line */
	file_putf(fp, "\n");

	/* Display player */
	display_player(1);

	/* Dump part of the screen */
	for (y = 11; y < 20; y++)
	{
		p = buf;
		/* Dump each row */
		for (x = 0; x < 39; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x, y, &a, &c));

			/* Dump it */
			p += wctomb(p, c);
		}

		/* Back up over spaces */
		while ((p > buf) && (p[-1] == ' ')) --p;

		/* Terminate */
		*p = '\0';

		/* End the row */
		x_file_putf(fp, "%s\n", buf);
	}

	/* Skip a line */
	file_putf(fp, "\n");

	/* Dump part of the screen */
	for (y = 11; y < 20; y++)
	{
		p = buf;
		/* Dump each row */
		for (x = 0; x < 39; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x + 40, y, &a, &c));

			/* Dump it */
			p += wctomb(p, c);
		}

		/* Back up over spaces */
		while ((p > buf) && (p[-1] == ' ')) --p;

		/* Terminate */
		*p = '\0';

		/* End the row */
		x_file_putf(fp, "%s\n", buf);
	}

	/* Skip some lines */
	file_putf(fp, "\n\n");


	/* If dead, dump last messages -- Prfnoff */
	if (p_ptr->is_dead)
	{
		i = messages_num();
		if (i > 15) i = 15;
		file_putf(fp, "  [Last Messages]\n\n");
		while (i-- > 0)
		{
			x_file_putf(fp, "> %s\n", message_str((s16b)i));
		}
		x_file_putf(fp, "\nKilled by %s.\n\n", p_ptr->died_from);
	}


	/* Dump the equipment */
	file_putf(fp, "  [Character Equipment]\n\n");
	for (i = INVEN_WIELD; i < ALL_INVEN_TOTAL; i++)
	{
		if (i == INVEN_TOTAL)
		{
			file_putf(fp, "\n\n  [Character Quiver]\n\n");
			continue;
		}
		object_desc(o_name, sizeof(o_name), &p_ptr->inventory[i],
				ODESC_PREFIX | ODESC_FULL);

		x_file_putf(fp, "%c) %s\n", index_to_label(i), o_name);
		if (p_ptr->inventory[i].kind)
			object_info_chardump(fp, &p_ptr->inventory[i], 5, 72);
	}

	/* Dump the inventory */
	file_putf(fp, "\n\n  [Character Inventory]\n\n");
	for (i = 0; i < INVEN_PACK; i++)
	{
		if (!p_ptr->inventory[i].kind) break;

		object_desc(o_name, sizeof(o_name), &p_ptr->inventory[i],
					ODESC_PREFIX | ODESC_FULL);

		x_file_putf(fp, "%c) %s\n", index_to_label(i), o_name);
		object_info_chardump(fp, &p_ptr->inventory[i], 5, 72);
	}
	file_putf(fp, "\n\n");


	/* Dump the Home -- if anything there */
	if (st_ptr->stock_num)
	{
		/* Header */
		file_putf(fp, "  [Home Inventory]\n\n");

		/* Dump all available items */
		for (i = 0; i < st_ptr->stock_num; i++)
		{
			object_desc(o_name, sizeof(o_name), &st_ptr->stock[i],
						ODESC_PREFIX | ODESC_FULL);
			x_file_putf(fp, "%c) %s\n", I2A(i), o_name);

			object_info_chardump(fp, &st_ptr->stock[i], 5, 72);
		}

		/* Add an empty line */
		file_putf(fp, "\n\n");
	}

	/* Dump character history */
	dump_history(fp);
	file_putf(fp, "\n\n");

	/* Dump options */
	file_putf(fp, "  [Options]\n\n");

	/* Dump options */
	for (i = 0; i < OPT_PAGE_MAX - 1; i++) {
		int j;
		const char *title = "";
		switch (i) {
			case 0: title = "Interface"; break;
			case 1: title = "Warning"; break;
			case 2: title = "Birth"; break;
		}

		file_putf(fp, "  [%s]\n\n", title);
		for (j = 0; j < OPT_PAGE_PER; j++) {
			int opt = option_page[i][j];
			if (!option_name(opt)) continue;

			file_putf(fp, "%-45s: %s (%s)\n",
			        option_desc(opt),
			        op_ptr->opt[opt] ? "yes" : "no ",
			        option_name(opt));
		}

		/* Skip some lines */
		file_putf(fp, "\n");
	}

	file_close(fp);


	/* Success */
	return (0);
}
Beispiel #19
0
bool LoadRTLights( void )
{
    FILE	*	fp;
    int8_t		Filename[ 256 ];
    char	*	NewExt = ".RTL";
    u_int32_t		MagicNumber;
    u_int32_t		VersionNumber;
    int			j;
    RT_LIGHT *	light;
    u_int16_t		type;
    XLIGHT	*	xlight;
    RT_FIXED_LIGHT		*fixed;
    RT_PULSING_LIGHT	*pulse;
    RT_FLICKERING_LIGHT	*flicker;
    RT_SPOT_LIGHT		*spot;

    Change_Ext( &LevelNames[ LevelNum ][ 0 ], &Filename[ 0 ], NewExt );


    fp = file_open( &Filename[ 0 ], "rb" );

    if( fp )
    {
        fread_var( fp, MagicNumber );
        fread_var( fp, VersionNumber );

        if( ( MagicNumber != MAGIC_NUMBER ) || ( VersionNumber != RTL_VERSION_NUMBER  ) )
        {
            fclose( fp );
            Msg( "LoadRTLights() Incompatible Real-Time Lights (.RTL) file %s", &Filename[ 0 ] );
            return( false );
        }

        fread_var( fp, rt_lights );

        if ( rt_lights )
        {
            rt_light = (RT_LIGHT *) calloc( rt_lights, sizeof( RT_LIGHT ) );
            if ( !rt_light )
            {
                fclose( fp );
                Msg( "LoadRTLights() malloc failed for %d Real-Time Lights ", rt_lights );
                rt_lights = 0;
                return false ;
            }

            for ( j = 0; j < rt_lights; j++ )
            {
                rt_light[ j ].xlight = (u_int16_t) -1;
                rt_light[ j ].enabled = false;
            }

            for ( j = 0; j < rt_lights; j++ )
            {
                light = &rt_light[ j ];
                fread_var( fp, type );
                light->type = (LIGHTTYPE) type;
                fread_var( fp, light->group );
                fread_var( fp, light->pos.x );
                fread_var( fp, light->pos.y );
                fread_var( fp, light->pos.z );
                fread_var( fp, light->range );
                fread_var( fp, light->r );
                fread_var( fp, light->g );
                fread_var( fp, light->b );
                light->r *= 255.0F;
                light->g *= 255.0F;
                light->b *= 255.0F;
                fread_var( fp, type );
                light->generation_type = (GENTYPE) type;
                fread_var( fp, light->generation_delay );
                switch ( light->type )
                {
                case LIGHT_FIXED:
                    fixed = &light->fixed;
                    fread_var( fp, type );
                    fixed->on_type = (PULSETYPE) type;
                    fread_var( fp, type );
                    fixed->off_type = (PULSETYPE) type;
                    fread_var( fp, fixed->on_time );
                    fread_var( fp, fixed->off_time );
                    fixed->on_time *= ANIM_SECOND;
                    fixed->off_time *= ANIM_SECOND;
                    break;
                case LIGHT_PULSING:
                    pulse = &light->pulse;
                    fread_var( fp, type );
                    pulse->type = (PULSETYPE) type;
                    fread_var( fp, pulse->on_time );
                    fread_var( fp, pulse->stay_on_time );
                    fread_var( fp, pulse->off_time );
                    fread_var( fp, pulse->stay_off_time );
                    pulse->on_time *= ANIM_SECOND;
                    pulse->stay_on_time *= ANIM_SECOND;
                    pulse->off_time *= ANIM_SECOND;
                    pulse->stay_off_time *= ANIM_SECOND;
                    pulse->stay_on_point = pulse->on_time + pulse->stay_on_time;
                    pulse->off_point = pulse->stay_on_point + pulse->off_time;
                    pulse->total_time = pulse->off_point + pulse->stay_off_time;
                    break;
                case LIGHT_FLICKERING:
                    flicker = &light->flicker;
                    fread_var( fp, flicker->stay_on_chance );
                    fread_var( fp, flicker->stay_off_chance );
                    fread_var( fp, flicker->stay_on_time );
                    fread_var( fp, flicker->stay_off_time );
                    flicker->stay_on_time *= ANIM_SECOND;
                    flicker->stay_off_time *= ANIM_SECOND;
                    break;
                case LIGHT_SPOT:
                    spot = &light->spot;
                    fread_var( fp, spot->dir.x );
                    fread_var( fp, spot->dir.y );
                    fread_var( fp, spot->dir.z );
                    fread_var( fp, spot->up.x );
                    fread_var( fp, spot->up.y );
                    fread_var( fp, spot->up.z );
                    fread_var( fp, spot->cone );
                    fread_var( fp, spot->rotation_period );
                    if ( spot->rotation_period )
                        spot->rotation_speed = 2 * PI / ( spot->rotation_period * ANIM_SECOND );
                    else
                        spot->rotation_speed = 0.0F;
                    spot->angle = 0.0F;
                    break;
                }
                light->now_time = 0.0F;
                switch ( light->generation_type )
                {
                case GENTYPE_Initialised:
                    light->enabled = true;
                    light->state = STATE_TURNING_ON;
                    light->delay = 0.0F;
                    break;
                case GENTYPE_Time:
                    light->enabled = false;
                    light->state = STATE_OFF;
                    light->delay = light->generation_delay * ANIM_SECOND;
                    break;
                case GENTYPE_Trigger:
                    light->enabled = false;
                    light->state = STATE_OFF;
                    light->delay = 0.0F;
                    break;
                }
                light->xlight = FindFreeXLight();
                if ( light->xlight != (u_int16_t) -1 )
                {
                    xlight = &XLights[ light->xlight ];
                    xlight->Pos = light->pos;
                    xlight->Size = light->range;
                    xlight->SizeCount = 0.0F;
                    xlight->r = light->r;
                    xlight->g = light->g;
                    xlight->b = light->b;
                    xlight->Group = light->group;
                    xlight->Visible = false;
                    if ( light->type == LIGHT_SPOT )
                    {
                        xlight->Type = SPOT_LIGHT;
                        xlight->CosArc = (float) cos( D2R( light->spot.cone * 0.5F ) );
                    }
                }
            }
        }
        fclose( fp );
    }

    return true;
}
Beispiel #20
0
int
open_history( const char *str_name1, const char *str_name2 )
{
#if defined(NO_LOGGING)
  int iret;

  iret = record_close( &record_game );
  if ( iret < 0 ) { return -1; }

  iret = record_open( &record_game, "game.csa", mode_read_write,
		      str_name1, str_name2 );
  if ( iret < 0 ) { return -1; }

  return 1;
#else
  FILE *pf;
  int i, iret;
  char str_file[SIZE_FILENAME];
  
  if ( record_game.pf != NULL && ! record_game.moves )
    {
      record_game.str_name1[0] = '\0';
      record_game.str_name2[0] = '\0';

      if ( str_name1 )
	{
	  strncpy( record_game.str_name1, str_name1, SIZE_PLAYERNAME-1 );
	  record_game.str_name1[SIZE_PLAYERNAME-1] = '\0';
	}
      
      if ( str_name2 )
	{
	  strncpy( record_game.str_name2, str_name2, SIZE_PLAYERNAME-1 );
	  record_game.str_name2[SIZE_PLAYERNAME-1] = '\0';
	}
      return 1;
    }

  if ( ( ( game_status & flag_nonewlog )
#  if defined(USI)
	 ||  usi_mode != usi_off
#  endif
	 ) && 0 <= record_num )
    {
      iret = record_close( &record_game );
      if ( iret < 0 ) { return -1; }
      
      snprintf( str_file, SIZE_FILENAME, "%s/game%03d.csa",
		str_dir_logs, record_num );
      iret = record_open( &record_game, str_file, mode_read_write,
			  str_name1, str_name2 );
      if ( iret < 0 ) { return -1; }
    }
  else
    {
      iret = file_close( pf_log );
      if ( iret < 0 ) { return -1; }
      
      iret = record_close( &record_game );
      if ( iret < 0 ) { return -1; }
      
      for ( i = 0; i < 999; i++ )
	{
	  snprintf( str_file, SIZE_FILENAME, "%s/game%03d.csa",
		    str_dir_logs, i );
	  pf = file_open( str_file, "r" );
	  if ( pf == NULL ) { break; }
	  iret = file_close( pf );
	  if ( iret < 0 ) { return -1; }
	}
      record_num = i;
      
      snprintf( str_file, SIZE_FILENAME, "%s/n%03d.log",
		str_dir_logs, i );
      pf_log = file_open( str_file, "w" );
      if ( pf_log == NULL ) { return -1; }
      
      snprintf( str_file, SIZE_FILENAME, "%s/game%03d.csa",
		str_dir_logs, i );
      iret = record_open( &record_game, str_file, mode_read_write,
			  str_name1, str_name2 );
      if ( iret < 0 ) { return -1; }
    }
  
  return 1;
#endif
}
Beispiel #21
0
status_t BnMonzax::onTransact(
        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{

    status_t status = BBinder::onTransact(code, data, reply, flags);
    if (status != UNKNOWN_TRANSACTION) {
        return status;
    }
    if (! reply) {
        ALOGE("Monzax::onTransact(): null reply parcel received.");
        return BAD_VALUE;
    }

    IPCThreadState *ipc = IPCThreadState::self();
    const int pid = ipc->getCallingPid();
    const int uid = ipc->getCallingUid();

    // dispatch to the appropriate method based on the transaction code.
    switch(code){
        case FILE_OPEN:
            {
                CHECK_INTERFACE(IMonzax, data, reply);
                ALOGI("BnMonzax: onTransact: FILE_OPEN"
                    "client to access MonzaxService from uid=%d pid=%d code: %d",
                    uid, pid, code);
                char *pName = (char *) data.readCString();
                int ret = file_open(pName);
                reply->writeInt32(ret);
                return NO_ERROR;
            }
            break;
        case FILE_CLOSE:
            {
                ALOGI("BnMonzax: onTransact: FILE_CLOSE"
                    "client to access MonzaxService from uid=%d pid=%d code: %d",
                    uid, pid, code);
                CHECK_INTERFACE(IMonzax, data, reply);
                int fd = data.readInt32();
                int ret = file_close(fd);
                reply->writeInt32(ret);
                return NO_ERROR;
            }
            break;
        case FILE_SEEK:
            {
                CHECK_INTERFACE(IMonzax, data, reply);
                int ret;

                int fd = data.readInt32();
                int offset = data.readInt32();
                int whence = data.readInt32();
                ret = file_seek(fd, offset, whence);
                reply->writeInt32(ret);
                return NO_ERROR;
            }
            break;
        case FILE_READ:
            {
                CHECK_INTERFACE(IMonzax, data, reply);
                char *pReadBuf;
                int ret;

                int fd = data.readInt32();
                int length = data.readInt32();
                pReadBuf = (char*) malloc(sizeof(char) * length);
                if (pReadBuf == NULL) {
                    ret = -1;
                    reply->writeInt32(ret);
                    ALOGE("onTransact File_Read malloc result failed.\n");
                    goto err_read;
                }
                ret = file_read(fd, pReadBuf, length);
                reply->writeInt32(ret);
                if(ret >0){
                    reply->write((char *) pReadBuf, ret);
                }
                free(pReadBuf);
                pReadBuf = NULL;
                return NO_ERROR;
err_read:
                ALOGE("onTransact File_Read ,ret =%d out\n",  (int)ret);
                return ret;
            }
            break;
        case FILE_WRITE:
            {
                CHECK_INTERFACE(IMonzax, data, reply);
                int ret;
                int fd = data.readInt32();
                int length = data.readInt32();
                char *pWriteBuf = (char*) malloc(sizeof(char) * length);
                if (pWriteBuf == NULL) {
                    ret = -1;
                    reply->writeInt32(ret);
                    ALOGE("onTransact File_Write malloc result failed.\n");
                    goto err_write;
                }
                if(length > 0){
                    const char *input = (const char *) data.readInplace(length);
                    if (input)
                        memcpy(pWriteBuf, input, length);
                    else {
                        ALOGE("onTransact File_Write length is 0, failed.\n");
                        memset(pWriteBuf, 0, length);
                        length = 0;
                    }
                } else
                    memset(pWriteBuf, 0, length);

                ret = file_write(fd, (char *)pWriteBuf, length);
                reply->writeInt32(ret);
                free(pWriteBuf);
                pWriteBuf = NULL;
                return NO_ERROR;
err_write:
                ALOGE("onTransact File_Write ,ret =%d out\n",  (int)ret);
                return ret;
            }
            break;
        default:
            return BBinder::onTransact(code, data, reply, flags);
    }
}
Beispiel #22
0
/*
 * Remove old lines from pref files
 *
 * If you are using setgid, make sure privileges were raised prior
 * to calling this.
 */
static void remove_old_dump(const char *cur_fname, const char *mark)
{
	bool between_marks = FALSE;
	bool changed = FALSE;

	char buf[1024];

	char start_line[1024];
	char end_line[1024];

	char new_fname[1024];

	ang_file *new_file;
	ang_file *cur_file;


	/* Format up some filenames */
	strnfmt(new_fname, sizeof(new_fname), "%s.new", cur_fname);

	/* Work out what we expect to find */
	strnfmt(start_line, sizeof(start_line), "%s begin %s",
			dump_separator, mark);
	strnfmt(end_line,   sizeof(end_line),   "%s end %s",
			dump_separator, mark);



	/* Open current file */
	cur_file = file_open(cur_fname, MODE_READ, -1);
	if (!cur_file) return;

	/* Open new file */
	new_file = file_open(new_fname, MODE_WRITE, FTYPE_TEXT);
	if (!new_file)
	{
		msg("Failed to create file %s", new_fname);
		return;
	}

	/* Loop for every line */
	while (file_getl(cur_file, buf, sizeof(buf)))
	{
		/* If we find the start line, turn on */
		if (!strcmp(buf, start_line))
		{
			between_marks = TRUE;
		}

		/* If we find the finish line, turn off */
		else if (!strcmp(buf, end_line))
		{
			between_marks = FALSE;
			changed = TRUE;
		}

		if (!between_marks)
		{
			/* Copy orginal line */
			file_putf(new_file, "%s\n", buf);
		}
	}

	/* Close files */
	file_close(cur_file);
	file_close(new_file);

	/* If there are changes, move things around */
	if (changed)
	{
		char old_fname[1024];
		strnfmt(old_fname, sizeof(old_fname), "%s.old", cur_fname);

		if (file_move(cur_fname, old_fname))
		{
			file_move(new_fname, cur_fname);
			file_delete(old_fname);
		}
	}

	/* Otherwise just destroy the new file */
	else
	{
		file_delete(new_fname);
	}
}
Beispiel #23
0
int
fortune_build (
    const char *infile,                 /*  Name of file to compress         */
    const char *outfile,                /*  Output file, created             */
    Bool        compress)               /*  Compress yes/no                  */
{
    char
        line [LINE_MAX + 1];            /*  Line from input file             */
    int
        block_nbr;
    long
        offset;

    inbuf   = mem_alloc (BLOCK_SIZE);
    outbuf  = mem_alloc (BLOCK_SIZE);
    sizes   = mem_alloc (MAX_BLOCKS * sizeof (int));
    input   = file_open (infile, 'r');
    scratch = ftmp_open (NULL);

    if (!inbuf || !outbuf || !sizes || !input || !scratch)
      {
        mem_free (inbuf);
        mem_free (outbuf);
        mem_free (sizes);
        return (-1);
      }

    nbr_blocks = 0;
    nbr_paras  = 0;                     /*  Number of paragraphs in block    */
    insize     = 2;                     /*  Leave room for nbr_paras         */

    while (file_read (input, line))
      {
        if (streq (line, "%%"))
            have_end_of_paragraph (compress);
        else
          {
            memcpy (inbuf + insize, line, strlen (line));
            insize += strlen (line);
            inbuf [insize++] = '\n';
          }
      }
    have_end_of_paragraph (compress);
    if (nbr_paras)
        have_end_of_block (compress);

    fclose (input);                     /*  Finished with input file         */

    output = fopen (outfile, "wb");
    fprintf (output, "IFF%s -- http://www.imatix.com/ --\n%c",
                     compress? "CMP": "TXT", 26);

    output_dbyte = htons (nbr_blocks);
    ASSERT (fwrite (&output_dbyte, 2, 1, output));
    offset = ftell (output) + nbr_blocks * 4;

    for (block_nbr = 0; block_nbr < nbr_blocks; block_nbr++)
      {
        output_qbyte = htonl (offset);
        ASSERT (fwrite (&output_qbyte, 4, 1, output));
        offset += sizes [block_nbr];
      }
    fseek (scratch, 0, SEEK_SET);       /*  Back to start of scratch file    */
    while ((outsize = fread (outbuf, 1, BLOCK_SIZE, scratch)) != 0)
        ASSERT (fwrite (outbuf, 1, outsize, output));

    file_close (output);
    ftmp_close (scratch);
    mem_free (sizes);
    mem_free (inbuf);
    mem_free (outbuf);

    return (0);                         /*  No errors                        */
}
Beispiel #24
0
int do_copy(struct file_s *src, struct file_s *dst)
{
	int crc_match = 0;
	int fdsrc, fddst;
	struct stat fssrc,fsdst;
	char *msrc, *mdst;
	if (src == NULL||dst == NULL) return;
#ifdef DEBUG
	printf("'%s'(%d)->'%s'(%d)\n",src->path,src->isdir,dst->path,dst->isdir);
#endif
	fdsrc = file_open(src->path, &fssrc, OPEN_SRC);
	fddst = file_open(dst->path, &fsdst, OPEN_DST);

	msrc = mmap(NULL, fssrc.st_size, PROT_READ, MAP_SHARED, fdsrc, 0);
	if (msrc == MAP_FAILED) {
		perror("mmap src");
		exit(-1);
	}
	if (ftruncate(fddst,fssrc.st_size) != 0)
	{
		perror("ftruncate");
	}
	mdst = mmap(NULL, fssrc.st_size, PROT_WRITE, MAP_SHARED, fddst, 0);
	if (mdst == MAP_FAILED) {
		perror("mmap dst");
		exit(-1);
	}

	long long remain_size = fssrc.st_size;

	char *tmp_msrc, *tmp_mdst;
	tmp_msrc = msrc;
	tmp_mdst = mdst;
	while (remain_size--)
	{
		*tmp_mdst++ = *tmp_msrc++;
	}

	// destroy the data if ERRORTEST defined
	// for test a crc
#ifdef ERRORTEST
	mdst[0] = ~mdst[0];
#endif

	if (msync(mdst,fssrc.st_size,MS_SYNC) != 0)
	{
		perror("msync");
		exit(-1);
	}
	
	munmap(mdst, fssrc.st_size);

	if (option.paranoid)
	{
		uint32_t src_crc = file_crc32c(fdsrc,fssrc.st_size,msrc);
		uint32_t dst_crc = file_crc32c(fddst,fssrc.st_size,NULL);
		if (src_crc == dst_crc)
			crc_match = 1;
		else
			crc_match = -1;
	}

	munmap(msrc, fssrc.st_size);
	close(fdsrc);
	close(fddst);
	return crc_match;
}
Beispiel #25
0
static int blockset_open_file(struct blockstore *blockStore,
                              struct blockset *bs) {
  uint64 offset;
  mtime_t ts;
  int res;

  res = file_open(bs->filename, 0 /* R/O */, 0 /* !unbuf */, &bs->desc);
  if (res) {
    return res;
  }

  bs->filesize = file_getsize(bs->desc);
  if (bs->filesize < 0) {
    return errno;
  }

  if (bs->filesize > 0) {
    char *s = print_size(bs->filesize);
    char *name = file_getname(bs->filename);
    Log(LGPFX " reading file %s -- %s -- %llu headers.\n", name, s,
        bs->filesize / sizeof(btc_block_header));
    free(name);
    free(s);
  }

  ts = time_get();
  offset = 0;
  while (offset < bs->filesize) {
    btc_block_header buf[10000];
    size_t numRead;
    size_t numBytes;
    int numHeaders;
    int i;

    numBytes = MIN(bs->filesize - offset, sizeof buf);

    res = file_pread(bs->desc, offset, buf, numBytes, &numRead);
    if (res != 0) {
      break;
    }

    if (btc->stop != 0) {
      res = 1;
      NOT_TESTED();
      break;
    }

    numHeaders = numRead / sizeof(btc_block_header);
    for (i = 0; i < numHeaders; i++) {
      struct blockentry *be;
      uint256 hash;

      be = blockstore_alloc_entry(buf + i);
      be->written = 1;
      hash256_calc(buf + i, sizeof buf[0], &hash);

      if (!blockstore_validate_chkpt(&hash, blockStore->height + 1)) {
        return 1;
      }

      blockstore_add_entry(blockStore, be, &hash);

      if (i == numHeaders - 1) {
        bitcui_set_status("loading headers .. %llu%%",
                          (offset + numBytes) * 100 / bs->filesize);
      }
      if (i == numHeaders - 1 ||
          (numBytes < sizeof buf && i > numHeaders - 256)) {
        bitcui_set_last_block_info(&hash, blockStore->height,
                                   be->header.timestamp);
      }
    }

    offset += numRead;
  }

  ts = time_get() - ts;

  char hashStr[80];
  char *latStr;

  uint256_snprintf_reverse(hashStr, sizeof hashStr, &blockStore->best_hash);
  Log(LGPFX " loaded blocks up to %s\n", hashStr);
  latStr = print_latency(ts);
  Log(LGPFX " this took %s\n", latStr);
  free(latStr);

  return res;
}
Beispiel #26
0
void log_setOutputFile(const char* filename) {
	logger.logFileFd = file_open(filename);
}
Beispiel #27
0
/*
 * Recursive file perusal.
 *
 * Return false on "?", otherwise true.
 *
 * This function could be made much more efficient with the use of "seek"
 * functionality, especially when moving backwards through a file, or
 * forwards through a file by less than a page at a time.  XXX XXX XXX
 */
bool show_file(const char *name, const char *what, int line, int mode)
{
	int i, k, n;

	struct keypress ch;

	/* Number of "real" lines passed by */
	int next = 0;

	/* Number of "real" lines in the file */
	int size;

	/* Backup value for "line" */
	int back = 0;

	/* This screen has sub-screens */
	bool menu = false;

	/* Case sensitive search */
	bool case_sensitive = false;

	/* Current help file */
	ang_file *fff = null;

	/* Find this string (if any) */
	char *find = null;

	/* Jump to this tag */
	const char *tag = null;

	/* Hold a string to find */
	char finder[80] = "";

	/* Hold a string to show */
	char shower[80] = "";

	/* Filename */
	char filename[1024];

	/* Describe this thing */
	char caption[128] = "";

	/* Path buffer */
	char path[1024];

	/* General buffer */
	char buf[1024];

	/* Lower case version of the buffer, for searching */
	char lc_buf[1024];

	/* Sub-menu information */
	char hook[26][32];

	int wid, hgt;



	/* Wipe the hooks */
	for (i = 0; i < 26; i++) hook[i][0] = '\0';

	/* Get size */
	Term_get_size(&wid, &hgt);

	/* Copy the filename */
	my_strcpy(filename, name, sizeof(filename));

	n = strlen(filename);

	/* Extract the tag from the filename */
	for (i = 0; i < n; i++)
	{
		if (filename[i] == '#')
		{
			filename[i] = '\0';
			tag = filename + i + 1;
			break;
		}
	}

	/* Redirect the name */
	name = filename;


	/* Hack XXX XXX XXX */
	if (what)
	{
		my_strcpy(caption, what, sizeof(caption));

		my_strcpy(path, name, sizeof(path));
		fff = file_open(path, MODE_READ, -1);
	}

	/* Look in "help" */
	if (!fff)
	{
		strnfmt(caption, sizeof(caption), "Help file '%s'", name);

		path_build(path, sizeof(path), ANGBAND_DIR_HELP, name);
		fff = file_open(path, MODE_READ, -1);
	}

	/* Look in "info" */
	if (!fff)
	{
		strnfmt(caption, sizeof(caption), "Info file '%s'", name);

		path_build(path, sizeof(path), ANGBAND_DIR_INFO, name);
		fff = file_open(path, MODE_READ, -1);
	}

	/* Oops */
	if (!fff)
	{
		/* Message */
		msg("Cannot open '%s'.", name);
		message_flush();

		/* Oops */
		return (true);
	}


	/* Pre-Parse the file */
	while (true)
	{
		/* Read a line or stop */
		if (!file_getl(fff, buf, sizeof(buf))) break;

		/* XXX Parse "menu" items */
		if (prefix(buf, "***** "))
		{
			char b1 = '[', b2 = ']';

			/* Notice "menu" requests */
			if ((buf[6] == b1) && isalpha((unsigned char)buf[7]) &&
			    (buf[8] == b2) && (buf[9] == ' '))
			{
				/* This is a menu file */
				menu = true;

				/* Extract the menu item */
				k = A2I(buf[7]);

				/* Store the menu item (if valid) */
				if ((k >= 0) && (k < 26))
					my_strcpy(hook[k], buf + 10, sizeof(hook[0]));
			}
			/* Notice "tag" requests */
			else if (buf[6] == '<')
			{
				if (tag)
				{
					/* Remove the closing '>' of the tag */
					buf[strlen(buf) - 1] = '\0';

					/* Compare with the requested tag */
					if (streq(buf + 7, tag))
					{
						/* Remember the tagged line */
						line = next;
					}
				}
			}

			/* Skip this */
			continue;
		}

		/* Count the "real" lines */
		next++;
	}

	/* Save the number of "real" lines */
	size = next;



	/* Display the file */
	while (true)
	{
		/* Clear screen */
		Term_clear();


		/* Restrict the visible range */
		if (line > (size - (hgt - 4))) line = size - (hgt - 4);
		if (line < 0) line = 0;


		/* Re-open the file if needed */
		if (next > line)
		{
			/* Close it */
			file_close(fff);

			/* Hack -- Re-Open the file */
			fff = file_open(path, MODE_READ, -1);
			if (!fff) return (true);

			/* File has been restarted */
			next = 0;
		}


		/* Goto the selected line */
		while (next < line)
		{
			/* Get a line */
			if (!file_getl(fff, buf, sizeof(buf))) break;

			/* Skip tags/links */
			if (prefix(buf, "***** ")) continue;

			/* Count the lines */
			next++;
		}


		/* Dump the next lines of the file */
		for (i = 0; i < hgt - 4; )
		{
			/* Hack -- track the "first" line */
			if (!i) line = next;

			/* Get a line of the file or stop */
			if (!file_getl(fff, buf, sizeof(buf))) break;

			/* Hack -- skip "special" lines */
			if (prefix(buf, "***** ")) continue;

			/* Count the "real" lines */
			next++;

			/* Make a copy of the current line for searching */
			my_strcpy(lc_buf, buf, sizeof(lc_buf));

			/* Make the line lower case */
			if (!case_sensitive) string_lower(lc_buf);

			/* Hack -- keep searching */
			if (find && !i && !strstr(lc_buf, find)) continue;

			/* Hack -- stop searching */
			find = null;

			/* Dump the line */
			Term_putstr(0, i+2, -1, TERM_WHITE, buf);

			/* Highlight "shower" */
			if (shower[0])
			{
				const char *str = lc_buf;

				/* Display matches */
				while ((str = strstr(str, shower)) != null)
				{
					int len = strlen(shower);

					/* Display the match */
					Term_putstr(str-lc_buf, i+2, len, TERM_YELLOW, &buf[str-lc_buf]);

					/* Advance */
					str += len;
				}
			}

			/* Count the printed lines */
			i++;
		}

		/* Hack -- failed search */
		if (find)
		{
			bell("Search string not found!");
			line = back;
			find = null;
			continue;
		}


		/* Show a general "title" */
		prt(format("[%s, %s, Line %d-%d/%d]", buildid,
		           caption, line, line + hgt - 4, size), 0, 0);


		/* Prompt -- menu screen */
		if (menu)
		{
			/* Wait for it */
			prt("[Press a Number, or ESC to exit.]", hgt - 1, 0);
		}

		/* Prompt -- small files */
		else if (size <= hgt - 4)
		{
			/* Wait for it */
			prt("[Press ESC to exit.]", hgt - 1, 0);
		}

		/* Prompt -- large files */
		else
		{
			/* Wait for it */
			prt("[Press Space to advance, or ESC to exit.]", hgt - 1, 0);
		}

		/* Get a keypress */
		ch = inkey();

		/* Exit the help */
		if (ch.code == '?') break;

		/* Toggle case sensitive on/off */
		if (ch.code == '!')
		{
			case_sensitive = !case_sensitive;
		}

		/* Try showing */
		if (ch.code == '&')
		{
			/* Get "shower" */
			prt("Show: ", hgt - 1, 0);
			(void)askfor_aux(shower, sizeof(shower), null);

			/* Make the "shower" lowercase */
			if (!case_sensitive) string_lower(shower);
		}

		/* Try finding */
		if (ch.code == '/')
		{
			/* Get "finder" */
			prt("Find: ", hgt - 1, 0);
			if (askfor_aux(finder, sizeof(finder), null))
			{
				/* Find it */
				find = finder;
				back = line;
				line = line + 1;

				/* Make the "finder" lowercase */
				if (!case_sensitive) string_lower(finder);

				/* Show it */
				my_strcpy(shower, finder, sizeof(shower));
			}
		}

		/* Go to a specific line */
		if (ch.code == '#')
		{
			char tmp[80] = "0";

			prt("Goto Line: ", hgt - 1, 0);
			if (askfor_aux(tmp, sizeof(tmp), null))
				line = atoi(tmp);
		}

		/* Go to a specific file */
		if (ch.code == '%')
		{
			char ftmp[80] = "help.hlp";

			prt("Goto File: ", hgt - 1, 0);
			if (askfor_aux(ftmp, sizeof(ftmp), null))
			{
				if (!show_file(ftmp, null, 0, mode))
					ch.code = ESCAPE;
			}
		}

		switch (ch.code) {
			/* up a line */
			case ARROW_UP:
			case '8': line--; break;

			/* up a page */
			case KC_PGUP:
			case '9':
			case '-': line -= (hgt - 4); break;

			/* home */
			case KC_HOME:
			case '7': line = 0; break;

			/* down a line */
			case ARROW_DOWN:
			case '2':
			case '\n':
			case '\r': line++; break;

			/* down a page */
			case KC_PGDOWN:
			case '3':
			case ' ': line += hgt - 4; break;

			/* end */
			case KC_END:
			case '1': line = size; break;
		}

		/* Recurse on letters */
		if (menu && isalpha((unsigned char)ch.code))
		{
			/* Extract the requested menu item */
			k = A2I(ch.code);

			/* Verify the menu item */
			if ((k >= 0) && (k <= 25) && hook[k][0])
			{
				/* Recurse on that file */
				if (!show_file(hook[k], null, 0, mode)) ch.code = ESCAPE;
			}
		}

		/* Exit on escape */
		if (ch.code == ESCAPE) break;
	}

	/* Close the file */
	file_close(fff);

	/* Done */
	return (ch.code != '?');
}
Beispiel #28
0
int elf_load(struct sys_info *info, const char *filename, const char *cmdline)
{
    Elf_ehdr ehdr;
    Elf_phdr *phdr = NULL;
    unsigned long phdr_size;
    unsigned long checksum_offset;
    unsigned short checksum = 0;
    Elf_Bhdr *boot_notes = NULL;
    int retval = -1;
    int image_retval;
    unsigned int offset;

    image_name = image_version = NULL;

    if (!file_open(filename))
	goto out;

    for (offset = 0; offset < 16 * 512; offset += 512) {
        if ((size_t)lfile_read(&ehdr, sizeof ehdr) != sizeof ehdr) {
            debug("Can't read ELF header\n");
            retval = LOADER_NOT_SUPPORT;
            goto out;
        }

        if (ehdr.e_ident[EI_MAG0] == ELFMAG0)
            break;

        file_seek(offset);
    }

    if (ehdr.e_ident[EI_MAG0] != ELFMAG0
	    || ehdr.e_ident[EI_MAG1] != ELFMAG1
	    || ehdr.e_ident[EI_MAG2] != ELFMAG2
	    || ehdr.e_ident[EI_MAG3] != ELFMAG3
	    || ehdr.e_ident[EI_CLASS] != ARCH_ELF_CLASS
	    || ehdr.e_ident[EI_DATA] != ARCH_ELF_DATA
	    || ehdr.e_ident[EI_VERSION] != EV_CURRENT
	    || ehdr.e_type != ET_EXEC
	    || !ARCH_ELF_MACHINE_OK(ehdr.e_machine)
	    || ehdr.e_version != EV_CURRENT
	    || ehdr.e_phentsize != sizeof(Elf_phdr)) {
	debug("Not a bootable ELF image\n");
	retval = LOADER_NOT_SUPPORT;
	goto out;
    }

    phdr_size = ehdr.e_phnum * sizeof *phdr;
    phdr = malloc(phdr_size);
    file_seek(offset + ehdr.e_phoff);
    if ((unsigned long)lfile_read(phdr, phdr_size) != phdr_size) {
	printf("Can't read program header\n");
	goto out;
    }

    if (!check_mem_ranges(info, phdr, ehdr.e_phnum))
	goto out;

    checksum_offset = process_image_notes(phdr, ehdr.e_phnum, &checksum, offset);

    printf("Loading %s", image_name ? image_name : "image");
    if (image_version)
	printf(" version %s", image_version);
    printf("...\n");

    if (!load_segments(phdr, ehdr.e_phnum, checksum_offset, offset))
	goto out;

    if (checksum_offset) {
	if (!verify_image(&ehdr, phdr, ehdr.e_phnum, checksum))
	    goto out;
    }

    boot_notes = build_boot_notes(info, cmdline);

    //debug("current time: %lu\n", currticks());

    debug("entry point is %#llx\n", addr_fixup(ehdr.e_entry));
    printf("Jumping to entry point...\n");

#if 0
    {
        extern unsigned int qemu_mem_size;
        extern char boot_device;
        void *init_openprom(unsigned long memsize, const char *cmdline, char boot_device);

        int (*entry)(const void *romvec, int p2, int p3, int p4, int p5);
        const void *romvec;

        romvec = init_openprom(qemu_mem_size, cmdline, boot_device);
        entry = (void *) addr_fixup(ehdr.e_entry);
        image_retval = entry(romvec, 0, 0, 0, 0);
    }
#else
    image_retval = start_elf(addr_fixup(ehdr.e_entry), virt_to_phys(boot_notes));
#endif

    // console_init(); FIXME
    printf("Image returned with return value %#x\n", image_retval);
    retval = 0;

out:
    file_close();
    if (phdr)
	free(phdr);
    if (boot_notes)
	free(boot_notes);
    if (image_name)
	free(image_name);
    if (image_version)
	free(image_version);
    return retval;
}
Beispiel #29
0
/* Take an html screenshot */
void html_screenshot(const char *name, int mode)
{
	int y, x;
	int wid, hgt;

	byte a = TERM_WHITE;
	byte oa = TERM_WHITE;
	char c = ' ';

	const char *new_color_fmt = (mode == 0) ?
					"<font color=\"#%02X%02X%02X\">"
				 	: "[COLOR=\"#%02X%02X%02X\"]";
	const char *change_color_fmt = (mode == 0) ?
					"</font><font color=\"#%02X%02X%02X\">"
					: "[/COLOR][COLOR=\"#%02X%02X%02X\"]";
	const char *close_color_fmt = mode ==  0 ? "</font>" : "[/COLOR]";

	ang_file *fp;
	char buf[1024];


	path_build(buf, sizeof(buf), ANGBAND_DIR_USER, name);
	fp = file_open(buf, MODE_WRITE, FTYPE_TEXT);

	/* Oops */
	if (!fp)
	{
		plog_fmt("Cannot write the '%s' file!", buf);
		return;
	}

	/* Retrieve current screen size */
	Term_get_size(&wid, &hgt);

	if (mode == 0)
	{
		file_putf(fp, "<!DOCTYPE html><html><head>\n");
		file_putf(fp, "  <meta='generator' content='%s'>\n", buildid);
		file_putf(fp, "  <title>%s</title>\n", name);
		file_putf(fp, "</head>\n\n");
		file_putf(fp, "<body style='color: #fff; background: #000;'>\n");
		file_putf(fp, "<pre>\n");
	}
	else 
	{
		file_putf(fp, "[CODE][TT][BC=black][COLOR=white]\n");
	}

	/* Dump the screen */
	for (y = 0; y < hgt; y++)
	{
		for (x = 0; x < wid; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x, y, &a, &c));

			/* Color change */
			if (oa != a && c != ' ')
			{
				/* From the default white to another color */
				if (oa == TERM_WHITE)
				{
					file_putf(fp, new_color_fmt,
					        angband_color_table[a][1],
					        angband_color_table[a][2],
					        angband_color_table[a][3]);
				}

				/* From another color to the default white */
				else if (a == TERM_WHITE)
				{
					file_putf(fp, close_color_fmt);
				}

				/* Change colors */
				else
				{
					file_putf(fp, change_color_fmt,
					        angband_color_table[a][1],
					        angband_color_table[a][2],
					        angband_color_table[a][3]);
				}

				/* Remember the last color */
				oa = a;
			}

			/* Write the character and escape special HTML characters */
			if (mode == 0) write_html_escape_char(fp, c);
			else file_putf(fp, "%c", c);
		}

		/* End the row */
		file_putf(fp, "\n");
	}

	/* Close the last font-color tag if necessary */
	if (oa != TERM_WHITE) file_putf(fp, close_color_fmt);

	if (mode == 0)
	{
		file_putf(fp, "</pre>\n");
		file_putf(fp, "</body>\n");
		file_putf(fp, "</html>\n");
	}
	else 
	{
		file_putf(fp, "[/COLOR][/BC][/TT][/CODE]\n");
	}

	/* Close it */
	file_close(fp);
}
//Main function begins
int main(int argc,char *argv[])
{
	int sock;
	struct sockaddr_in client;
	FILE *fp;
	struct hostent *hp;
	char buff[20]="/0";
	int rval;
	int count=0;
	int sz;	
	printf("The number of arguments are %d %s %s\n",argc, argv[1], argv[2]);
	if(argc<=4)
	{	
		perror("the arguments are less\n");
		exit(1);
	}
	fp=file_open(argv[1]);
	sz=file_size(fp);

	input_data_t id;
	// copy the output file name to the structure 
	strcpy(id.file_name, argv[2]);
	id.size = sz;
	//Create socket
	sock=socket(AF_INET,SOCK_STREAM,0);
	if(sock <0)
	{
		perror("Failed to access socket");
		// Close the file
		fclose(fp);
		// Close the socket
		close (sock);
		exit(1);
	}
	client.sin_family=AF_INET;
	// Connection establishment if client and server are running on the same machine
	if(strcmp(argv[3],"localhost")==0)
	{
		if (strcmp(argv[1],argv[2])==0){
			 perror("Trying to overwrite the file on the same machine \n");
                        // Close the file
                        fclose(fp);
                        // Close the socket
                        close (sock);
                        exit(1);
		}	
		hp=gethostbyname(argv[3]);
		if(hp==0)
		{
			perror("gethostbyname failed");
			// Close the file
			fclose(fp);
			// Close the socket
			close (sock);
			exit(1);
		}
		memcpy(&client.sin_addr,hp->h_addr,hp->h_length);
	} else
		// Connection establishment if client and server  both are running on different machine
	{
		client.sin_addr.s_addr = inet_addr(argv[3]);

	}
	//Binding the client to a port number
	client.sin_port=htons(atoi(argv[4]));
	//Checking Connection
	if(connect(sock, (struct sockaddr *) &client, sizeof(client))<0)
	{
		perror("connection failed");
		// Close the file
		fclose(fp);
		// Close the socket
		close (sock);
		exit(1);
	}

	// Send meta data to the server
	// 1. Output file name
	// 2. Size of file 
	if(send(sock,&id,sizeof(id),0)<=0)
	{
		//close socket before exiting the program
		perror("send failed");
		// Close the file
		fclose(fp);
		// Close the socket
		close (sock);
		exit(1);
	}
	printf("Checking for Connection establishment:The data sending is %s %d \n",id.file_name, id.size); 
	send_file(fp,sock);
	printf("File successfully sent\n");
	// Close the file
	fclose(fp);
	// Close the socket
	close (sock);
	return 0;
}