Exemple #1
0
int rom_load(struct rom_t *rom, UINT8 *mem, int idx, int max)
{
	int offset, length;

_continue:
	offset = rom[idx].offset;

	if (rom[idx].skip == 0)
	{
		file_read(&mem[offset], rom[idx].length);

		if (rom[idx].type == ROM_WORDSWAP)
			swab(&mem[offset], &mem[offset], rom[idx].length);
	}
	else
	{
		int c;
		int skip = rom[idx].skip + rom[idx].group;

		length = 0;

		if (rom[idx].group == 1)
		{
			if (rom[idx].type == ROM_WORDSWAP)
				offset ^= 1;

			while (length < rom[idx].length)
			{
				if ((c = file_getc()) == EOF) break;
				mem[offset] = c;
				offset += skip;
				length++;
			}
		}
		else
		{
			while (length < rom[idx].length)
			{
				if ((c = file_getc()) == EOF) break;
				mem[offset + 0] = c;
				if ((c = file_getc()) == EOF) break;
				mem[offset + 1] = c;
				offset += skip;
				length += 2;
			}
		}
	}

	if (++idx != max)
	{
		if (rom[idx].type == ROM_CONTINUE)
		{
			goto _continue;
		}
	}

	return idx;
}
Exemple #2
0
static int wtap_file_read_pattern (wtap *wth, const char *pattern, int *err,
                                gchar **err_info)
{
    int c;
    const char *cp;

    cp = pattern;
    while (*cp)
    {
        c = file_getc(wth->fh);
        if (c == EOF)
        {
            *err = file_error(wth->fh, err_info);
            if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
                return -1;      /* error */
            return 0;   /* EOF */
        }
        if (c == *cp)
            cp++;
        else
        {
            if (c == pattern[0])
                cp = &pattern[1];
            else
                cp = pattern;
        }
    }
    return (*cp == '\0' ? 1 : 0);
}
Exemple #3
0
/* Seeks to the beginning of the next packet, and returns the
   byte offset.  Returns -1 on failure, and sets "*err" to the error. */
static gint64 toshiba_seek_next_packet(wtap *wth, int *err)
{
  int byte;
  guint level = 0;
  gint64 cur_off;

  while ((byte = file_getc(wth->fh)) != EOF) {
    if (byte == toshiba_rec_magic[level]) {
      level++;
      if (level >= TOSHIBA_REC_MAGIC_SIZE) {
	      /* note: we're leaving file pointer right after the magic characters */
        cur_off = file_tell(wth->fh);
        if (cur_off == -1) {
          /* Error. */
          *err = file_error(wth->fh);
          return -1;
        }
        return cur_off + 1;
      }
    } else {
      level = 0;
    }
  }
  if (file_eof(wth->fh)) {
    /* We got an EOF. */
    *err = 0;
  } else {
    /* We got an error. */
    *err = file_error(wth->fh);
  }
  return -1;
}
Exemple #4
0
/* Seeks to the beginning of the next packet, and returns the
   byte offset.  Returns -1 on failure, and sets "*err" to the error. */
static gint64 eyesdn_seek_next_packet(wtap *wth, int *err)
{
	int byte;
	gint64 cur_off;

	while ((byte = file_getc(wth->fh)) != EOF) {
		if (byte == 0xff) {
			cur_off = file_tell(wth->fh);
			if (cur_off == -1) {
				/* Error. */
				*err = file_error(wth->fh);
				return -1;
			}
			return cur_off;
		}
	}
	if (file_eof(wth->fh)) {
		/* We got an EOF. */
		*err = 0;
	} else {
		/* We got an error. */
		*err = file_error(wth->fh);
	}
	return -1;
}
/* Seeks to the beginning of the next packet, and returns the
   byte offset.  Returns -1 on failure, and sets "*err" to the error
   and "*err_info" to null or an additional error string. */
static gint64 dbs_etherwatch_seek_next_packet(wtap *wth, int *err,
                                              gchar **err_info)
{
    int byte;
    unsigned int level = 0;
    gint64 cur_off;

    while ((byte = file_getc(wth->fh)) != EOF) {
        if (byte == dbs_etherwatch_rec_magic[level]) {
            level++;
            if (level >= DBS_ETHERWATCH_REC_MAGIC_SIZE) {
                /* note: we're leaving file pointer right after the magic characters */
                cur_off = file_tell(wth->fh);
                if (cur_off == -1) {
                    /* Error. */
                    *err = file_error(wth->fh, err_info);
                    return -1;
                }
                return cur_off + 1;
            }
        } else {
            level = 0;
        }
    }
    /* EOF or error. */
    *err = file_error(wth->fh, err_info);
    return -1;
}
static int wtap_file_read_pattern (wtap *wth, const char *pattern, int *err)
{
    int c;
    const char *cp;

    cp = pattern;
    while (*cp)
    {
	c = file_getc(wth->fh);
	if (c == EOF) {
	    if (file_eof(wth->fh))
		return 0;	/* EOF */
	    else {
		/* We (presumably) got an error (there's no equivalent to
		   "ferror()" in zlib, alas, so we don't have a wrapper
		   to check for an error). */
		*err = file_error(wth->fh);
		return -1;	/* error */
	    }
	}
	if (c == *cp)
	    cp++;
	else
	{
	    if (c == pattern[0])
		cp = &pattern[1];
	    else
		cp = pattern;
	}
    }
    return (*cp == '\0' ? 1 : 0);
}
static int wtap_file_read_till_separator (wtap *wth, char *buffer, int buflen,
					const char *separators, int *err)
{
    int c;
    char *cp;
    int i;

    for (cp = buffer, i = 0; i < buflen; i++, cp++)
    {
	c = file_getc(wth->fh);
	if (c == EOF) {
	    if (file_eof(wth->fh))
		return 0;	/* EOF */
	    else {
		/* We (presumably) got an error (there's no equivalent to
		   "ferror()" in zlib, alas, so we don't have a wrapper
		   to check for an error). */
		*err = file_error(wth->fh);
		return -1;	/* error */
	    }
	}
	if (strchr (separators, c) != NULL)
	{
	    *cp = '\0';
	    break;
	}
	else
	    *cp = c;
    }
    return i;
}
/* Seeks to the beginning of the next packet, and returns the
   byte offset.  Returns -1 on failure, and sets "*err" to the error. */
static gint64 eyesdn_seek_next_packet(wtap *wth, int *err)
{
	int byte;
	gint64 cur_off;

	while ((byte = file_getc(wth->fh)) != EOF) {
		if (byte == 0xff) {
			cur_off = file_tell(wth->fh);
			if (cur_off == -1) {
				/* Error. */
				*err = file_error(wth->fh);
				return -1;
			}
			return cur_off;
		}
	}
	if (file_eof(wth->fh)) {
		/* We got an EOF. */
		*err = 0;
	} else {
		/* We (presumably) got an error (there's no equivalent to
		   "ferror()" in zlib, alas, so we don't have a wrapper to
		   check for an error). */
		*err = file_error(wth->fh);
	}
	return -1;
}
Exemple #9
0
static int wtap_file_read_pattern (wtap *wth, const char *pattern, int *err)
{
    int c;
    const char *cp;

    cp = pattern;
    while (*cp)
    {
	c = file_getc(wth->fh);
	if (c == EOF) {
	    if (file_eof(wth->fh))
		return 0;	/* EOF */
	    else {
		*err = file_error(wth->fh);
		return -1;	/* error */
	    }
	}
	if (c == *cp)
	    cp++;
	else
	{
	    if (c == pattern[0])
		cp = &pattern[1];
	    else
		cp = pattern;
	}
    }
    return (*cp == '\0' ? 1 : 0);
}
Exemple #10
0
static int wtap_file_read_till_separator (wtap *wth, char *buffer, int buflen,
					const char *separators, int *err)
{
    int c;
    char *cp;
    int i;

    for (cp = buffer, i = 0; i < buflen; i++, cp++)
    {
	c = file_getc(wth->fh);
	if (c == EOF) {
	    if (file_eof(wth->fh))
		return 0;	/* EOF */
	    else {
		*err = file_error(wth->fh);
		return -1;	/* error */
	    }
	}
	if (strchr (separators, c) != NULL)
	{
	    *cp = '\0';
	    break;
	}
	else
	    *cp = c;
    }
    return i;
}
Exemple #11
0
char file_peekc(FileStream *fs)
{
    unsigned pos = fs->position;
    char c = file_getc(fs);
    file_seek(fs, pos);
    return c;
}
Exemple #12
0
static int wtap_file_read_till_separator (wtap *wth, char *buffer, int buflen,
                                        const char *separators, int *err,
                                        gchar **err_info)
{
    int c;
    char *cp;
    int i;

    for (cp = buffer, i = 0; i < buflen; i++, cp++)
    {
        c = file_getc(wth->fh);
        if (c == EOF)
        {
            *err = file_error(wth->fh, err_info);
            if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
                return -1;      /* error */
            return 0;   /* EOF */
        }
        if (strchr (separators, c) != NULL)
        {
            *cp = '\0';
            break;
        }
        else
            *cp = c;
    }
    return i;
}
Exemple #13
0
/* This internal function reads a number from the file, similar to Lua's io.read("*num").
 * In Lua this is done with a fscanf(file, "%lf", &double), but we can't use fscanf() since
 * this may be coming from a zip file and we need to use file_wrappers.c functions.
 * So we get a character at a time, building a buffer for fscanf.
 * XXX this isn't perfect - if just "2." exists in file, for example, it consumes it.
 */
#define WSLUA_MAXNUMBER2STR  32 /* 16 digits, sign, point, and \0 */
static int File_read_number (lua_State *L, FILE_T ft) {
    lua_Number d;
    gchar buff[WSLUA_MAXNUMBER2STR];
    int buff_end = 0;
    int c = -1;
    int num_digits = 0;
    gboolean has_decimal = FALSE;

    c = file_peekc(ft);
    if (c == '+' || c == '-') {
        buff[buff_end++] = (gchar)c;
        /* make sure next char is a digit */
        c = file_peekc(ft);
        if (c < '0' || c > '9') {
            lua_pushnil(L);  /* "result" to be removed */
            return 0;  /* read fails */
        }
        /* eat the +/- */
        file_getc(ft);
    }

    while((c = file_peekc(ft)) > 0 && buff_end < (WSLUA_MAXNUMBER2STR-1)) {
        if (c >= '0' && c <= '9') {
            buff[buff_end++] = (gchar)c;
            num_digits++;
            file_getc(ft);
        }
        else if (!has_decimal && c == '.') {
            has_decimal = TRUE;
            buff[buff_end++] = (gchar)c;
            file_getc(ft);
        }
        else break;
    }

    buff[buff_end] = '\0';

    if (buff_end > 0 && num_digits > 0 && sscanf(buff, "%lf", &d) == 1) {
        lua_pushnumber(L, d);
        return 1;
    }
    else {
        lua_pushnil(L);  /* "result" to be removed */
        return 0;  /* read fails */
    }
}
Exemple #14
0
static int esc_read(guint8 *buf, int len, FILE_T fh)
{
	int i;
	int value;

	for(i=0; i<len; i++) {
		value=file_getc(fh);
		if(value==-1)
			return -2; /* EOF or error */
		if(value==0xff)
			return -1; /* error !!, read into next frame */
		if(value==0xfe) {
			/* we need to escape */
			value=file_getc(fh);
			if(value==-1)
				return -2;
			value+=2;
		}
		buf[i]=value;
	}

	return i;
}
Exemple #15
0
static gboolean esc_read(FILE_T fh, guint8 *buf, int len, int *err, gchar **err_info)
{
	int i;
	int value;

	for(i=0; i<len; i++) {
		value=file_getc(fh);
		if(value==-1) {
			/* EOF or error */
			*err=file_error(fh, err_info);
			if(*err==0)
				*err=WTAP_ERR_SHORT_READ;
			return FALSE;
		}
		if(value==0xff) {
			/* error !!, read into next frame */
			*err=WTAP_ERR_BAD_FILE;
			*err_info=g_strdup("eyesdn: No flag character seen in frame");
			return FALSE;
		}
		if(value==0xfe) {
			/* we need to escape */
			value=file_getc(fh);
			if(value==-1) {
				/* EOF or error */
				*err=file_error(fh, err_info);
				if(*err==0)
					*err=WTAP_ERR_SHORT_READ;
				return FALSE;
			}
			value+=2;
		}
		buf[i]=value;
	}

	return TRUE;
}
Exemple #16
0
static byte sf_get(void)
{
	byte c, v;

	/* Get a character, decode the value */
	c = file_getc(fff) & 0xFF;
	v = c ^ xor_byte;
	xor_byte = c;

	/* Maintain the checksum info */
	v_check += v;
	x_check += xor_byte;

	/* Return the value */
	return (v);
}
Exemple #17
0
/* Seeks to the beginning of the next packet, and returns the
   byte offset.  Returns -1 on failure, and sets "*err" to the error
   and "*err_info" to null or an additional error string. */
static gint64 eyesdn_seek_next_packet(wtap *wth, int *err, gchar **err_info)
{
	int byte;
	gint64 cur_off;

	while ((byte = file_getc(wth->fh)) != EOF) {
		if (byte == 0xff) {
			cur_off = file_tell(wth->fh);
			if (cur_off == -1) {
				/* Error. */
				*err = file_error(wth->fh, err_info);
				return -1;
			}
			return cur_off;
		}
	}
	/* EOF or error. */
	*err = file_error(wth->fh, err_info);
	return -1;
}
Exemple #18
0
//! @brief Manage cat command
//!
//! @param b_more   enable the '|more' management
//!
//! @todo more management not fully functional with file without CR
//!
void ushell_cmd_cat(bool b_more)
{
   char c_file_character;
   uint8_t n_line=0;

   if( g_s_arg[0][0] == 0 )
      return;

   // Select file
   if( !nav_setcwd((FS_STRING)g_s_arg[0],true,false) )
   {
      fputs(MSG_ER_UNKNOWN_FILE, stdout);
      return;
   }

   // Open file
   file_open(FOPEN_MODE_R);
   while (file_eof()==false)
   {
      // Check 'b_more' option
      if( b_more && (n_line >= USHELL_NB_LINE))
      {
         n_line = 0;
         if( !ushell_more_wait() )
            break;   // Stop cat command
      }

      // Display a character
      c_file_character = file_getc();
      putchar( c_file_character );

      // Count the line number
      if (c_file_character==ASCII_LF)
         n_line++;
   }
   file_close();

   // Jump in a new line
   putchar(ASCII_CR);putchar(ASCII_LF);
}
Exemple #19
0
/* Seeks to the beginning of the next packet, and returns the
   byte offset at which the header for that packet begins.
   Returns -1 on failure. */
static gint64 ascend_seek(wtap *wth, int *err, gchar **err_info)
{
  int byte;
  gint64 date_off = -1, cur_off, packet_off;
  size_t string_level[ASCEND_MAGIC_STRINGS];
  guint string_i = 0, type = 0;
  guint excessive_read_count = 262144;

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

  while (((byte = file_getc(wth->fh)) != EOF)) {
    excessive_read_count--;

    if (!excessive_read_count) {
      *err = 0;
      return -1;
    }

    for (string_i = 0; string_i < ASCEND_MAGIC_STRINGS; string_i++) {
      const gchar *strptr = ascend_magic[string_i].strptr;
      size_t len          = strlen(strptr);

      if (byte == *(strptr + string_level[string_i])) {
        string_level[string_i]++;
        if (string_level[string_i] >= len) {
          cur_off = file_tell(wth->fh);
          if (cur_off == -1) {
            /* Error. */
            *err = file_error(wth->fh, err_info);
            return -1;
          }

          /* Date: header is a special case. Remember the offset,
             but keep looking for other headers. */
	  if (strcmp(strptr, ASCEND_DATE) == 0) {
            date_off = cur_off - len;
          } else {
            if (date_off == -1) {
              /* Back up over the header we just read; that's where a read
                 of this packet should start. */
              packet_off = cur_off - len;
            } else {
              /* This packet has a date/time header; a read of it should
                 start at the beginning of *that* header. */
              packet_off = date_off;
            }

            type = ascend_magic[string_i].type;
            goto found;
          }
        }
      } else {
        string_level[string_i] = 0;
      }
    }
  }

  *err = file_error(wth->fh, err_info);
  return -1;

found:
  /*
   * Move to where the read for this packet should start, and return
   * that seek offset.
   */
  if (file_seek(wth->fh, packet_off, SEEK_SET, err) == -1)
    return -1;

  wth->phdr.pseudo_header.ascend.type = type;

  return packet_off;
}
Exemple #20
0
// initializes the SD/MMC memory resources: GPIO, SPI and MMC
//-------------------------------------------------------------------
static void sd_mmc_resources_init(long pba_hz) {
	
	// GPIO pins used for SD/MMC interface
	static const gpio_map_t SD_MMC_SPI_GPIO_MAP = {
	{SD_MMC_SPI_SCK_PIN,  SD_MMC_SPI_SCK_FUNCTION },  // SPI Clock.
	{SD_MMC_SPI_MISO_PIN, SD_MMC_SPI_MISO_FUNCTION},  // MISO.
	{SD_MMC_SPI_MOSI_PIN, SD_MMC_SPI_MOSI_FUNCTION},  // MOSI.
	{SD_MMC_SPI_NPCS_PIN, SD_MMC_SPI_NPCS_FUNCTION}   // Chip Select NPCS.
	};

	// SPI options.
	spi_options_t spiOptions = {
		.reg          = SD_MMC_SPI_NPCS,
		.baudrate     = SD_MMC_SPI_MASTER_SPEED,  // Defined in conf_sd_mmc_spi.h.
		.bits         = SD_MMC_SPI_BITS,          // Defined in conf_sd_mmc_spi.h.
		.spck_delay   = 0,
		.trans_delay  = 0,
		.stay_act     = 1,
		.spi_mode     = 0,
		.modfdis      = 1
	};

	// assign I/Os to SPI.
	gpio_enable_module(SD_MMC_SPI_GPIO_MAP,
	sizeof(SD_MMC_SPI_GPIO_MAP) / sizeof(SD_MMC_SPI_GPIO_MAP[0]));

	// initialize as master.
	spi_initMaster(SD_MMC_SPI, &spiOptions);

	// set SPI selection mode: variable_ps, pcs_decode, delay.
	spi_selectionMode(SD_MMC_SPI, 0, 0, 0);

	// enable SPI module.
	spi_enable(SD_MMC_SPI);

	// Initialize SD/MMC driver with SPI clock (PBA).
	sd_mmc_spi_init(spiOptions, pba_hz);
}

// process a USB frame
//-------------------------------------------------------------------
void process_frame(uint16_t framenumber)
{
	static uint8_t cpt_sof = 0;
	static injectState_t state = state_START_INJECT;
	static uint8_t wait = 0;
	static uint16_t debounce = 0;
	static uint16_t injectToken = 0x0000;
	
	static uint16_t delay = 0;
	
	// scan process running each 2ms
	cpt_sof++;
	if( 2 > cpt_sof )
	return;
	cpt_sof = 0;
	
	// pulse led
	LED_Set_Intensity( LED0, framenumber >> 1 );
	
	// debounce switch
	if( debounce > 0 ) --debounce;
	
	//delay a random amount
	if(delay == 0){
		// injection state machine
		switch(state) {

			case state_IDLE:
			// check switch
			if( gpio_get_pin_value(GPIO_JOYSTICK_PUSH) == GPIO_JOYSTICK_PUSH_PRESSED ) {
			
				// debounce
				if( debounce == 0 ) {
					state = state_START_INJECT;
					debounce = 250;
				}
			}
			break;
		
			case state_START_INJECT:
			file_open(FOPEN_MODE_R);
			state = state_INJECTING;
			break;
		
			case state_INJECTING:
		
			if( file_eof() ) {
				file_close();
				state = state_IDLE;
				break;
			}
		
			injectToken = ( file_getc() | ( file_getc() << 8 ) );
		
			if( ( injectToken&0xff ) == 0x00 ) {
				wait = injectToken>>8;
				state = state_WAIT;
			}
			else if( ( injectToken>>8 ) == 0x00 ) {
				state = state_KEY_DOWN;
			}
			else {
				state = state_MOD_DOWN;
			}
			break;
		
			case state_KEY_DOWN:
			udi_hid_kbd_down(injectToken&0xff);
			state = state_KEY_UP;
			delay = rand() % MAX_DELAY;
			break;

			case state_KEY_UP:
			udi_hid_kbd_up(injectToken&0xff);
			state = state_INJECTING;
			delay = rand() % MAX_DELAY;
			break;
		
			case state_MOD_DOWN:
			udi_hid_kbd_modifier_down(injectToken>>8);
			state = state_MOD_KEY_DOWN;
			delay = rand() % MAX_DELAY;
			break;

			case state_MOD_KEY_DOWN:
			udi_hid_kbd_down(injectToken&0xff);
			state = state_MOD_KEY_UP;
			delay = rand() % MAX_DELAY;
			break;

			case state_MOD_KEY_UP:
			udi_hid_kbd_up(injectToken&0xff);
			state = state_MOD_UP;
			delay = rand() % MAX_DELAY;
			break;
		
			case state_MOD_UP:
			udi_hid_kbd_modifier_up(injectToken>>8);
			state = state_INJECTING;
			delay = rand() % 50;
			break;
		
			case state_WAIT:
			if( --wait == 0 ) {
				state = state_INJECTING;
			}
			break;
		
			default:
			state = state_IDLE;
		}
Exemple #21
0
/* Seeks to the beginning of the next packet, and returns the
   byte offset at which the header for that packet begins.
   Returns -1 on failure. */
static gint64 ascend_seek(wtap *wth, int *err, gchar **err_info)
{
  int byte;
  gint64 date_off = -1, cur_off, packet_off;
  size_t string_level[ASCEND_MAGIC_STRINGS];
  guint string_i = 0, type = 0;
  static const gchar ascend_date[] = ASCEND_DATE;
  size_t ascend_date_len           = sizeof ascend_date - 1; /* strlen of a constant string */
  size_t ascend_date_string_level;
  guint excessive_read_count = 262144;

  memset(&string_level, 0, sizeof(string_level));
  ascend_date_string_level = 0;

  while (((byte = file_getc(wth->fh)) != EOF)) {
    excessive_read_count--;

    if (!excessive_read_count) {
      *err = 0;
      return -1;
    }

    /*
     * See whether this is the string_level[string_i]th character of
     * Ascend magic string string_i.
     */
    for (string_i = 0; string_i < ASCEND_MAGIC_STRINGS; string_i++) {
      const gchar *strptr = ascend_magic[string_i].strptr;
      size_t len          = ascend_magic[string_i].strlength;

      if (byte == *(strptr + string_level[string_i])) {
        /*
         * Yes, it is, so we need to check for the next character of
         * that string.
         */
        string_level[string_i]++;

        /*
         * Have we matched the entire string?
         */
        if (string_level[string_i] >= len) {
          /*
           * Yes.
           */
          cur_off = file_tell(wth->fh);
          if (cur_off == -1) {
            /* Error. */
            *err = file_error(wth->fh, err_info);
            return -1;
          }

          /* We matched some other type of header. */
          if (date_off == -1) {
            /* We haven't yet seen a date header, so this packet
               doesn't have one.
               Back up over the header we just read; that's where a read
               of this packet should start. */
            packet_off = cur_off - len;
          } else {
            /* This packet has a date/time header; a read of it should
               start at the beginning of *that* header. */
            packet_off = date_off;
          }

          type = ascend_magic[string_i].type;
          goto found;
        }
      } else {
        /*
         * Not a match for this string, so reset the match process.
         */
        string_level[string_i] = 0;
      }
    }

    /*
     * See whether this is the date_string_level'th character of
     * ASCEND_DATE.
     */
    if (byte == *(ascend_date + ascend_date_string_level)) {
      /*
       * Yes, it is, so we need to check for the next character of
       * that string.
       */
      ascend_date_string_level++;

      /*
       * Have we matched the entire string?
       */
      if (ascend_date_string_level >= ascend_date_len) {
        /* We matched a Date: header.  It's a special case;
           remember the offset, but keep looking for other
           headers.

           Reset the amount of Date: header that we've matched,
           so that we start the process of matching a Date:
           header all over again.

           XXX - what if we match multiple Date: headers before
           matching some other header? */
        cur_off = file_tell(wth->fh);
        if (cur_off == -1) {
          /* Error. */
          *err = file_error(wth->fh, err_info);
          return -1;
        }

        date_off = cur_off - ascend_date_len;
        ascend_date_string_level = 0;
      }
    } else {
      /*
       * Not a match for the Date: string, so reset the match process.
       */
      ascend_date_string_level = 0;
    }
  }

  *err = file_error(wth->fh, err_info);
  return -1;

found:
  /*
   * Move to where the read for this packet should start, and return
   * that seek offset.
   */
  if (file_seek(wth->fh, packet_off, SEEK_SET, err) == -1)
    return -1;

  wth->phdr.pseudo_header.ascend.type = type;

  return packet_off;
}
Exemple #22
0
#include <time.h>

#define PES_PREFIX 1
#define PES_VALID(n) (((n) >> 8 & 0xffffff) == PES_PREFIX)

typedef struct {
    nstime_t now;
    time_t t0;
} mpeg_t;

static int
mpeg_resync(wtap *wth, int *err, gchar **err_info _U_)
{
    gint64 offset = file_tell(wth->fh);
    int count = 0;
    int byte = file_getc(wth->fh);

    while (byte != EOF) {
        if (byte == 0xff && count > 0) {
            byte = file_getc(wth->fh);
            if (byte != EOF && (byte & 0xe0) == 0xe0)
                break;
        } else
            byte = file_getc(wth->fh);
        count++;
    }
    if (file_seek(wth->fh, offset, SEEK_SET, err) == -1)
        return 0;
    return count;
}
Exemple #23
0
/* Returns TRUE if packet data copied, FALSE if error occurred or EOF (no more records). */
static gboolean
collate(pppdump_t* state, FILE_T fh, int *err, gchar **err_info, guint8 *pd,
		int *num_bytes, direction_enum *direction, pkt_id *pid,
		gint64 num_bytes_to_skip)
{
	int		id;
	pkt_t		*pkt = NULL;
	int		byte0, byte1;
	int		n, num_written = 0;
	gint64		start_offset;
	guint32		time_long;
	guint8		time_short;

	/*
	 * Process any data left over in the current record when doing
	 * sequential processing.
	 */
	if (state->num_bytes > 0) {
		g_assert(num_bytes_to_skip == 0);
		pkt = state->pkt;
		num_written = process_data(state, fh, pkt, state->num_bytes,
		    pd, err, err_info, pid);

		if (num_written < 0) {
			return FALSE;
		}
		else if (num_written > 0) {
			*num_bytes = num_written;
			*direction = pkt->dir;
			return TRUE;
		}
		/* if 0 bytes written, keep processing */
	} else {
		/*
		 * We didn't have any data left over, so the packet will
		 * start at the beginning of a record.
		 */
		if (pid)
			pid->num_bytes_to_skip = 0;
	}

	/*
	 * That didn't get all the data for this packet, so process
	 * subsequent records.
	 */
	start_offset = state->offset;
	while ((id = file_getc(fh)) != EOF) {
		state->offset++;
		switch (id) {
			case PPPD_SENT_DATA:
			case PPPD_RECV_DATA:
				pkt = id == PPPD_SENT_DATA ? &state->spkt : &state->rpkt;

				/*
				 * Save the offset of the beginning of
				 * the current record.
				 */
				pkt->cd_offset = state->offset - 1;

				/*
				 * Get the length of the record.
				 */
				byte0 = file_getc(fh);
				if (byte0 == EOF)
					goto done;
				state->offset++;
				byte1 = file_getc(fh);
				if (byte1 == EOF)
					goto done;
				state->offset++;
				n = (byte0 << 8) | byte1;

				if (pkt->id_offset == 0) {
					/*
					 * We don't have the initial data
					 * offset for this packet, which
					 * means this is the first
					 * data record for that packet.
					 * Save the offset of the
					 * beginning of that record and
					 * the offset of the first data
					 * byte in the packet, which is
					 * the first data byte in the
					 * record.
					 */
					pkt->id_offset = pkt->cd_offset;
					pkt->sd_offset = state->offset;
				}

				if (n == 0)
					continue;

				g_assert(num_bytes_to_skip < n);
				while (num_bytes_to_skip) {
					if (file_getc(fh) == EOF)
						goto done;
					state->offset++;
					num_bytes_to_skip--;
					n--;
				}
				num_written = process_data(state, fh, pkt, n,
				    pd, err, err_info, pid);

				if (num_written < 0) {
					return FALSE;
				}
				else if (num_written > 0) {
					*num_bytes = num_written;
					*direction = pkt->dir;
					return TRUE;
				}
				/* if 0 bytes written, keep looping */
				break;

			case PPPD_SEND_DELIM:
			case PPPD_RECV_DELIM:
				/* What can we do? */
				break;

			case PPPD_RESET_TIME:
				wtap_file_read_unknown_bytes(&time_long, sizeof(guint32), fh, err, err_info);
				state->offset += sizeof(guint32);
				state->timestamp = pntohl(&time_long);
				state->tenths = 0;
				break;

			case PPPD_TIME_STEP_LONG:
				wtap_file_read_unknown_bytes(&time_long, sizeof(guint32), fh, err, err_info);
				state->offset += sizeof(guint32);
				state->tenths += pntohl(&time_long);

				if (state->tenths >= 10) {
					state->timestamp += state->tenths / 10;
					state->tenths = state->tenths % 10;
				}

				break;

			case PPPD_TIME_STEP_SHORT:
				wtap_file_read_unknown_bytes(&time_short, sizeof(guint8), fh, err, err_info);
				state->offset += sizeof(guint8);
				state->tenths += time_short;

				if (state->tenths >= 10) {
					state->timestamp += state->tenths / 10;
					state->tenths = state->tenths % 10;
				}

				break;

			default:
				/* XXX - bad file */
				*err = WTAP_ERR_BAD_FILE;
				*err_info = g_strdup_printf("pppdump: bad ID byte 0x%02x", id);
				return FALSE;
		}

	}

done:
	*err = file_error(fh, err_info);
	if (*err == 0) {
		if (state->offset != start_offset) {
			/*
			 * We read at least one byte, so we were working
			 * on a record; an EOF means that record was
			 * cut short.
			 */
			*err = WTAP_ERR_SHORT_READ;
		}
	}
	return FALSE;
}
Exemple #24
0
/* Returns number of bytes copied for record, -1 if failure.
 *
 * This is modeled after pppdump.c, the utility to parse pppd log files; it
 * comes with the ppp distribution.
 */
static int
process_data(pppdump_t *state, FILE_T fh, pkt_t *pkt, int n, guint8 *pd,
    int *err, gchar **err_info, pkt_id *pid)
{
	int	c;
	int	num_bytes = n;
	int	num_written;

	for (; num_bytes > 0; --num_bytes) {
		c = file_getc(fh);
		if (c == EOF) {
			*err = file_error(fh, err_info);
			if (*err == 0) {
				*err = WTAP_ERR_SHORT_READ;
			}
			return -1;
		}
		state->offset++;
		switch (c) {
			case 0x7e:
				/*
				 * Flag Sequence for RFC 1662 HDLC-like
				 * framing.
				 *
				 * As this is a raw trace of octets going
				 * over the wire, and that might include
				 * the login sequence, there is no
				 * guarantee that *only* PPP traffic
				 * appears in this file, so there is no
				 * guarantee that the first 0x7e we see is
				 * a start flag sequence, and therefore we
				 * cannot safely ignore all characters up
				 * to the first 0x7e, and therefore we
				 * might end up with some bogus PPP
				 * packets.
				 */
				if (pkt->cnt > 0) {
					/*
					 * We've seen stuff before this,
					 * so this is the end of a frame.
					 * Make a frame out of that stuff.
					 */
					pkt->esc = FALSE;

					num_written = pkt->cnt;
					pkt->cnt = 0;
					if (num_written <= 0) {
						return 0;
					}

					if (num_written > PPPD_BUF_SIZE) {
						*err = WTAP_ERR_UNC_OVERFLOW;
						return -1;
					}

					memcpy(pd, pkt->buf, num_written);

					/*
					 * Remember the offset of the
					 * first record containing data
					 * for this packet, and how far
					 * into that record to skip to
					 * get to the beginning of the
					 * data for this packet; the number
					 * of bytes to skip into that record
					 * is the file offset of the first
					 * byte of this packet minus the
					 * file offset of the first byte of
					 * this record, minus 3 bytes for the
					 * header of this record (which, if
					 * we re-read this record, we will
					 * process, not skip).
					 */
					if (pid) {
						pid->offset = pkt->id_offset;
						pid->num_bytes_to_skip =
						    pkt->sd_offset - pkt->id_offset - 3;
						g_assert(pid->num_bytes_to_skip >= 0);
					}

					num_bytes--;
					if (num_bytes > 0) {
						/*
						 * There's more data in this
						 * record.
						 * Set the initial data offset
						 * for the next packet.
						 */
						pkt->id_offset = pkt->cd_offset;
						pkt->sd_offset = state->offset;
					} else {
						/*
						 * There is no more data in
						 * this record.
						 * Thus, we don't have the
						 * initial data offset for
						 * the next packet.
						 */
						pkt->id_offset = 0;
						pkt->sd_offset = 0;
					}
					state->num_bytes = num_bytes;
					state->pkt = pkt;
					return num_written;
				}
				break;

			case 0x7d:
				/*
				 * Control Escape octet for octet-stuffed
				 * RFC 1662 HDLC-like framing.
				 */
				if (!pkt->esc) {
					/*
					 * Control Escape not preceded by
					 * Control Escape; discard it
					 * but XOR the next octet with
					 * 0x20.
					 */
					pkt->esc = TRUE;
					break;
				}
				/*
				 * Control Escape preceded by Control Escape;
				 * treat it as an ordinary character,
				 * by falling through.
				 */

			default:
				if (pkt->esc) {
					/*
					 * This character was preceded by
					 * Control Escape, so XOR it with
					 * 0x20, as per RFC 1662's octet-
					 * stuffed framing, and clear
					 * the flag saying that the
					 * character should be escaped.
					 */
					c ^= 0x20;
					pkt->esc = FALSE;
				}

				if (pkt->cnt >= PPPD_BUF_SIZE) {
					*err = WTAP_ERR_UNC_OVERFLOW;
					return -1;
				}
				pkt->buf[pkt->cnt++] = c;
				break;
		}
	}

	/* we could have run out of bytes to read */
	return 0;
}
Exemple #25
0
//! This function adds files in play list
//!
//! @param sz_filterext add file only corresponding to the  extension filter
//! @param u8_mode      PL_ADD_FILE, PL_ADD_DIR, PL_ADD_SUBDIR
//!
//! @return    false in case of error, see global value "fs_g_status" for more detail
//! @return    true otherwise
//!
//! @verbatim
//! It is possible to select a file or all files in a directory
//! @endverbatim
//!
bool   pl_add( const FS_STRING sz_filterext , uint8_t u8_mode )
{
   uint8_t nav_id_save;
   uint8_t u8_folder_level;

   if( !pl_main_modify() )
      return false;
   nav_id_save = nav_get();

   // Check last character of file
   nav_select( FS_NAV_ID_PLAYLIST );
   if( 0!=nav_file_lgt() )
   {
#if( PL_UNICODE == true)
      file_string_unicode();
      file_seek( 2, FS_SEEK_END);
      if( '\n' != file_getc())
      {
         file_seek( 2, FS_SEEK_END);
         file_putc('\n');
      }
      file_string_ascii();
#else
      file_seek( 1, FS_SEEK_END);
      if( '\n' != file_getc())
      {
         file_seek( 1, FS_SEEK_END);
         file_putc('\n');
      }
#endif
   }
   nav_select( nav_id_save );

   // Get path of play list file and check with current to create a relative path

   if( PL_ADD_FILE == u8_mode )
      goto pl_add_file;

   // Add all files valid in current dir
   u8_folder_level = 0;
   nav_filelist_reset();
   while(1)
   {
      while(1)
      {
         if( nav_filelist_set( 0 , FS_FIND_NEXT ) )
            break;   // a next file and directory is found
         // No other dir or file in current dir then go to parent dir
         if( 0 == u8_folder_level )
            goto pl_add_end;  // end of ADD
         // Remark, nav_dir_gotoparent() routine go to in parent dir and select the children dir in list
         u8_folder_level--;
         if( !nav_dir_gotoparent() )
            return false;
      }

      if( nav_file_isdir())
      {
         if( PL_ADD_SUBDIR == u8_mode )
         {  // Enter in sub dir
            if( !nav_dir_cd())
               return false;
            u8_folder_level++;
         }
      }
      else
      {
pl_add_file:
         if( nav_file_checkext( sz_filterext ) )
         {
            // It is a valid file
            // Get name of current file
#if( (FS_ASCII == true) && (FS_UNICODE == true) && (PL_UNICODE == false) )
            nav_string_ascii();
#endif
            nav_getcwd( (FS_STRING)pl_cache_path, PL_CACHE_PATH_MAX_SIZE, true );
#if( (FS_ASCII == true) && (FS_UNICODE == true) && (PL_UNICODE == false) )
            nav_string_unicode();
#endif
            // Write path in file list
            nav_select( FS_NAV_ID_PLAYLIST );
#if( PL_UNICODE == true)
            file_string_unicode();
#endif
            if( file_puts(pl_cache_path))
               file_putc('\n');
#if( PL_UNICODE == true)
            file_string_ascii();
#endif
            nav_select( nav_id_save );
            pl_g_u16_list_size++;
         }
         if( PL_ADD_FILE == u8_mode )
            goto pl_add_end;
      } // if dir OR file
   } // end of first while(1)

pl_add_end:
   // Go to beginning of file AND no file selected
   nav_select( FS_NAV_ID_PLAYLIST );
   file_seek( 0 , FS_SEEK_SET );
   pl_g_u16_list_sel = 0;
   nav_select( nav_id_save );
   return true;
}
Exemple #26
0
int edit(char* filename) {
    int offset_in_text = 0;
    int c;
    int edits_done = 0;

    // Over all edits to be done:
    //
    while (read_edit_spec()) {

        // Copy forward through file to read edit point:
        //
        while (offset_in_text < edit_offset) {
            fputc( file_getc( text ), edited );
            ++offset_in_text;
        }

        // Verify that expected text is found at that point:
	//
        {   char* to_match = from_string;
            while (*to_match) {
                c = file_getc( text );
                if (c != *to_match) {
		    fprintf(
                        stderr,
                        "%s: at offset %d in %s read '%c'x=%02x (expected '%c'x=%02x) while trying to match %s\n",
                        program_name,
                        offset_in_text,
                        filename,
                        c,
                        *to_match,
                        from_string   
                    );
		    fflush(stderr);
                    exit(1);
                }
                ++offset_in_text;
                ++to_match; 
            }
        }

        // Replace it per edit specification:
        //
        {   char* to_write = to_string;
            while (*to_write) {
	      fputc( *to_write, edited);
                ++to_write; 
            }
        }

        ++edits_done;
    }

    // Copy remaining input file to edited:
    //
    while ((c = fgetc( text )) != EOF) {
        fputc( c, edited );
    }

    fclose( edited );
    fclose( text );
    fclose( edits );

    fprintf(stderr, "%s: %d edits done.\n", program_name, edits_done); 	fflush(stderr);
}
Exemple #27
0
uint32_t load_spc(uint8_t* filename, uint32_t spc_data_addr, uint32_t spc_header_addr) {
  DWORD filesize;
  UINT bytes_read;
  uint8_t data;
  UINT j;

  printf("%s\n", filename);

  file_open(filename, FA_READ); /* Open SPC file */
  if(file_res) return 0;
  filesize = file_handle.fsize;
  if (filesize < 65920) { /*  At this point, we care about filesize only */
    file_close();         /* since SNES decides if it is an SPC file */
    sram_writebyte(0, spc_header_addr);	/* If file is too small, destroy previous SPC header */
    return 0;
  }

  set_mcu_addr(spc_data_addr);
  f_lseek(&file_handle, 0x100L); /* Load 64K data segment */

  for(;;) {
    bytes_read = file_read();
    if (file_res || !bytes_read) break;
    FPGA_SELECT();
    FPGA_TX_BYTE(0x98);
    for(j=0; j<bytes_read; j++) {
      FPGA_TX_BYTE(file_buf[j]);
      FPGA_WAIT_RDY();
    }
    FPGA_DESELECT();
  }

  file_close();
  file_open(filename, FA_READ); /* Reopen SPC file to reset file_getc state*/

  set_mcu_addr(spc_header_addr);
  f_lseek(&file_handle, 0x0L); /* Load 256 bytes header */

  FPGA_SELECT();
  FPGA_TX_BYTE(0x98);
  for (j = 0; j < 256; j++) {
    data = file_getc();
    FPGA_TX_BYTE(data);
    FPGA_WAIT_RDY();
  }
  FPGA_DESELECT();

  file_close();
  file_open(filename, FA_READ); /* Reopen SPC file to reset file_getc state*/

  set_mcu_addr(spc_header_addr+0x100);
  f_lseek(&file_handle, 0x10100L); /* Load 128 DSP registers */

  FPGA_SELECT();
  FPGA_TX_BYTE(0x98);
  for (j = 0; j < 128; j++) {
    data = file_getc();
    FPGA_TX_BYTE(data);
    FPGA_WAIT_RDY();
  }
  FPGA_DESELECT();
  file_close(); /* Done ! */

  /* clear echo buffer to avoid artifacts */
  uint8_t esa = sram_readbyte(spc_header_addr+0x100+0x6d);
  uint8_t edl = sram_readbyte(spc_header_addr+0x100+0x7d);
  uint8_t flg = sram_readbyte(spc_header_addr+0x100+0x6c);
  if(!(flg & 0x20) && (edl & 0x0f)) {
    int echo_start = esa << 8;
    int echo_length = (edl & 0x0f) << 11;
    printf("clearing echo buffer %04x-%04x...\n", echo_start, echo_start+echo_length-1);
    sram_memset(spc_data_addr+echo_start, echo_length, 0);
  }

  return (uint32_t)filesize;
}
Exemple #28
0
//! This function fills an ASCII buffer with the current text line of opened file
//!
//! @param     b_unicode      true to return a unicode string (UTF16), ASCII otherwise over there
//! @param     string         string used to store text line
//! @param     u16_str_size   maximum size of string (unit character, 1B for ASCII, 2B for unicode)
//!
//! @return    size of the line (may be < or > at u16_str_size)
//! @return    0, in case of error
//!
//! @verbatim
//! This routine remove the character '\n' '\r'
//! @endverbatim
//!
uint16_t   reader_txt_get_line( bool b_unicode, FS_STRING string , uint16_t u16_str_size )
{
    uint8_t    utf8[UNI_MAX_UTF8_SIZE];
    uint8_t    size_utf8_buf=0;
    uint8_t    size_utf8_dec=0;
    uint16_t   u16_size_line = 1;   // 1 to compute null terminator
    uint16_t   u16_unicode;
    bool  b_error = false;

    nav_checkdisk_disable();   // To optimize speed

    while( 0 == file_eof() && !b_error )
    {
        // Get a unicode value
        switch( fs_g_nav_entry.u8_txt_format )
        {
        case UNI_TYPE_UTF8:
            // Remove UTF8 codes used
            if( 0 != size_utf8_dec )
            {
                uint8_t u8_i;
                for( u8_i=0; u8_i<(UNI_MAX_UTF8_SIZE-size_utf8_dec); u8_i++ )
                {
                    utf8[u8_i]=utf8[u8_i+size_utf8_dec];
                }
                size_utf8_buf -= size_utf8_dec;
                size_utf8_dec =0;
            }
            // Complete UTF8 array
            size_utf8_buf += file_read_buf( &utf8[size_utf8_buf], (UNI_MAX_UTF8_SIZE-size_utf8_buf) );
            // Decode UTF8 to unicode
            size_utf8_dec = utf8_to_unicode( &utf8[0], &u16_unicode );
            break;

        case UNI_TYPE_UTF16BE:
            MSB(u16_unicode) = file_getc();
            LSB(u16_unicode) = file_getc();
            if (LSB(u16_unicode) == (FS_EOF & 0xFF) && fs_g_status != FS_ERR_EOF)
                b_error = true;
            break;

        case UNI_TYPE_UTF16LE:
            LSB(u16_unicode) = file_getc();
            MSB(u16_unicode) = file_getc();
            if (MSB(u16_unicode) == (FS_EOF & 0xFF) && fs_g_status != FS_ERR_EOF)
                b_error = true;
            break;

        default: // ASCII or other
            u16_unicode = file_getc();
            if (u16_unicode == FS_EOF && fs_g_status != FS_ERR_EOF)
                b_error = true;
            break;
        }

        // Check character to remove
        if( '\r' == u16_unicode )
            continue;   // Ignore character

        // Check end of line
        if((  0  == u16_unicode )
                || ('\n' == u16_unicode ) )
            break;      // End of line

        u16_size_line++;
        // Fill string
        if( 1 < u16_str_size )
        {
            if( b_unicode )
            {
                ((FS_STR_UNICODE)string)[0] = u16_unicode;
            } else {
                string[0] = u16_unicode;
            }
            string += (b_unicode? 2 : 1 );
            u16_str_size--;
        }
    }
    // HERE, the line is read

    if( UNI_TYPE_UTF8 == fs_g_nav_entry.u8_txt_format )
    {
        // Re position cursor on next UTF8
        file_seek( (size_utf8_buf-size_utf8_dec) , FS_SEEK_CUR_RE );
    }

    // Handle error cases
    if (b_error)
    {
        nav_checkdisk_enable();
        return 0;
    }

    // Add Null terminate
    if( 0 != u16_str_size )
    {
        if( b_unicode )
        {
            ((FS_STR_UNICODE)string)[0] = 0;
        } else {
            string[0] = 0;
        }
    }
    nav_checkdisk_enable();
    return u16_size_line;
}