Exemplo n.º 1
0
static int check_header(const struct strbuf *line,
				struct strbuf *hdr_data[], int overwrite)
{
	int i, ret = 0, len;
	struct strbuf sb = STRBUF_INIT;
	/* search for the interesting parts */
	for (i = 0; header[i]; i++) {
		int len = strlen(header[i]);
		if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
			/* Unwrap inline B and Q encoding, and optionally
			 * normalize the meta information to utf8.
			 */
			strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
			decode_header(&sb);
			handle_header(&hdr_data[i], &sb);
			ret = 1;
			goto check_header_out;
		}
	}

	/* Content stuff */
	if (cmp_header(line, "Content-Type")) {
		len = strlen("Content-Type: ");
		strbuf_add(&sb, line->buf + len, line->len - len);
		decode_header(&sb);
		strbuf_insert(&sb, 0, "Content-Type: ", len);
		handle_content_type(&sb);
		ret = 1;
		goto check_header_out;
	}
	if (cmp_header(line, "Content-Transfer-Encoding")) {
		len = strlen("Content-Transfer-Encoding: ");
		strbuf_add(&sb, line->buf + len, line->len - len);
		decode_header(&sb);
		handle_content_transfer_encoding(&sb);
		ret = 1;
		goto check_header_out;
	}

	/* for inbody stuff */
	if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
		ret = 1; /* Should this return 0? */
		goto check_header_out;
	}
	if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
		for (i = 0; header[i]; i++) {
			if (!memcmp("Subject", header[i], 7)) {
				handle_header(&hdr_data[i], line);
				ret = 1;
				goto check_header_out;
			}
		}
	}

check_header_out:
	strbuf_release(&sb);
	return ret;
}
Exemplo n.º 2
0
Arquivo: mailinfo.c Projeto: 9b/git
static int check_header(struct mailinfo *mi,
			const struct strbuf *line,
			struct strbuf *hdr_data[], int overwrite)
{
	int i, ret = 0, len;
	struct strbuf sb = STRBUF_INIT;

	/* search for the interesting parts */
	for (i = 0; header[i]; i++) {
		int len = strlen(header[i]);
		if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
			/* Unwrap inline B and Q encoding, and optionally
			 * normalize the meta information to utf8.
			 */
			strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
			decode_header(mi, &sb);
			handle_header(&hdr_data[i], &sb);
			ret = 1;
			goto check_header_out;
		}
	}

	/* Content stuff */
	if (cmp_header(line, "Content-Type")) {
		len = strlen("Content-Type: ");
		strbuf_add(&sb, line->buf + len, line->len - len);
		decode_header(mi, &sb);
		strbuf_insert(&sb, 0, "Content-Type: ", len);
		handle_content_type(mi, &sb);
		ret = 1;
		goto check_header_out;
	}
	if (cmp_header(line, "Content-Transfer-Encoding")) {
		len = strlen("Content-Transfer-Encoding: ");
		strbuf_add(&sb, line->buf + len, line->len - len);
		decode_header(mi, &sb);
		handle_content_transfer_encoding(mi, &sb);
		ret = 1;
		goto check_header_out;
	}
	if (cmp_header(line, "Message-Id")) {
		len = strlen("Message-Id: ");
		strbuf_add(&sb, line->buf + len, line->len - len);
		decode_header(mi, &sb);
		if (mi->add_message_id)
			mi->message_id = strbuf_detach(&sb, NULL);
		ret = 1;
		goto check_header_out;
	}

check_header_out:
	strbuf_release(&sb);
	return ret;
}
Exemplo n.º 3
0
static int check_header(char *line, unsigned linesize, char **hdr_data, int overwrite)
{
	int i;

	/* search for the interesting parts */
	for (i = 0; header[i]; i++) {
		int len = strlen(header[i]);
		if ((!hdr_data[i] || overwrite) &&
		    !strncasecmp(line, header[i], len) &&
		    line[len] == ':' && isspace(line[len + 1])) {
			/* Unwrap inline B and Q encoding, and optionally
			 * normalize the meta information to utf8.
			 */
			decode_header(line + len + 2, linesize - len - 2);
			hdr_data[i] = xmalloc(1000 * sizeof(char));
			if (! handle_header(line, hdr_data[i], len + 2)) {
				return 1;
			}
		}
	}

	/* Content stuff */
	if (!strncasecmp(line, "Content-Type", 12) &&
		line[12] == ':' && isspace(line[12 + 1])) {
		decode_header(line + 12 + 2, linesize - 12 - 2);
		if (! handle_content_type(line)) {
			return 1;
		}
	}
	if (!strncasecmp(line, "Content-Transfer-Encoding", 25) &&
		line[25] == ':' && isspace(line[25 + 1])) {
		decode_header(line + 25 + 2, linesize - 25 - 2);
		if (! handle_content_transfer_encoding(line)) {
			return 1;
		}
	}

	/* for inbody stuff */
	if (!memcmp(">From", line, 5) && isspace(line[5]))
		return 1;
	if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
		for (i = 0; header[i]; i++) {
			if (!memcmp("Subject: ", header[i], 9)) {
				if (! handle_header(line, hdr_data[i], 0)) {
					return 1;
				}
			}
		}
	}

	/* no match */
	return 0;
}
Exemplo n.º 4
0
/*
 * Read a soft-character definition string from a file.  Strip off garbage
 * at the beginning (to accommodate the "font2xx" output format).
 */
void
setup_softchars(const char *filename)
{
  FILE *fp;
  int c;
  size_t len = 1024;
  size_t use = 0;
  char *buffer = (char *) malloc(len);
  char *s;
  char *first = 0;
  char *last = 0;
  int save_8bits = input_8bits;
  input_8bits = FALSE;  /* use the 7-bit input-parsing */

  /* read the file into memory */
  if ((fp = fopen(filename, "r")) == 0) {
    perror(filename);
    exit(EXIT_FAILURE);
  }
  while ((c = fgetc(fp)) != EOF) {
    if (use + 1 >= len) {
      buffer = (char *) realloc(buffer, len *= 2);
    }
    buffer[use++] = (char) c;
  }
  buffer[use] = '\0';
  fclose(fp);

  /* find the DCS that begins the control string */
  /* and the ST that ends the control string */
  for (s = buffer; *s; s++) {
    if (first == 0) {
      if (skip_dcs(s) != 0)
        first = s;
    } else {
      if (!strncmp(s, st_input(), (size_t) 2)) {
        last = s + 2;
        *last = '\0';
        break;
      }
    }
  }
  input_8bits = save_8bits;

  if (first == 0 || last == 0) {
    fprintf(stderr, "Not a vtXXX font description: %s\n", filename);
    exit(EXIT_FAILURE);
  }
  for (s = buffer; (*s++ = *first++) != '\0';) ;
  if (LOG_ENABLED && first != 0)
    fprintf(log_fp, "Font String:\n%s\n", buffer);

  font_string = buffer;

  decode_header();
}
Exemplo n.º 5
0
Sfoff_t huffdecode(register Huff_t *hp,Sfio_t *input,Sfio_t *output,int size)
{
	register long buffer;
	register int left, i, n;
	register int lev = 0;
	register unsigned char *outp;
	register unsigned char *inp;
	unsigned char *outend;
	unsigned char *outbuff;
	Sfoff_t insize = hp->outsize;
	/* decode the header if called with different hp */
	if(lastid!=hp->id)
	{
		decode_header(hp);
		if(!hp->id)
			hp->id = id++;
		lastid = hp->id;
	}
	/* set up output buffers for faster access */
	if(!(outp=outbuff=(unsigned char*)sfreserve(output,SF_UNBOUND,SF_LOCKR)))
		return(sfvalue(output));
	n = sfvalue(output);
	if(size>=0)
	{
		if(n > size)
			n = size;
		size -= n;
	}
	outend = outp+n;
	/* set up input buffers for faster access */
	infile = input;
	if(!(inp=inbuff=(unsigned char*)sfreserve(infile,SF_UNBOUND,0)))
		return(sfvalue(infile));
	inend = inp + sfvalue(infile);
	buffer = hp->buffer;
	left = hp->left;
	/* main decoding loop */
	while (1)
	{
		if(lev==0)
		{
			fillbuff(buffer,left,hp->maxlev,inp);
			i = getbits(buffer,left,CHUNK);
			if((n=(numbits[i]-1)) >= 0)
			{
				putbits(buffer,left,n);
				*outp++ = outchar[i];
				goto pout;
			}
			if(hp->excess)
			{
				putbits(buffer,left,hp->excess);
				i >>= hp->excess;
			}
			lev = CHUNK-hp->excess;
		}
Exemplo n.º 6
0
	void do_read_header() {
		auto self(shared_from_this());
		boost::asio::async_read(socket_, boost::asio::buffer(header_data_, HEADER_LENGTH),
			[this, self](boost::system::error_code ec, std::size_t) {
			if (!ec) {
				do_read_body(decode_header());
			}
		}
		);
	}
Exemplo n.º 7
0
	PNGLoader::PNGLoader(IODevice iodevice, bool force_srgb)
		: file(iodevice), force_srgb(force_srgb), scanline(nullptr), prev_scanline(nullptr), scanline_4ub(nullptr), scanline_4us(nullptr), palette(nullptr)
	{
		read_magic();
		read_chunks();
		decode_header();
		decode_palette();
		decode_colorkey();
		decode_image();
	}
Exemplo n.º 8
0
	//-------------------------------------------------------------
	//
	void NetClient::handle_read_header(const boost::system::error_code& error)
	{
		if (!error && decode_header())
		{
			m_read.resize(m_nHeadCount);
			boost::asio::async_read(m_socket,
				boost::asio::buffer(m_read.bytes(), m_nHeadCount),
				boost::bind(&NetClient::handle_read_body, this,
				boost::asio::placeholders::error));
		}
		else
		{
			throwError(error);
		}
	}
Exemplo n.º 9
0
MonitorInfo * decode_edid(const uint8_t *edid) {
    MonitorInfo *info = new MonitorInfo();
    decode_check_sum(edid, info);
    if (decode_header(edid) && //
            decode_vendor_and_product_identification(edid, info) && //
            decode_edid_version(edid, info) && //
            decode_display_parameters(edid, info) && //
            decode_color_characteristics(edid, info) && //
            decode_established_timings(edid, info) && //
            decode_standard_timings(edid, info) && //
            decode_descriptors(edid, info)) {
        return info;
    } else {
        delete info;
        return 0;
    }
}
Exemplo n.º 10
0
int MPGLIB_DecodeFrame(PMPSTR mp, const unsigned char* in, void* out)
{
    int done;
    
    /* First decode header */
    mp->header =
        (((unsigned long)in[0]) << 24) |
        (((unsigned long)in[1]) << 16) |
        (((unsigned long)in[2]) <<  8) |
        (((unsigned long)in[3]));
    decode_header(&mp->fr, mp->header);
    mp->framesize = mp->fr.framesize;

    mp->wordpointer = mp->bsspace[mp->bsnum] + 512;
    mp->bsnum = (mp->bsnum + 1) & 0x1;
    mp->bitindex = 0;

    memcpy(mp->wordpointer, in+4, mp->framesize);

    done = 0;
    if(mp->fr.error_protection)
        getbits(mp, 16);
    switch(mp->fr.lay) {
      case 1:
        do_layer1(mp,(unsigned char *) out, &done);
        break;
      case 2:
        do_layer2(mp,(unsigned char *) out, &done);
        break;
      case 3:
        do_layer3(mp,(unsigned char *) out, &done, synth_1to1_mono, synth_1to1);
        break;
    }
    
    mp->fsizeold = mp->framesize;
    mp->framesize = 0;
    
    if (done) {
        return MP3_OK;
    } else {
        return MP3_INVALID_BITS;
    }
}
Exemplo n.º 11
0
MonitorInfo *
decode_edid (const uchar *edid)
{
    MonitorInfo *info = calloc (1, sizeof (MonitorInfo));

    decode_check_sum (edid, info);

    if (!decode_header (edid) ||
        !decode_vendor_and_product_identification (edid, info) ||
        !decode_edid_version (edid, info) ||
        !decode_display_parameters (edid, info) ||
        !decode_color_characteristics (edid, info) ||
        !decode_established_timings (edid, info) ||
        !decode_standard_timings (edid, info) ||
        !decode_descriptors (edid, info)) {
        free(info);
	return NULL;
    }

    return info;
}
Exemplo n.º 12
0
MonitorInfo *
decode_edid (const uchar *edid)
{
    MonitorInfo *info = g_new0 (MonitorInfo, 1);

    decode_check_sum (edid, info);

    if (decode_header (edid)
	&& decode_vendor_and_product_identification (edid, info)
	&& decode_edid_version (edid, info)
	&& decode_display_parameters (edid, info)
	&& decode_color_characteristics (edid, info)
	&& decode_established_timings (edid, info)
	&& decode_standard_timings (edid, info)
	&& decode_descriptors (edid, info))
    {
	return info;
    }
    else
    {
	g_free (info);
	return NULL;
    }
}
Exemplo n.º 13
0
/*
 * Extract a file from the archive.
 */
void
extract_archive ()
{
  register char *data;
  int fd, check, namelen, written, openflag;
  long size;
  struct utimbuf acc_upd_times;
  register int skipcrud;
  register int i;
  /*	int sparse_ind = 0;*/
  union record *exhdr;
  struct saved_dir_info *tmp;
  /*	int end_nulls; */

  saverec (&head);		/* Make sure it sticks around */
  userec (head);		/* And go past it in the archive */
  decode_header (head, &hstat, &head_standard, 1);	/* Snarf fields */

  if ((f_confirm && !confirm ("extract", current_file_name)) ||
      (f_exstdout && head->header.linkflag != LF_OLDNORMAL &&
       head->header.linkflag != LF_NORMAL &&
       head->header.linkflag != LF_CONTIG))
    {
      if (head->header.isextended)
	skip_extended_headers ();
      skip_file ((long) hstat.st_size);
      saverec ((union record **) 0);
      return;
    }

  /* Print the record from 'head' and 'hstat' */
  if (f_verbose)
    print_header ();

  /*
	 * Check for fully specified pathnames and other atrocities.
	 *
	 * Note, we can't just make a pointer to the new file name,
	 * since saverec() might move the header and adjust "head".
	 * We have to start from "head" every time we want to touch
	 * the header record.
	 */
  skipcrud = 0;
  while (!f_absolute_paths
	 && '/' == current_file_name[skipcrud])
    {
      static int warned_once = 0;

      skipcrud++;		/* Force relative path */
      if (!warned_once++)
	{
	  msg ("Removing leading / from absolute path names in the archive.");
	}
    }

  switch (head->header.linkflag)
    {

    default:
      msg ("Unknown file type '%c' for %s, extracted as normal file",
	   head->header.linkflag, skipcrud + current_file_name);
      /* FALL THRU */

      /*
	  * JK - What we want to do if the file is sparse is loop through
	  * the array of sparse structures in the header and read in
	  * and translate the character strings representing  1) the offset
	  * at which to write and 2) how many bytes to write into numbers,
	  * which we store into the scratch array, "sparsearray".  This
	  * array makes our life easier the same way it did in creating
	  * the tar file that had to deal with a sparse file.
	  *
	  * After we read in the first five (at most) sparse structures,
	  * we check to see if the file has an extended header, i.e.,
	  * if more sparse structures are needed to describe the contents
	  * of the new file.  If so, we read in the extended headers
	  * and continue to store their contents into the sparsearray.
	  */
    case LF_SPARSE:
      sp_array_size = 10;
      sparsearray = (struct sp_array *) ck_malloc (sp_array_size * sizeof (struct sp_array));
      for (i = 0; i < SPARSE_IN_HDR; i++)
	{
	  sparsearray[i].offset =
	    from_oct (1 + 12, head->header.sp[i].offset);
	  sparsearray[i].numbytes =
	    from_oct (1 + 12, head->header.sp[i].numbytes);
	  if (!sparsearray[i].numbytes)
	    break;
	}

      /*		end_nulls = from_oct(1+12, head->header.ending_blanks);*/

      if (head->header.isextended)
	{
	  /* read in the list of extended headers
			    and translate them into the sparsearray
			    as before */

	  /* static */ int ind = SPARSE_IN_HDR;

	  for (;;)
	    {

	      exhdr = findrec ();
	      for (i = 0; i < SPARSE_EXT_HDR; i++)
		{

		  if (i + ind > sp_array_size - 1)
		    {
		      /*
					  * realloc the scratch area
					  * since we've run out of room --
					  */
		      sparsearray = (struct sp_array *)
			ck_realloc (sparsearray,
			    2 * sp_array_size * (sizeof (struct sp_array)));
		      sp_array_size *= 2;
		    }
		  if (!exhdr->ext_hdr.sp[i].numbytes)
		    break;
		  sparsearray[i + ind].offset =
		    from_oct (1 + 12, exhdr->ext_hdr.sp[i].offset);
		  sparsearray[i + ind].numbytes =
		    from_oct (1 + 12, exhdr->ext_hdr.sp[i].numbytes);
		}
	      if (!exhdr->ext_hdr.isextended)
		break;
	      else
		{
		  ind += SPARSE_EXT_HDR;
		  userec (exhdr);
		}
	    }
	  userec (exhdr);
	}

      /* FALL THRU */
    case LF_OLDNORMAL:
    case LF_NORMAL:
    case LF_CONTIG:
      /*
		  * Appears to be a file.
		  * See if it's really a directory.
		  */
      namelen = strlen (skipcrud + current_file_name) - 1;
      if (current_file_name[skipcrud + namelen] == '/')
	goto really_dir;

      /* FIXME, deal with protection issues */
    again_file:
      openflag = (f_keep ?
		  O_BINARY | O_NDELAY | O_WRONLY | O_CREAT | O_EXCL :
		  O_BINARY | O_NDELAY | O_WRONLY | O_CREAT | O_TRUNC)
	| ((head->header.linkflag == LF_SPARSE) ? 0 : O_APPEND);
      /*
			  * JK - The last | is a kludge to solve the problem
			  * the O_APPEND flag  causes with files we are
			  * trying to make sparse:  when a file is opened
			  * with O_APPEND, it writes  to the last place
			  * that something was written, thereby ignoring
			  * any lseeks that we have done.  We add this
			  * extra condition to make it able to lseek when
			  * a file is sparse, i.e., we don't open the new
			  * file with this flag.  (Grump -- this bug caused
			  * me to waste a good deal of time, I might add)
			  */

      if (f_exstdout)
	{
	  fd = 1;
	  goto extract_file;
	}

      if (f_unlink && !f_keep) {
	if (unlink(skipcrud + current_file_name) == -1)
		if (errno != ENOENT)
		   msg_perror ("Could not unlink %s",
                      skipcrud + current_file_name);
      }

#ifdef O_CTG
      /*
		  * Contiguous files (on the Masscomp) have to specify
		  * the size in the open call that creates them.
		  */
      if (head->header.linkflag == LF_CONTIG)
	fd = open ((longname ? longname : head->header.name)
		   + skipcrud,
		   openflag | O_CTG,
		   hstat.st_mode, hstat.st_size);
      else
#endif
	{
#ifdef NO_OPEN3
	  /*
			  * On raw V7 we won't let them specify -k (f_keep), but
			  * we just bull ahead and create the files.
			  */
	  fd = creat ((longname
		       ? longname
		       : head->header.name) + skipcrud,
		      hstat.st_mode);
#else
	  /*
			  * With 3-arg open(), we can do this up right.
			  */
	  fd = open (skipcrud + current_file_name,
		     openflag, hstat.st_mode);
#endif
	}

      if (fd < 0)
	{
	  if (make_dirs (skipcrud + current_file_name))
	    goto again_file;
	  msg_perror ("Could not create file %s",
		      skipcrud + current_file_name);
	  if (head->header.isextended)
	    skip_extended_headers ();
	  skip_file ((long) hstat.st_size);
	  goto quit;
	}

    extract_file:
      if (head->header.linkflag == LF_SPARSE)
	{
	  char *name;
	  int namelen;

	  /*
			  * Kludge alert.  NAME is assigned to header.name
			  * because during the extraction, the space that
			  * contains the header will get scribbled on, and
			  * the name will get munged, so any error messages
			  * that happen to contain the filename will look
			  * REAL interesting unless we do this.
			  */
	  namelen = strlen (skipcrud + current_file_name) + 1;
	  name = (char *) ck_malloc ((sizeof (char)) * namelen);
	  bcopy (skipcrud + current_file_name, name, namelen);
	  size = hstat.st_size;
	  extract_sparse_file (fd, &size, hstat.st_size, name);
	}
      else
	for (size = hstat.st_size;
	     size > 0;
	     size -= written)
	  {

	    /*			long	offset,
				 numbytes;*/

	    if (f_multivol)
	      {
		save_name = current_file_name;
		save_totsize = hstat.st_size;
		save_sizeleft = size;
	      }

	    /*
			  * Locate data, determine max length
			  * writeable, write it, record that
			  * we have used the data, then check
			  * if the write worked.
			  */
	    data = findrec ()->charptr;
	    if (data == NULL)
	      {			/* Check it... */
		msg ("Unexpected EOF on archive file");
		break;
	      }
	    /*
			  * JK - If the file is sparse, use the sparsearray
			  * that we created before to lseek into the new
			  * file the proper amount, and to see how many
			  * bytes we want to write at that position.
			  */
	    /*			if (head->header.linkflag == LF_SPARSE) {
				 off_t pos;

				 pos = lseek(fd, (off_t) sparsearray[sparse_ind].offset, 0);
				 printf("%d at %d\n", (int) pos, sparse_ind);
				 written = sparsearray[sparse_ind++].numbytes;
			 } else*/
	    written = endofrecs ()->charptr - data;
	    if (written > size)
	      written = size;
	    errno = 0;
	    check = write (fd, data, written);
	    /*
			  * The following is in violation of strict
			  * typing, since the arg to userec
			  * should be a struct rec *.  FIXME.
			  */
	    userec ((union record *) (data + written - 1));
	    if (check == written)
	      continue;
	    /*
			  * Error in writing to file.
			  * Print it, skip to next file in archive.
			  */
	    if (check < 0)
	      msg_perror ("couldn't write to file %s",
			  skipcrud + current_file_name);
	    else
	      msg ("could only write %d of %d bytes to file %s",
		   check, written, skipcrud + current_file_name);
	    skip_file ((long) (size - written));
	    break;		/* Still do the close, mod time, chmod, etc */
	  }

      if (f_multivol)
	save_name = 0;

      /* If writing to stdout, don't try to do anything
			    to the filename; it doesn't exist, or we don't
			    want to touch it anyway */
      if (f_exstdout)
	break;

      /*		if (head->header.isextended) {
			 register union record *exhdr;
			 register int i;

			 for (i = 0; i < 21; i++) {
				 long offset;

				 if (!exhdr->ext_hdr.sp[i].numbytes)
					 break;
				 offset = from_oct(1+12,
						 exhdr->ext_hdr.sp[i].offset);
				 written = from_oct(1+12,
						 exhdr->ext_hdr.sp[i].numbytes);
				 lseek(fd, offset, 0);
				 check = write(fd, data, written);
				 if (check == written) continue;

			 }


		 }*/
      check = close (fd);
      if (check < 0)
	{
	  msg_perror ("Error while closing %s",
		      skipcrud + current_file_name);
	}


    set_filestat:

      /*
		  * If we are root, set the owner and group of the extracted
		  * file.  This does what is wanted both on real Unix and on
		  * System V.  If we are running as a user, we extract as that
		  * user; if running as root, we extract as the original owner.
		  */
      if (we_are_root || f_do_chown)
	{
	  if (chown (skipcrud + current_file_name,
		     hstat.st_uid, hstat.st_gid) < 0)
	    {
	      msg_perror ("cannot chown file %s to uid %d gid %d",
			  skipcrud + current_file_name,
			  hstat.st_uid, hstat.st_gid);
	    }
	}

      /*
       * Set the modified time of the file.
       *
       * Note that we set the accessed time to "now", which
       * is really "the time we started extracting files".
       * unless f_gnudump is used, in which case .st_atime is used
       */
      if (!f_modified)
	{
	  /* fixme if f_gnudump should set ctime too, but how? */
	  if (f_gnudump)
	    acc_upd_times.actime = hstat.st_atime;
	  else
	    acc_upd_times.actime = now;	/* Accessed now */
	  acc_upd_times.modtime = hstat.st_mtime;	/* Mod'd */
	  if (utime (skipcrud + current_file_name,
		     &acc_upd_times) < 0)
	    {
	      msg_perror ("couldn't change access and modification times of %s", skipcrud + current_file_name);
	    }
	}
      /* We do the utime before the chmod because some versions of
		   utime are broken and trash the modes of the file.  Since
		   we then change the mode anyway, we don't care. . . */

      /*
		 * If '-k' is not set, open() or creat() could have saved
		 * the permission bits from a previously created file,
		 * ignoring the ones we specified.
		 * Even if -k is set, if the file has abnormal
		 * mode bits, we must chmod since writing or chown() has
		 * probably reset them.
		 *
		 * If -k is set, we know *we* created this file, so the mode
		 * bits were set by our open().   If the file is "normal", we
		 * skip the chmod.  This works because we did umask(0) if -p
		 * is set, so umask will have left the specified mode alone.
		 */
      if ((!f_keep)
	  || (hstat.st_mode & (S_ISUID | S_ISGID | S_ISVTX)))
	{
	  if (chmod (skipcrud + current_file_name,
		     notumask & (int) hstat.st_mode) < 0)
	    {
	      msg_perror ("cannot change mode of file %s to 0%o",
			  skipcrud + current_file_name,
			  notumask & (int) hstat.st_mode);
	    }
	}

    quit:
      break;

    case LF_LINK:
    again_link:
      {
	struct stat st1, st2;

        if (f_unlink && !f_keep) {
	  if (unlink(skipcrud + current_file_name) == -1)
		if (errno != ENOENT)
		   msg_perror ("Could not unlink %s",
                      skipcrud + current_file_name);
        }

	check = link (current_link_name, skipcrud + current_file_name);

	if (check == 0)
	  break;
	if (make_dirs (skipcrud + current_file_name))
	  goto again_link;
	if (f_gnudump && errno == EEXIST)
	  break;
	if (stat (current_link_name, &st1) == 0
	    && stat (current_file_name + skipcrud, &st2) == 0
	    && st1.st_dev == st2.st_dev
	    && st1.st_ino == st2.st_ino)
	  break;
	msg_perror ("Could not link %s to %s",
		    skipcrud + current_file_name,
		    current_link_name);
      }
      break;

#ifdef S_ISLNK
    case LF_SYMLINK:
    again_symlink:
      if (f_unlink && !f_keep) {
	  if (unlink(skipcrud + current_file_name) == -1)
		if (errno != ENOENT)
		   msg_perror ("Could not unlink %s",
                      skipcrud + current_file_name);
      }

      check = symlink (current_link_name,
		       skipcrud + current_file_name);
      /* FIXME, don't worry uid, gid, etc... */
      if (check == 0)
	break;
      if (make_dirs (current_file_name + skipcrud))
	goto again_symlink;
      msg_perror ("Could not create symlink to %s",
		  current_link_name);
      break;
#endif

#ifdef S_IFCHR
    case LF_CHR:
      hstat.st_mode |= S_IFCHR;
      goto make_node;
#endif

#ifdef S_IFBLK
    case LF_BLK:
      hstat.st_mode |= S_IFBLK;
#endif
#if defined(S_IFCHR) || defined(S_IFBLK)
    make_node:
      if (f_unlink && !f_keep) {
	  if (unlink(skipcrud + current_file_name) == -1)
		if (errno != ENOENT)
		   msg_perror ("Could not unlink %s",
                      skipcrud + current_file_name);
      }

      check = mknod (current_file_name + skipcrud,
		     (int) hstat.st_mode, (int) hstat.st_rdev);
      if (check != 0)
	{
	  if (make_dirs (skipcrud + current_file_name))
	    goto make_node;
	  msg_perror ("Could not make %s",
		      current_file_name + skipcrud);
	  break;
	};
      goto set_filestat;
#endif

#ifdef S_ISFIFO
      /* If local system doesn't support FIFOs, use default case */
    case LF_FIFO:
    make_fifo:
      if (f_unlink && !f_keep) {
	  if (unlink(skipcrud + current_file_name) == -1)
		if (errno != ENOENT)
		   msg_perror ("Could not unlink %s",
                      skipcrud + current_file_name);
      }

      check = mkfifo (current_file_name + skipcrud,
		      (int) hstat.st_mode);
      if (check != 0)
	{
	  if (make_dirs (current_file_name + skipcrud))
	    goto make_fifo;
	  msg_perror ("Could not make %s",
		      skipcrud + current_file_name);
	  break;
	};
      goto set_filestat;
#endif

    case LF_DIR:
    case LF_DUMPDIR:
      namelen = strlen (current_file_name + skipcrud) - 1;
    really_dir:
      /* Check for trailing /, and zap as many as we find. */
      while (namelen
	     && current_file_name[skipcrud + namelen] == '/')
	current_file_name[skipcrud + namelen--] = '\0';
      if (f_gnudump)
	{			/* Read the entry and delete files
					   that aren't listed in the archive */
	  gnu_restore (skipcrud);

	}
      else if (head->header.linkflag == LF_DUMPDIR)
	skip_file ((long) (hstat.st_size));


    again_dir:
      check = mkdir (skipcrud + current_file_name,
		     (we_are_root ? 0 : 0300) | (int) hstat.st_mode);
      if (check != 0)
	{
	  struct stat st1;

	  if (make_dirs (skipcrud + current_file_name))
	    goto again_dir;
	  /* If we're trying to create '.', let it be. */
	  if (current_file_name[skipcrud + namelen] == '.' &&
	      (namelen == 0 ||
	       current_file_name[skipcrud + namelen - 1] == '/'))
	    goto check_perms;
	  if (errno == EEXIST
	      && stat (skipcrud + current_file_name, &st1) == 0
	      && (S_ISDIR (st1.st_mode)))
	    break;
	  msg_perror ("Could not create directory %s", skipcrud + current_file_name);
	  break;
	}

    check_perms:
      if (!we_are_root && 0300 != (0300 & (int) hstat.st_mode))
	{
	  hstat.st_mode |= 0300;
	  msg ("Added write and execute permission to directory %s",
	       skipcrud + current_file_name);
	}

      /*
       * If we are root, set the owner and group of the extracted
       * file.  This does what is wanted both on real Unix and on
       * System V.  If we are running as a user, we extract as that
       * user; if running as root, we extract as the original owner.
       */
      if (we_are_root || f_do_chown)
	{
	  if (chown (skipcrud + current_file_name,
		     hstat.st_uid, hstat.st_gid) < 0)
	    {
	      msg_perror ("cannot chown file %s to uid %d gid %d",
			  skipcrud + current_file_name,
			  hstat.st_uid, hstat.st_gid);
	    }
	}

      if (!f_modified)
	{
	  tmp = ((struct saved_dir_info *)
		 ck_malloc (sizeof (struct saved_dir_info)));
	  tmp->path = (char *) ck_malloc (strlen (skipcrud
						  + current_file_name) + 1);
	  strcpy (tmp->path, skipcrud + current_file_name);
	  tmp->mode = hstat.st_mode;
	  tmp->atime = hstat.st_atime;
	  tmp->mtime = hstat.st_mtime;
	  tmp->next = saved_dir_info_head;
	  saved_dir_info_head = tmp;
	}
      else
	{
	  /* This functions exactly as the code for set_filestat above. */
	  if ((!f_keep)
	      || (hstat.st_mode & (S_ISUID | S_ISGID | S_ISVTX)))
	    {
	      if (chmod (skipcrud + current_file_name,
			 notumask & (int) hstat.st_mode) < 0)
		{
		  msg_perror ("cannot change mode of file %s to 0%o",
			      skipcrud + current_file_name,
			      notumask & (int) hstat.st_mode);
		}
	    }
	}
      break;

    case LF_VOLHDR:
      if (f_verbose)
	{
	  printf ("Reading %s\n", current_file_name);
	}
      break;

    case LF_NAMES:
      extract_mangle (head);
      break;

    case LF_MULTIVOL:
      msg ("Can't extract '%s'--file is continued from another volume\n", current_file_name);
      skip_file ((long) hstat.st_size);
      break;

    case LF_LONGNAME:
    case LF_LONGLINK:
      msg ("Visible long name error\n");
      skip_file ((long) hstat.st_size);
      break;
    }

  /* We don't need to save it any longer. */
  saverec ((union record **) 0);/* Unsave it */
}
Exemplo n.º 14
0
bool lsb_find_heka_message(lsb_heka_message *m,
                           lsb_input_buffer *ib,
                           bool decode,
                           size_t *discarded_bytes,
                           lsb_logger *logger)
{
  if (!m || !ib || !discarded_bytes) {
    if (logger && logger->cb) {
      logger->cb(logger->context, __func__, 4, LSB_ERR_UTIL_NULL);
    }
    return false;
  }

  *discarded_bytes = 0;
  if (ib->readpos == ib->scanpos) {
    return false; // empty buffer
  }

  char *p = memchr(&ib->buf[ib->scanpos], 0x1e, ib->readpos - ib->scanpos);
  if (p) {
    if (p != ib->buf + ib->scanpos) {
      // partial buffer skipped before locating a possible header
      *discarded_bytes += p - ib->buf - ib->scanpos;
    }
    ib->scanpos = p - ib->buf;

    if (ib->readpos - ib->scanpos < 2) {
      return false; // header length is not buf
    }

    size_t hlen = (unsigned char)ib->buf[ib->scanpos + 1];
    size_t hend = ib->scanpos + hlen + 3;
    if (hend > ib->readpos) {
      return false; // header is not in buf
    }
    if (ib->buf[hend - 1] != 0x1f) {
      // invalid header length
      ++ib->scanpos;
      ++*discarded_bytes;
      size_t db;
      bool b =  lsb_find_heka_message(m, ib, decode, &db, logger);
      *discarded_bytes += db;
      return b;
    }

    if (!ib->msglen) {
      ib->msglen = decode_header(&ib->buf[ib->scanpos + 2], hlen,
                                 ib->maxsize - LSB_MAX_HDR_SIZE);
    }

    if (ib->msglen) {
      size_t mend = hend + ib->msglen;
      if (mend > ib->readpos) {
        return false; // message is not in buf
      }

      if (decode) {
        if (lsb_decode_heka_message(m, &ib->buf[hend], ib->msglen, logger)) {
          ib->scanpos = mend;
          ib->msglen = 0;
          return true;
        } else {
          // message decode failure
          ++ib->scanpos;
          ++*discarded_bytes;
          ib->msglen = 0;
          size_t db;
          bool b =  lsb_find_heka_message(m, ib, decode, &db, logger);
          *discarded_bytes += db;
          return b;
        }
      } else {
        // allow a framed message is non Heka protobuf format
        lsb_clear_heka_message(m);
        m->raw.s = &ib->buf[hend];
        m->raw.len = ib->msglen;
        ib->scanpos = mend;
        ib->msglen = 0;
        return true;
      }
    } else {
      // header decode failure
      ++ib->scanpos;
      ++*discarded_bytes;
      size_t db;
      bool b =  lsb_find_heka_message(m, ib, decode, &db, logger);
      *discarded_bytes += db;
      return b;
    }
  } else {
    // full buffer skipped since no header was located
    *discarded_bytes += ib->readpos - ib->scanpos;
    ib->scanpos = ib->readpos = 0;
  }
  return false;
}
Exemplo n.º 15
0
void
diff_archive (void)
{
  register char *data;
  int check, namelen;
  int err;
  off_t offset;
  struct stat filestat;

#ifndef __MSDOS__
  dev_t dev;
  ino_t ino;
#endif

  errno = EPIPE;		/* FIXME, remove perrors */

  saverec (&head);		/* make sure it sticks around */
  userec (head);		/* and go past it in the archive */
  decode_header (head, &hstat, &head_standard, 1);	/* snarf fields */

  /* Print the record from `head' and `hstat'.  */

  if (flag_verbose)
    {
      if (now_verifying)
	fprintf (stdlis, _("Verify "));
      print_header ();
    }

  switch (head->header.linkflag)
    {

    default:
      WARN ((0, 0, _("Unknown file type '%c' for %s, diffed as normal file"),
		 head->header.linkflag, current_file_name));
      /* Fall through.  */

    case LF_OLDNORMAL:
    case LF_NORMAL:
    case LF_SPARSE:
    case LF_CONTIG:

      /* Appears to be a file.  See if it's really a directory.  */

      namelen = strlen (current_file_name) - 1;
      if (current_file_name[namelen] == '/')
	goto really_dir;

      if (do_stat (&filestat))
	{
	  if (head->header.isextended)
	    skip_extended_headers ();
	  skip_file ((long) hstat.st_size);
	  different++;
	  goto quit;
	}

      if (!S_ISREG (filestat.st_mode))
	{
	  fprintf (stdlis, _("%s: Not a regular file\n"), current_file_name);
	  skip_file ((long) hstat.st_size);
	  different++;
	  goto quit;
	}

      filestat.st_mode &= 07777;
      if (filestat.st_mode != hstat.st_mode)
	sigh (_("Mode"));
      if (filestat.st_uid != hstat.st_uid)
	sigh (_("Uid"));
      if (filestat.st_gid != hstat.st_gid)
	sigh (_("Gid"));
      if (filestat.st_mtime != hstat.st_mtime)
	sigh (_("Mod time"));
      if (head->header.linkflag != LF_SPARSE &&
	  filestat.st_size != hstat.st_size)
	{
	  sigh (_("Size"));
	  skip_file ((long) hstat.st_size);
	  goto quit;
	}

      diff_fd = open (current_file_name, O_NDELAY | O_RDONLY | O_BINARY);

      if (diff_fd < 0 && !flag_absolute_names)
	{
	  char *tmpbuf = tar_xmalloc (strlen (current_file_name) + 2);

	  *tmpbuf = '/';
	  strcpy (tmpbuf + 1, current_file_name);
	  diff_fd = open (tmpbuf, O_NDELAY | O_RDONLY);
	  free (tmpbuf);
	}
      if (diff_fd < 0)
	{
	  ERROR ((0, errno, _("Cannot open %s"), current_file_name));
	  if (head->header.isextended)
	    skip_extended_headers ();
	  skip_file ((long) hstat.st_size);
	  different++;
	  goto quit;
	}

      /* Need to treat sparse files completely differently here.  */

      if (head->header.linkflag == LF_SPARSE)
	diff_sparse_files (hstat.st_size);
      else
	{
	  if (flag_multivol)
	    {
	      assign_string (&save_name, current_file_name);
	      save_totsize = hstat.st_size;
	      /* save_size is set in wantbytes ().  */
	    }
	  wantbytes ((long) (hstat.st_size), compare_chunk);
	  if (flag_multivol)
	    assign_string (&save_name, NULL);
	}

      check = close (diff_fd);
      if (check < 0)
	ERROR ((0, errno, _("Error while closing %s"), current_file_name));

    quit:
      break;

#ifndef __MSDOS__
    case LF_LINK:
      if (do_stat (&filestat))
	break;
      dev = filestat.st_dev;
      ino = filestat.st_ino;
      err = stat (current_link_name, &filestat);
      if (err < 0)
	{
	  if (errno == ENOENT)
	    fprintf (stdlis, _("%s: Does not exist\n"), current_file_name);
	  else
	    WARN ((0, errno, _("Cannot stat file %s"), current_file_name));
	  different++;
	  break;
	}
      if (filestat.st_dev != dev || filestat.st_ino != ino)
	{
	  fprintf (stdlis, _("%s: Not linked to %s\n"),
		   current_file_name, current_link_name);
	  break;
	}
      break;
#endif

#ifdef S_ISLNK
    case LF_SYMLINK:
      {
	char linkbuf[NAMSIZ + 3]; /* FIXME: may be too short.  */

	check = readlink (current_file_name, linkbuf, (sizeof linkbuf) - 1);

	if (check < 0)
	  {
	    if (errno == ENOENT)
	      fprintf (stdlis, _("%s: No such file or directory\n"),
		       current_file_name);
	    else
	      WARN ((0, errno, _("Cannot read link %s"), current_file_name));
	    different++;
	    break;
	  }

	linkbuf[check] = '\0';	/* null-terminate it */
	if (strncmp (current_link_name, linkbuf, (size_t) check) != 0)
	  {
	    fprintf (stdlis, _("%s: Symlink differs\n"), current_link_name);
	    different++;
	  }
      }
      break;
#endif

#ifdef S_IFCHR
    case LF_CHR:
      hstat.st_mode |= S_IFCHR;
      goto check_node;
#endif

#ifdef S_IFBLK
      /* If local system doesn't support block devices, use default case.  */

    case LF_BLK:
      hstat.st_mode |= S_IFBLK;
      goto check_node;
#endif

#ifdef S_ISFIFO
      /* If local system doesn't support FIFOs, use default case.  */

    case LF_FIFO:
#ifdef S_IFIFO
      hstat.st_mode |= S_IFIFO;
#endif
      hstat.st_rdev = 0;	/* FIXME, do we need this? */
      goto check_node;
#endif

    check_node:
      /* FIXME, deal with umask.  */

      if (do_stat (&filestat))
	break;
      if (hstat.st_rdev != filestat.st_rdev)
	{
	  fprintf (stdlis, _("%s: Device numbers changed\n"),
		   current_file_name);
	  different++;
	  break;
	}
      if (
#ifdef S_IFMT
	  hstat.st_mode != filestat.st_mode
#else
	  /* POSIX lossage */
	  (hstat.st_mode & 07777) != (filestat.st_mode & 07777)
#endif
	  )
	{
	  fprintf (stdlis, _("%s: Mode or device-type changed\n"),
		   current_file_name);
	  different++;
	  break;
	}
      break;

    case LF_DUMPDIR:
      data = diff_dir = get_dir_contents (current_file_name, 0);
      if (flag_multivol)
	{
	  assign_string (&save_name, current_file_name);
	  save_totsize = hstat.st_size;
	  /* save_size is set in wantbytes ().  */
	}
      if (data)
	{
	  wantbytes ((long) (hstat.st_size), compare_dir);
	  free (data);
	}
      else
	wantbytes ((long) (hstat.st_size), no_op);
      if (flag_multivol)
	assign_string (&save_name, NULL);
      /* Fall through.  */

    case LF_DIR:
      /* Check for trailing /.  */

      namelen = strlen (current_file_name) - 1;

    really_dir:
      while (namelen && current_file_name[namelen] == '/')
	current_file_name[namelen--] = '\0';	/* zap / */

      if (do_stat (&filestat))
	break;
      if (!S_ISDIR (filestat.st_mode))
	{
	  fprintf (stdlis, _("%s: No longer a directory\n"),
		   current_file_name);
	  different++;
	  break;
	}
      if ((filestat.st_mode & 07777) != (hstat.st_mode & 07777))
	sigh (_("Mode"));
      break;

    case LF_VOLHDR:
      break;

    case LF_MULTIVOL:
      namelen = strlen (current_file_name) - 1;
      if (current_file_name[namelen] == '/')
	goto really_dir;

      if (do_stat (&filestat))
	break;

      if (!S_ISREG (filestat.st_mode))
	{
	  fprintf (stdlis, _("%s: Not a regular file\n"), current_file_name);
	  skip_file ((long) hstat.st_size);
	  different++;
	  break;
	}

      filestat.st_mode &= 07777;
      offset = from_oct (1 + 12, head->header.offset);
      if (filestat.st_size != hstat.st_size + offset)
	{
	  sigh (_("Size"));
	  skip_file ((long) hstat.st_size);
	  different++;
	  break;
	}

      diff_fd = open (current_file_name, O_NDELAY | O_RDONLY | O_BINARY);

      if (diff_fd < 0)
	{
	  WARN ((0, errno, _("Cannot open file %s"), current_file_name));
	  skip_file ((long) hstat.st_size);
	  different++;
	  break;
	}
      err = lseek (diff_fd, offset, 0);
      if (err != offset)
	{
	  WARN ((0, errno, _("Cannot seek to %ld in file %s"),
		     offset, current_file_name));
	  different++;
	  break;
	}

      if (flag_multivol)
	{
	  assign_string (&save_name, current_file_name);
	  save_totsize = filestat.st_size;
	  /* save_size is set in wantbytes ().  */
	}
      wantbytes ((long) (hstat.st_size), compare_chunk);
      if (flag_multivol)
	assign_string (&save_name, NULL);

      check = close (diff_fd);
      if (check < 0)
	ERROR ((0, errno, _("Error while closing %s"), current_file_name));
      break;

    }

  /* We don't need to save it any longer. */

  saverec ((union record **) 0);	/* unsave it */
}
Exemplo n.º 16
0
int decodeMP3(struct mpstr *mp, char *in, int isize,
              char *out, int osize, int *done)
{
    int len;

    if(osize < 4608) {
#ifndef BE_QUIET
        fprintf(stderr,"To less out space\n");
#endif
        return MP3_ERR;
    }

    if(in) {
        if(addbuf(mp, in, isize) == NULL) {
            return MP3_ERR;
        }
    }


    /* First decode header */
    if(mp->framesize == 0) {
        if(mp->bsize < 4) {
            return MP3_NEED_MORE;
        }
        read_head(mp);
        if(mp->tail)
            mp->ndatabegin = mp->tail->pos - 4;
        if (decode_header(mp, &mp->fr,mp->header) <= 0 )
            return MP3_ERR;

        mp->framesize = mp->fr.framesize;
    }

    /*	  printf(" fr.framesize = %i \n",mp->fr.framesize);
    	  printf(" bsize        = %i \n",mp->bsize);
    */

    if(mp->fr.framesize > mp->bsize) {
        return MP3_NEED_MORE;
    }
    mp->psd.wordpointer = mp->bsspace[mp->bsnum] + 512;
    mp->bsnum = (mp->bsnum + 1) & 0x1;
    mp->psd.bitindex = 0;

    len = 0;
    while(len < mp->framesize) {
        int nlen;
        int blen = mp->tail->size - mp->tail->pos;
        if( (mp->framesize - len) <= blen) {
            nlen = mp->framesize-len;
        }
        else {
            nlen = blen;
        }
        memcpy(mp->psd.wordpointer+len,mp->tail->pnt+mp->tail->pos,nlen);
        len += nlen;
        mp->tail->pos += nlen;
        mp->bsize -= nlen;
        if(mp->tail->pos == mp->tail->size) {
            remove_buf(mp);
        }
    }

    *done = 0;
    if(mp->fr.error_protection)
        getbits(&mp->psd, 16);

    // FOR mpglib.dll: see if error and return it
    if ((&mp->fr)->do_layer(&mp->psd, mp, &mp->fr, (unsigned char*) out, done) < 0)
        return MP3_ERR;

    mp->fsizeold = mp->framesize;
    mp->framesize = 0;
    return MP3_OK;
}
Exemplo n.º 17
0
void
list_archive (void)
{
  int isextended = 0;		/* to remember if current_header is extended */

  /* Print the header block.  */

  if (verbose_option)
    {
      if (verbose_option > 1)
	decode_header (current_header, &current_stat, &current_format, 0);
      print_header ();
    }

  if (incremental_option && current_header->header.typeflag == GNUTYPE_DUMPDIR)
    {
      size_t size, written, check;
      union block *data_block;

      set_next_block_after (current_header);
      if (multi_volume_option)
	{
	  assign_string (&save_name, current_file_name);
	  save_totsize = current_stat.st_size;
	}
      for (size = current_stat.st_size; size > 0; size -= written)
	{
	  if (multi_volume_option)
	    save_sizeleft = size;
	  data_block = find_next_block ();
	  if (!data_block)
	    {
	      ERROR ((0, 0, _("EOF in archive file")));
	      break;		/* FIXME: What happens, then?  */
	    }
	  written = available_space_after (data_block);
	  if (written > size)
	    written = size;
	  errno = 0;		/* FIXME: errno should be read-only */
	  check = fwrite (data_block->buffer, sizeof (char), written, stdlis);
	  set_next_block_after ((union block *)
				(data_block->buffer + written - 1));
	  if (check != written)
	    {
	      ERROR ((0, errno, _("Only wrote %lu of %lu bytes to file %s"),
		      (unsigned long) check, (unsigned long) written, current_file_name));
	      skip_file ((long long) (size - written));
	      break;
	    }
	}
      if (multi_volume_option)
	assign_string (&save_name, NULL);
      fputc ('\n', stdlis);
      fflush (stdlis);
      return;

    }

  /* Check to see if we have an extended header to skip over also.  */

  if (current_header->oldgnu_header.isextended)
    isextended = 1;

  /* Skip past the header in the archive.  */

  set_next_block_after (current_header);

  /* If we needed to skip any extended headers, do so now, by reading
     extended headers and skipping past them in the archive.  */

  if (isextended)
    {
#if 0
      union block *exhdr;

      while (1)
	{
	  exhdr = find_next_block ();

	  if (!exhdr->sparse_header.isextended)
	    {
	      set_next_block_after (exhdr);
	      break;
	    }
	  set_next_block_after (exhdr);
	}
#endif
      skip_extended_headers ();
    }

  if (multi_volume_option)
    assign_string (&save_name, current_file_name);

  /* Skip to the next header on the archive.  */

  skip_file ((long long) current_stat.st_size);

  if (multi_volume_option)
    assign_string (&save_name, NULL);
}
int dns_lookup(const char *name, int type, int nscount, char **nsip,
			   unsigned char **outpacket, struct resolv_answer *a, const char *SourceIp)
{
	int count;
	static int id = 1;
	int i, j, len, fd, pos;
	static int ns = 0;
	fd_set set;
	struct timeval timeout;
	struct sockaddr_in sa;
	struct sockaddr_in Source;

	struct resolv_header h;
	struct resolv_question q;
	int retries = 0;
	unsigned char * packet = malloc(PACKETSZ);
	unsigned char * lookup = malloc(MAXDNAME);
	int variant = 0;

	fd = -1;

	if (!packet || !lookup || !nscount)
	    goto fail;

	DPRINTF("Looking up type %d answer for '%s'\n", type, name);

	ns %= nscount;

	while (retries++ < MAX_RETRIES) {

		if (fd != -1)
			close(fd);


		fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

		if (fd == -1)
			goto fail;

		memset(packet, 0, PACKETSZ);

		memset(&h, 0, sizeof(h));
		h.id = ++id;
		h.qdcount = 1;
		h.rd = 1;

		DPRINTF("encoding header\n", h.rd);

		i = encode_header(&h, packet, PACKETSZ);
		if (i < 0)
			goto fail;

		strncpy(lookup,name,MAXDNAME);
		if (variant < searchdomains && strchr(lookup, '.') == NULL)
		{
		    strncat(lookup,".", MAXDNAME);
		    strncat(lookup,searchdomain[variant], MAXDNAME);
		}
		DPRINTF("lookup name: %s\n", lookup);
		q.dotted = (char *)lookup;
		q.qtype = type;
		q.qclass = C_IN; /* CLASS_IN */

		j = encode_question(&q, packet+i, PACKETSZ-i);
		if (j < 0)
			goto fail;

		len = i + j;

		DPRINTF("On try %d, sending query to port %d of machine %s\n",
				retries, NAMESERVER_PORT, nsip[ns]);

		Source.sin_family = AF_INET;
		if( (Source.sin_addr.s_addr = inet_addr(SourceIp)) == -1 ) {
			printf("NSD DNS RESOLVING: SourceIp inet_addr() transfer error\n");
			goto fail;
		}
		if( bind(fd, (struct sockaddr *)&Source,sizeof(Source)) == -1) {
			printf("NSD DNS RESOLVING: bind error\n");
			goto fail;
		}


		sa.sin_family = AF_INET;
		sa.sin_port = htons(NAMESERVER_PORT);
		sa.sin_addr.s_addr = inet_addr(nsip[ns]);



		if (connect(fd, (struct sockaddr *) &sa, sizeof(sa)) == -1) {

			if (errno == ENETUNREACH) {
				/* routing error, presume not transient */
				goto tryall;
			} else
				/* retry */
				continue;
		}

		DPRINTF("Transmitting packet of length %d, id=%d, qr=%d\n",
				len, h.id, h.qr);

		send(fd, packet, len, 0);
		
		FD_ZERO(&set);
		FD_SET(fd,&set);
		timeout.tv_sec = 5;
		timeout.tv_usec = 0;
		
		if( (count = select(fd+1, &set,0,0,&timeout)) == 0 ) {
			DPRINTF("NSD DNS RESOLVING Timeout\n");
			goto again;
		} else if ( count < 0 ) {
			perror("DNS RESOLVING select");
			goto fail;
		}

		i = recv(fd, packet, PACKETSZ, 0);

		if (i < HFIXEDSZ)
			/* too short ! */
			goto again;

		decode_header(packet, &h);

		DPRINTF("id = %d, qr = %d\n", h.id, h.qr);

		if ((h.id != id) || (!h.qr))
			/* unsolicited */
			goto again;

		DPRINTF("Got response %s\n", "(i think)!");
		DPRINTF("qrcount=%d,ancount=%d,nscount=%d,arcount=%d\n",
				h.qdcount, h.ancount, h.nscount, h.arcount);
		DPRINTF("opcode=%d,aa=%d,tc=%d,rd=%d,ra=%d,rcode=%d\n",
				h.opcode, h.aa, h.tc, h.rd, h.ra, h.rcode);

		if ((h.rcode) || (h.ancount < 1)) {
			/* negative result, not present */
			goto again;
		}

		pos = HFIXEDSZ;

		for (j = 0; j < h.qdcount; j++) {
			DPRINTF("Skipping question %d at %d\n", j, pos);
			i = length_question(packet, pos);
			DPRINTF("Length of question %d is %d\n", j, i);
			if (i < 0)
				goto again;
			pos += i;
		}
		DPRINTF("Decoding answer at pos %d\n", pos);

		for (j=0;j<h.ancount;j++)
		{
		    i = decode_answer(packet, pos, a);

		    if (i<0) {
			DPRINTF("failed decode %d\n", i);
			goto again;
		    }
		    /* For all but T_SIG, accept first answer */
		    if (a->atype != T_SIG)
			break;

		    DPRINTF("skipping T_SIG %d\n", i);
		    free(a->dotted);
		    pos += i;
		}

		DPRINTF("Answer name = |%s|\n", a->dotted);
		DPRINTF("Answer type = |%d|\n", a->atype);

		close(fd);

		if (outpacket)
			*outpacket = packet;
		else
			free(packet);
		free(lookup);
		return (0);				/* success! */

	  tryall:
		/* if there are other nameservers, give them a go,
		   otherwise return with error */
		variant = 0;
		if (retries >= nscount*(searchdomains+1))
		    goto fail;

	  again:
		/* if there are searchdomains, try them or fallback as passed */
		if (variant < searchdomains) {
		    /* next search */
		    variant++;
		} else {
		    /* next server, first search */
		    ns = (ns + 1) % nscount;
		    variant = 0;
		}
	}

fail:
	if (fd != -1)
	    close(fd);
	if (lookup)
	    free(lookup);
	if (packet)
	    free(packet);
	return -1;
}
Exemplo n.º 19
0
int
soft_frame_contor::work (int noutput_items,
			gr_vector_const_void_star &input_items,
			gr_vector_void_star &output_items)
{
  const unsigned char *in_hard_and_flag = (const unsigned char *) input_items[0];
  const float         *in_soft          = (const float         *) input_items[1];
  int count=0;
  if (VERBOSE)
    fprintf(stderr,">>> Entering state machine\n");

  while (count < noutput_items){
    switch(d_state) {
      
    case STATE_SYNC_SEARCH:    // Look for flag indicating beginning of pkt
      if (VERBOSE)
        fprintf(stderr,"SYNC Search, noutput=%d\n", noutput_items);
      while (count < noutput_items) {
        if (in_hard_and_flag[count] & 0x2){  // Found it, set up for header decode
            enter_have_sync();
            break;
        }
        count++;
      }
      break;

    case STATE_HAVE_SYNC:
      if (VERBOSE)
          fprintf(stderr,"Header Search bitcnt=%d",d_headerbitlen_cnt);

      while (count < noutput_items) {	// Shift bits one at a time into header
          d_header = d_header << 1;
          d_header.set(0, (bool)(in_hard_and_flag[count++] & 0x1));
          if (++d_headerbitlen_cnt == HEADERBITLEN) {
              if (decode_header()) {
                  get_payload_len(&d_payload_len);
                  enter_have_header(d_payload_len);
                  if (d_packetlen == 0){	    // check for zero-length payload
                    // build a zero-length message
                    // NOTE: passing header field as arg1 is not scalable
	                gr_message_sptr msg = gr_make_message(0, 0, 0, 0);
                    d_target_queue->insert_tail(msg);		// send it
                    msg.reset();  				// free it up
                    enter_search();
                  }
              }
              else
              {
                  fprintf(stderr, "Soft_frame_contor:: Header Decoding Failed\n");
                  enter_search();				// bad header
              }
              break;					// we're in a new state
          }
      }
      break;

    case STATE_HAVE_HEADER:
      if (VERBOSE)
          fprintf(stderr,"Packet Build\n");
      while (count < noutput_items) {   // shift bits into bytes of packet one at a time
        d_packet_byte = (d_packet_byte << 1) | (in_hard_and_flag[count++] & 0x1);
        d_soft_bit_array[d_soft_float_counter++] = in_soft[count -1]; // We are assembling the soft bits
        if (d_packet_byte_index++ == 7) {	  	// byte is full so move to next byte
            d_packet[d_packetlen_cnt++] = d_packet_byte;
            d_packet_byte_index = 0;
            //fprintf(stderr, "d_packetlen_cnt = %d, count = %d \n", d_packetlen_cnt, count);
            if (d_packetlen_cnt == d_packetlen){		// packet is filled, we have assembled complete payload bits and soft bits.
                float* payload_soft_data = new float [d_packetlen * BITS_PER_BYTE];
                memset(payload_soft_data, 0, sizeof(float) * d_packetlen * BITS_PER_BYTE);
                memcpy(payload_soft_data, d_soft_bit_array, sizeof(float) * d_packetlen * BITS_PER_BYTE);
                // build a message
                // NOTE: passing header field as arg1 is not scalable
                gr_message_sptr msg =
                    gr_make_message(0, 0, 0, d_packetlen * sizeof(float) * BITS_PER_BYTE );
                memcpy(msg->msg(), payload_soft_data, d_packetlen * sizeof(float) * BITS_PER_BYTE);
                //reset vectors
                d_target_queue->insert_tail(msg);// send it
                msg.reset();  				// free it up

                delete[] payload_soft_data; // free data in heap
                enter_search();
                break;
            } // end if(d_packetlen_cnt == d_packetlen)
        }// end if (d_packet_byte_index++ == 7)
      }
      break;
      default:
        assert(0);
    } // switch

  }   // while

  return noutput_items;
}
Exemplo n.º 20
0
/**
 *  Read a whole DChat PDU from a file descriptor.
 *  Read linewise from a file descriptor to form a DChat protocol data unit.
 *  Information read from the file descriptor will be stored in this pdu.
 *  @param fd  File descriptor to read from
 *  @param pdu Pointer to a PDU structure whose headers will be filled.
 *  @return amount of bytes read in total if a protocol data unit has been read successfully, 0 on EOF ,
 *  -1 on error
 */
int
read_pdu(int fd, dchat_pdu_t* pdu)
{
    char* line;     // line read from file descriptor
    char* contentp; // content pointer
    int ret;        // return value
    int b;          // amount of bytes read as content
    int len = 0;    // amount of bytes read in total
    // zero out structure
    memset(pdu, 0, sizeof(*pdu));

    // read each line of the received pdu
    if ((ret = read_line(fd, &line)) == -1 || !ret)
    {
        return ret;
    }

    // first header must be version header
    if (decode_header(pdu, line) == -1 || pdu->version != DCHAT_V1)
    {
        ret = -1;
    }

    if (ret != -1)
    {
        len += strlen(line);
        free(line);

        // read header lines from file descriptors, until
        // an empty line is received
        while ((ret = read_line(fd, &line)) != -1 || ret == 0)
        {
            len += strlen(line);

            if (decode_header(pdu, line) == -1)
            {
                // if line is not a header, it must be an empty line
                if (!strcmp(line, "\n") || !strcmp(line, "\r\n"))
                {
                    break; // All headers have been read
                }

                ret = -1;
                break;
            }

            free(line);
        }
    }

    // On error print illegal line
    if (ret == -1)
    {
        ui_log(LOG_ERR, "Illegal PDU header received: '%s'", line);
    }

    // EOF or ERROR
    if (ret <= 0)
    {
        free(line);
        return ret;
    }

    // has content type, onion-id and listen-port been specified?
    if (pdu->content_type == 0 || pdu->onion_id == NULL || pdu->lport == 0)
    {
        ui_log(LOG_ERR, "Mandatory PDU headers are missing!");
        free(line);
        return -1;
    }

    // allocate memory for content
    pdu->content = malloc(pdu->content_length + 1);
    contentp = pdu->content; // point to the beginning

    // read content frm file descriptor
    // read x bytes defined by Content-Length
    for (b = 0, contentp = pdu->content; b < pdu->content_length;
         b++, contentp++, len++)
    {
        if ((ret = read(fd, contentp, 1)) == -1 || !ret)
        {
            free(pdu->content);
            return ret;
        }
    }

    *contentp = '\0'; // NULL terminate potential string
    return len; // amount of bytes read as content == content length
}
Exemplo n.º 21
0
void GlzDecoder::decode(uint8_t *data, SpicePalette *palette, void *opaque_usr_info)
{
    DecodedImageWinId image_window_id;
    GlzDecodedImage *decoded_image;
    size_t n_in_bytes_decoded;
    int bytes_per_pixel;
    LzImageType decoded_type;

    _in_start = data;
    _in_now = data;

    decode_header();

#ifdef GLZ_DECODE_TO_RGB32
    bytes_per_pixel = 4;

    if (_image.type == LZ_IMAGE_TYPE_RGBA) {
        decoded_type = LZ_IMAGE_TYPE_RGBA;
    } else {
        decoded_type = LZ_IMAGE_TYPE_RGB32;
    }

#else
    if (IS_IMAGE_TYPE_PLT[_image.type]) {
        GLZ_ASSERT(_debug_calls, !(_image.gross_pixels % PLT_PIXELS_PER_BYTE[_image.type]));
    }
    bytes_per_pixel = RGB_BYTES_PER_PIXEL[_image.type];
    decoded_type = _image.type;
#endif


    image_window_id = _images_window.pre_decode(_image.id, _image.id - _image.win_head_dist);

    decoded_image = _usr_handler.alloc_image(opaque_usr_info, _image.id,
                                             _image.id - _image.win_head_dist,
                                             decoded_type, _image.width, _image.height,
                                             _image.gross_pixels, bytes_per_pixel,
                                             _image.top_down);

    _image.data = decoded_image->get_data();

    // decode_by_type
#ifdef GLZ_DECODE_TO_RGB32
    n_in_bytes_decoded = DECODE_TO_RGB32[_image.type](_images_window, _in_now, _image.data,
                                                      _image.gross_pixels, image_window_id,
                                                      palette, _debug_calls);
#else
    n_in_bytes_decoded = DECODE_TO_SAME[_image.type](_images_window, _in_now, _image.data,
                                                     IS_IMAGE_TYPE_PLT[_image.type] ?
                                                     _image.gross_pixels /
                                                     PLT_PIXELS_PER_BYTE[_image.type] :
                                                     _image.gross_pixels,
                                                     image_window_id, palette, _debug_calls);
#endif

    _in_now += n_in_bytes_decoded;

    if (_image.type == LZ_IMAGE_TYPE_RGBA) {
        glz_rgb_alpha_decode(_images_window, _in_now, _image.data,
                             _image.gross_pixels, image_window_id, palette, _debug_calls);
    }

    _images_window.post_decode(decoded_image);
}
Exemplo n.º 22
0
GP<JB2Image>
MMRDecoder::decode(GP<ByteStream> gbs)
{
  ByteStream &inp=*gbs;
  // Read header
  int width, height, invert;
  const bool striped=decode_header(inp, width, height, invert);
  // Prepare image
  GP<JB2Image> jimg = JB2Image::create();
  jimg->set_dimension(width, height);
  // Choose pertinent blocksize
  int blocksize = MIN(500,MAX(64,MAX(width/17,height/22)));
  int blocksperline = (width+blocksize-1)/blocksize;
  // Prepare decoder
  GP<MMRDecoder> gdcd=MMRDecoder::create(gbs, width, height, striped);
  MMRDecoder &dcd=*gdcd;
  // Loop on JB2 bands
  int line = height-1;
  while (line >= 0)
    {
      int bandline = MIN(blocksize-1,line);
      GPArray<GBitmap> blocks(0,blocksperline-1);
      // Loop on scanlines
      for(; bandline >= 0; bandline--,line--)
      {
        // Decode one scanline
        const unsigned short *s = dcd.scanruns();
        if (s)
        {
	  // Loop on blocks
          int x = 0;
          int b = 0;
          int firstx = 0;
          bool c = !!invert;
          while (x < width)
            {
              int xend = x + *s++;
              while (b<blocksperline)
                {
                  int lastx = MIN(firstx+blocksize,width);
                  if (c)
                    {
                      if (!blocks[b])
                        blocks[b] = GBitmap::create(bandline+1, lastx-firstx);
                      unsigned char *bptr = (*blocks[b])[bandline] - firstx;
                      int x1 = MAX(x,firstx);
                      int x2 = MIN(xend,lastx);
                      while (x1 < x2)
                        bptr[x1++] = 1;
                    }
                  if (xend < lastx)
                    break;
                  firstx = lastx;
                  b ++;
                }
              x = xend;
              c = !c; 
            }
	}
      }
      // Insert blocks into JB2Image
      for (int b=0; b<blocksperline; b++)
	{
	  JB2Shape shape;
	  shape.bits = blocks[b];
	  if (shape.bits) 
	    {
	      shape.parent = -1;
	      shape.bits->compress();
	      JB2Blit blit;
	      blit.left = b*blocksize;
	      blit.bottom = line+1;
	      blit.shapeno = jimg->add_shape(shape);
	      jimg->add_blit(blit);
	    }
	}
    }
  // Return
  return jimg;
}
Exemplo n.º 23
0
int decode_bytecode_pump(decode_state_t* ds, const unsigned char* pData, size_t iLength)
{
    decoded_prototype_t* proto;

    /* Continue the read operation which caused the yield. */
    ds->chunk = pData;
    ds->chunklen = iLength;
    if(!read(ds, ds->readtarget, ds->readlen))
        return DECODE_YIELD;

    proto = ds->stack[ds->level - 1];

    switch(ds->yieldpos)
    {
    case DECODE_YIELDPOS_HEADER:
        if(!decode_header(ds))
            return DECODE_FAIL;

        /* Main prototype decoding function */
ENTER_CHILD_PROTO:
        if(ds->level >= LUAI_MAXCCALLS)
            return DECODE_UNSAFE;
        proto = alloc_proto(ds);
        if(proto == NULL)
            return DECODE_ERROR_MEM;
        ds->stack[ds->level++] = proto;

        READ(NULL, ds->sizeint * 2);
        READ(ds->buffer, 3);

        proto->numparams = ds->buffer[0];
        proto->is_vararg = ds->buffer[1] != 0;
        proto->numregs = ds->buffer[2];

        /* Code */
        proto->instructionsize = ds->sizeins;
        READ_INT(&proto->numinstructions, ds->sizeint);
        if(proto->numinstructions == 0)
            return DECODE_UNSAFE;
        proto->code = (unsigned char*)ds->alloc(ds->allocud, NULL, 0,
                                                ds->sizeins * proto->numinstructions + sizeof(int));
        if(proto->code == NULL)
            return DECODE_ERROR_MEM;
        READ(proto->code, ds->sizeins * proto->numinstructions);
        if(ds->swapendian)
        {
            for(i = 0; i < proto->numinstructions; ++i)
                byteswap(proto->code + i * ds->sizeins, ds->sizeins);
        }

        /* Constants (excluding prototypes) */
        READ_INT(&proto->numconstants, ds->sizeint);
        proto->constant_types = (unsigned char*)ds->alloc(ds->allocud,
                                NULL, 0, proto->numconstants);
        if(proto->numconstants != 0 && proto->constant_types == NULL)
            return DECODE_ERROR_MEM;
        for(i = 0; i < proto->numconstants; ++i)
        {
            unsigned char t;
            READ(proto->constant_types + i, 1);
            t = proto->constant_types[i];
            /* NB: Cannot use switch statement here, as possibly yielding reads
               cannot be in a nested swtich. */
            if(t == LUA_TSTRING)
            {
                SKIP_STRING_1();
                SKIP_STRING_2();
            }
            else if(t == LUA_TNUMBER)
            {
                READ(ds->buffer, ds->sizenum);
                if(is_signalling_nan(ds, ds->buffer))
                    return DECODE_UNSAFE;
            }
            else if(t == LUA_TBOOLEAN)
            {
                READ(ds->buffer, 1);
                if(ds->buffer[0] > 1)
                    return DECODE_UNSAFE;
            }
            else if(t != LUA_TNIL)
            {
                return DECODE_FAIL;
            }
        }

        /* Prototypes */
        READ_INT(&proto->numprototypes, ds->sizeint);
        proto->prototypes = (decoded_prototype_t**)ds->alloc(ds->allocud,
                            NULL, 0, sizeof(decoded_prototype_t*) * proto->numprototypes);
        if(proto->numprototypes != 0 && proto->prototypes == NULL)
            return DECODE_ERROR_MEM;
        for(i = 0; i < proto->numprototypes; ++i)
            proto->prototypes[i] = NULL;
        for(i = 0; i < proto->numprototypes; ++i)
        {
            /* Recursively decode the child prototype.
              The loop counter needs to be saved somewhere, as it will be
              overwritten during the recursion. For this, the numupvalues field
              is used, as its value is not important at this stage of the
              decoding process. The result of the recursion is then pulled out
              of the stack and stored in the appropriate place. */
            proto->numupvalues = i;
            goto ENTER_CHILD_PROTO;
RESUME_PARENT_PROTO:
            i = proto->numupvalues;
            proto->prototypes[i] = ds->stack[ds->level];
        }

        /* Upvalues */
        READ_INT(&proto->numupvalues, ds->sizeint);
        proto->upvalue_instack = (bool*)ds->alloc(ds->allocud, NULL, 0,
                                 sizeof(bool) * proto->numupvalues);
        proto->upvalue_index = (unsigned char*)ds->alloc(ds->allocud, NULL, 0,
                               proto->numupvalues);
        if((proto->upvalue_instack == NULL || proto->upvalue_index == NULL)
                && proto->numupvalues != 0)
            return DECODE_ERROR_MEM;
        for(i = 0; i < proto->numupvalues; ++i)
        {
            READ(ds->buffer, 2);
            proto->upvalue_instack[i] = ds->buffer[0] != 0;
            proto->upvalue_index[i] = ds->buffer[1];
        }

        /* Debug information */
        SKIP_STRING_1();
        SKIP_STRING_2();
        READ_INT(&i, ds->sizeint);
        READ(NULL, ds->sizeint * i);
        READ_INT(&i, ds->sizeint);
        for(; i > 0; --i)
        {
            SKIP_STRING_1();
            SKIP_STRING_2();
            READ(NULL, ds->sizeint * 2);
        }
        READ_INT(&i, ds->sizeint);
        for(; i > 0; --i)
        {
            SKIP_STRING_1();
            SKIP_STRING_2();
        }

        if(--ds->level == 0)
        {
            if(ds->chunklen != 0) /* Data in epilogue? */
                return DECODE_FAIL;
            ds->yieldpos = DECODE_YIELDPOS_DONE;
            return DECODE_YIELD;
        }
        proto = ds->stack[ds->level - 1];
        goto RESUME_PARENT_PROTO;
    /* End of main prototype decoding function. */

    case DECODE_YIELDPOS_DONE:
        if(ds->chunklen == 0)
            return DECODE_YIELD;
        /* If this is being resumed, it means that there is spurious data
           beyond the end of the bytecode. In this case, the decoding should
           fail and not return a prototype, so the level field is set to 1 to
           ensure that the resulting prototype gets freed when the stack is
           freed. */
        ds->level = 1;
        return DECODE_FAIL;

    default:
        /* This should never happen, unless the yield/resume code is broken. */
        return DECODE_ERROR;
    }
}
Exemplo n.º 24
0
BOOL  DumpTAR_FAILED( LPDFSTR lpdf )
{
   BOOL  bRet = FALSE;
   LPTSTR   lpb = &gcOutBuf[0];  // [16K]
   LPTSTR   lpb2 = &gcOutBuf2[0];  // [16K]
   char * pv = (char *)lpdf->df_pVoid;
   struct posix_header * pph = (struct posix_header *)lpdf->df_pVoid;
   char * cp;
   size_t   off, boff, count, fsz, remains, len, hlen, culen;
   int   i;
   char c;
   size_t maxcnt = iFileCount + iDirCount;
   size_t entry = 0;
   enum read_header h;
   struct tar_stat_info * info = &current_stat_info;
   DWORD dwm = lpdf->dwmax;
   union block * p;
   if( !pph )
      return bRet;

   iMaxFileSize = 0;
   iMinFileSize = 0x7fffffff;
   current_block = (union block *)pv;
   dwm = lpdf->dwmax;
   p = current_block;
   while(dwm)
   {
      record_end = p;
      p++;
      if(dwm >= BLOCKSIZE)
      {
         dwm -= BLOCKSIZE;
         if(dwm == 0)
            record_end = p;
      }
      else
         dwm = 0;
   }

   if(( _strnicmp(pph->magic, TMAGIC, 5) == 0 )||
      ( rdhdr == HEADER_SUCCESS ) ){
      // we have a USTAR format
      off = 1;
      count = 0;
      sprtf( "TAR [%s] is [%s] format ..."MEOR,
         lpdf->fn,
         get_format_stg(current_format) );
      while(off)
      {
         entry++;
         boff = count * BLOCKSIZE;
         pph = (struct posix_header *) &pv[boff];
         if( (boff + BLOCKSIZE) > lpdf->dwmax )
         {
            sprtf( "WARNING: DATA EXPIRED BEFORE ZERO BLOCK!"MEOR );
            break;
         }
         tar_stat_destroy(info);
         current_header = (union block *)pph;
         h = tar_checksum ((union block *)pph, TRUE);
         form = -1;
         decode_header ((union block *)pph, info, &form, 0);
         //      if (header->header.typeflag == LNKTYPE)
         if( pph->typeflag == LNKTYPE )
            info->stat.st_size = 0;	/* links 0 size on tape */
         else
            info->stat.st_size = OFF_FROM_HEADER (pph->size);
         fsz = (size_t)info->stat.st_size;
         if( VERB5 )
         {
            cp = (char *)pph;
            sprtf( "%s: form [%s](%d): type [%s]: size %9d; offset %#08X; time %s"MEOR,
               get_header_stg( h ),
               get_format_stg(form),
               form,
               get_type_string( pph->typeflag),
               info->stat.st_size,
               (cp - pv),
               tartime( info->mtime, 0 ));
         }
         // else if (header->header.typeflag == XHDTYPE
		   // || header->header.typeflag == SOLARIS_XHDTYPE)
         if(( h == HEADER_SUCCESS )&&
            (( pph->typeflag == XHDTYPE )||
             ( pph->typeflag == SOLARIS_XHDTYPE )))
         {
            // we need to READ the xheader ...
            struct posix_header * pph_save = pph;
            fsz = (size_t)info->stat.st_size;
            len = 1;
            xheader_read (&info->xhdr, (union block *)pph, (size_t)fsz);
            if( VERB9 )
               sprtf( "Skipping %d extended header blocks ...\n", len );
            boff = ((count + len) * BLOCKSIZE);
            pph = (struct posix_header *)&pv[boff];
            if( (boff + BLOCKSIZE) > lpdf->dwmax )
            {
               sprtf( "WARNING: DATA EXPIRED BEFORE ZERO BLOCK!"MEOR );
               pph = pph_save;
               break;
            }
            tar_stat_destroy(info);
            pph = (struct posix_header *)current_block; // move up to this block
            current_header = (union block *)pph;
            h = tar_checksum ((union block *)pph, TRUE);
            form = -1;
            decode_header ((union block *)pph, info, &form, 0);
            if( pph->typeflag == LNKTYPE )
               info->stat.st_size = 0;	/* links 0 size on tape */
            else
               info->stat.st_size = OFF_FROM_HEADER (pph->size);
            fsz = (size_t)info->stat.st_size;
            if( h == HEADER_SUCCESS ) {
               XHDTYPE_count++;
               if( VERB5 )
               {
                  cp = (char *)pph;
                  sprtf( "%s: form [%s](%d): type [%s]: size %9d; offset %#08X; time %s"MEOR,
                     get_header_stg( h ),
                     get_format_stg(form),
                     form,
                     get_type_string( pph->typeflag),
                     info->stat.st_size,
                     (cp - pv),
                     tartime( info->mtime, 0 ));
               }
               count += len;
            } else {
               pph = pph_save;
               tar_stat_destroy(info);
               current_header = (union block *)pph;
               h = tar_checksum ((union block *)pph, TRUE);
               form = -1;
               decode_header ((union block *)pph, info, &form, 0);
            }
         }

         fsz = 0;
         i = collect_octal_size( lpb, pph, &fsz, 1 );
         off = collect_prefix_name( lpb, pph );
         if( off ) {
            // we GOT a NAME
            sprtf( "%5d %-50s %s %10d %s"MEOR,
               entry,
               lpb,
               get_type_string(pph->typeflag),
               fsz,
               tartime( info->mtime, 0 ));
            // gather counts
            switch(pph->typeflag)
            {
            case REGTYPE:
            case AREGTYPE:
               REGTYPE_count++;
               if( fsz > iMaxFileSize )
                  iMaxFileSize = fsz;
               if( fsz < iMinFileSize )
                  iMinFileSize = fsz;
               remains = fsz;
               while(remains)
               {
                  count++;
                  boff = count * BLOCKSIZE;
                  if(remains > BLOCKSIZE)
                     len = BLOCKSIZE;
                  else
                     len = remains;
                  culen = 0;
                  if( VERB9 && bExtraDebug )
                  {
                     while( len )
                     {
                        if(len > 16)
                           hlen = 16;
                        else
                           hlen = len;
                        *lpb = 0;
                        GetHEXString( lpb, &pv[boff+culen], hlen, pv, FALSE );
                        sprtf( "%s"MEOR, lpb );
                        len -= hlen;
                        culen += hlen;
                     }
                  }
                  pph = (struct posix_header *) &pv[boff];
                  if(remains > BLOCKSIZE)
                     remains -= BLOCKSIZE;
                  else
                     remains = 0;
               }
               break;
            case LNKTYPE:  // , "link" },
               LNKTYPE_count++;
               break;
            case SYMTYPE:  //, "reserved" },
               SYMTYPE_count++;
               break;
            case CHRTYPE:  // , "character special" },
               CHRTYPE_count++;
               break;
            case BLKTYPE:  //, "block special" }, //  '4'		/* block special */
               BLKTYPE_count++;
               break;
            case DIRTYPE:  // , "directory" },     //  '5'		/* directory */
               DIRTYPE_count++;
               break;
            case FIFOTYPE: //, "FIFO special" }, // '6'		/* FIFO special */
               FIFOTYPE_count++;
               break;
            case CONTTYPE: //, "reserved" },     // '7'		/* reserved */
               CONTTYPE_count++;
               break;
            case XHDTYPE:  //, "extended header" }, //  'x'   /* Extended header referring to the next file in the archive */
               XHDTYPE_count++;
               break;
            case XGLTYPE:  //, "global header" }, //  'g'            /* Global extended header */
               XGLTYPE_count++;
               break;
            default:
               default_count++;
               sprtf("WARNING: Uncased type %c!!!"MEOR, pph->typeflag);
               break;
            }
         }
         count++;
      }  // while ...

      if( max_warn_count < warn_count )
      {
         sprtf( "WARNING: Plus another [%d] OUT OF OCTAL RANGE!!!"MEOR,
            warn_count - max_warn_count );
      }

      // fell out because of a BLANK block
      sprtf( "Processed %d entries", maxcnt );
      if( REGTYPE_count ) {
         // case AREGTYPE: counted with above
         sprtf( ", %d file%s (min %d, max %d)",
            REGTYPE_count,
            ((REGTYPE_count == 1) ? "" : "s"),
            iMinFileSize,
            iMaxFileSize );
      }
      if( LNKTYPE_count )
         sprtf( ", %d link%s", LNKTYPE_count, ((LNKTYPE_count == 1) ? "" : "s") );
      if( SYMTYPE_count )
         sprtf( ", %d sym%s", SYMTYPE_count, ((SYMTYPE_count == 1) ? "" : "s") );
      if( CHRTYPE_count )
         sprtf( ", %d char%s", CHRTYPE_count, ((CHRTYPE_count == 1) ? "" : "s") );
      if( BLKTYPE_count )
         sprtf( ", %d block%s", BLKTYPE_count, ((BLKTYPE_count == 1) ? "" : "s") );
      if( DIRTYPE_count )
         sprtf( ", %d dir%s", DIRTYPE_count, ((DIRTYPE_count == 1) ? "" : "s") );
      if( FIFOTYPE_count )
         sprtf( ", %d fifo%s", FIFOTYPE_count, ((FIFOTYPE_count == 1) ? "" : "s") );
      if( CONTTYPE_count )
         sprtf( ", %d cont%s", CONTTYPE_count, ((CONTTYPE_count == 1) ? "" : "s") );
      if( XHDTYPE_count )
         sprtf( ", %d xhdr%s", XHDTYPE_count, ((XHDTYPE_count == 1) ? "" : "s") );
      if( XGLTYPE_count )
         sprtf( ", %d xgl%s", XGLTYPE_count, ((XGLTYPE_count == 1) ? "" : "s") );
      if( default_count )
         sprtf( ", %d default%s", default_count, ((default_count == 1) ? "" : "s") );
      sprtf( " (blocks %d)"MEOR,
         count );

      count++;
      boff = count * BLOCKSIZE;
      remains = (lpdf->dwmax - (boff + BLOCKSIZE));
      strcpy(lpb, (remains == 0 ? "perfect" : "remainder " ));
      if(remains) sprintf(EndBuf(lpb)," %d", remains );
      if(remains > 0)
      {
         off = 0;
         boff = count * BLOCKSIZE;
         if( VERB )
            sprtf( "Reached offset %d of %d ... %s"MEOR,
            (boff + BLOCKSIZE), lpdf->dwmax, lpb );
         while(remains > 0)
         {
            if(remains > BLOCKSIZE)
               len = BLOCKSIZE;
            else
               len = remains;
            culen = 0;
            remains -= len;
            while( len )
            {
               if(len > 16)
                  hlen = 16;
               else
                  hlen = len;
               for( i = 0; i < (int)hlen; i++ )
               {
                  c = pv[boff+culen+i];
                  if(c)
                     break;
               }
               if(c) {
                  if(VERB5)
                  {
                     *lpb = 0;
                     GetHEXString( lpb, &pv[boff+culen], hlen, pv, FALSE );
                     sprtf( "%s"MEOR, lpb );
                  }
                  off++;
               }
               len -= hlen;
               culen += hlen;
            }
            count++;
         }
         // done the remainder
         if( off == 0 ) {
            // NO HEX OUTPUT
            sprtf( "But it was ALL zeros ... (to %d)"MEOR, ((count+1) * BLOCKSIZE) );
         }
      }
      bRet = TRUE;
   }

   return bRet;
}
Exemplo n.º 25
0
/* Implement the 'r' (add files to end of archive), and 'u' (add files to
   end of archive if they arent there, or are more up to date than the
   version in the archive.) commands.*/
void
update_archive ()
{
  int found_end = 0;
  int status = 3;
  int prev_status;
  char *p;
  struct name *name;
  extern void dump_file ();

  name_gather ();
  if (cmd_mode == CMD_UPDATE)
    name_expand ();
  open_archive (2);		/* Open for updating */

  do
    {
      prev_status = status;
      status = read_header ();
      switch (status)
	{
	case EOF:
	  found_end = 1;
	  break;

	case 0:		/* A bad record */
	  userec (head);
	  switch (prev_status)
	    {
	    case 3:
	      msg ("This doesn't look like a tar archive.");
	      /* FALL THROUGH */
	    case 2:
	    case 1:
	      msg ("Skipping to next header");
	    case 0:
	      break;
	    }
	  break;

	  /* A good record */
	case 1:
	  /* printf("File %s\n",head->header.name); */
	  /* head->header.name[NAMSIZ-1]='\0'; */
	  if (cmd_mode == CMD_UPDATE && (name = name_scan (current_file_name)))
	    {

	      /* struct stat hstat; */
	      struct stat nstat;
	      int head_standard;

	      decode_header (head, &hstat, &head_standard, 0);
	      if (stat (current_file_name, &nstat) < 0)
		{
		  msg_perror ("can't stat %s:", current_file_name);
		}
	      else
		{
		  if (hstat.st_mtime >= nstat.st_mtime)
		    name->found++;
		}
	    }
	  userec (head);
	  if (head->header.isextended)
	    skip_extended_headers ();
	  skip_file ((long) hstat.st_size);
	  break;

	case 2:
	  ar_record = head;
	  found_end = 1;
	  break;
	}
    }
  while (!found_end);

  reset_eof ();
  time_to_start_writing = 1;
  output_start = ar_record->charptr;

  while (p = name_from_list ())
    {
      if (f_confirm && !confirm ("add", p))
	continue;
      if (cmd_mode == CMD_CAT)
	append_file (p);
      else
	dump_file (p, -1, 1);
    }

  write_eot ();
  close_archive ();
  names_notfound ();
}
Exemplo n.º 26
0
int
decodeMP3 (struct mpstr *mp, char *in, int isize, char *out,
	   int osize, int *done)
{
  int len;

  gmp = mp;

  if (osize < 4608)
    {
      fprintf (stderr, "To less out space\n");
      return MP3_ERR;
    }

  if (in)
    {
      if (addbuf (mp, in, isize) == NULL)
	{
	  return MP3_ERR;
	}
    }

  /* First decode header */
  if (mp->framesize == 0)
    {
      if (mp->bsize < 4)
	{
	  return MP3_NEED_MORE;
	}
      read_head (mp);
      decode_header (&mp->fr, mp->header);
      mp->framesize = mp->fr.framesize;
    }

  if (mp->fr.framesize > mp->bsize)
    return MP3_NEED_MORE;

  wordpointer = mp->bsspace[mp->bsnum] + 512;
  mp->bsnum = (mp->bsnum + 1) & 0x1;
  bitindex = 0;

  len = 0;
  while (len < mp->framesize)
    {
      int nlen;
      int blen = mp->tail->size - mp->tail->pos;
      if ((mp->framesize - len) <= blen)
	{
	  nlen = mp->framesize - len;
	}
      else
	{
	  nlen = blen;
	}
      memcpy (wordpointer + len, mp->tail->pnt + mp->tail->pos, nlen);
      len += nlen;
      mp->tail->pos += nlen;
      mp->bsize -= nlen;
      if (mp->tail->pos == mp->tail->size)
	{
	  remove_buf (mp);
	}
    }

  *done = 0;
  if (mp->fr.error_protection)
    getbits (16);
  switch (mp->fr.lay)
    {
    case 3:
      do_layer3 (&mp->fr, (unsigned char *) out, done);
      break;
    }

  mp->fsizeold = mp->framesize;
  mp->framesize = 0;

  return MP3_OK;
}
Exemplo n.º 27
0
void
list_archive (void)
{
  bool is_extended = false;	/* to remember if current.header is extended */

  /* Print the header block.  */

  if (verbose_option)
    {
      if (verbose_option_count > 1)
	decode_header (&current, false);
      print_header (&current);
    }

  if (incremental_option && current.block->header.typeflag == GNUTAR_DUMPDIR)
    {
      size_t size;
      size_t size_to_write;
      ssize_t size_written;
      union block *data_block;

      set_next_block_after (current.block);
      if (multi_volume_option)
	{
	  assign_string (&save_name, current.name);
	  save_totsize = current.stat.st_size;
	}
      for (size = current.stat.st_size; size > 0; size -= size_to_write)
	{
	  if (multi_volume_option)
	    save_sizeleft = size;
	  data_block = find_next_block ();
	  if (!data_block)
	    {
	      ERROR ((0, 0, _("Unexpected end of file in archive")));
	      break;		/* FIXME: What happens, then?  */
	    }
	  size_to_write = available_space_after (data_block);
	  if (size_to_write > size)
	    size_to_write = size;
	  errno = 0;		/* FIXME: errno should be read-only */
	  size_written = fwrite (data_block->buffer, 1, size_to_write, stdlis);
	  set_next_block_after ((union block *)
				(data_block->buffer + size_to_write - 1));
	  if (size_written != size_to_write)
	    {
	      /* FIXME: size_written may be negative, here!  */
	      ERROR ((0, errno, _("Only wrote %lu of %lu bytes to file %s"),
		      (unsigned long) size_written,
		      (unsigned long) size_to_write, current.name));
	      skip_file ((off_t) (size - size_to_write));
	      break;
	    }
	}
      if (multi_volume_option)
	assign_string (&save_name, NULL);
      fputc ('\n', stdlis);
      fflush (stdlis);
      return;
    }

  /* Check to see if we have an extended header to skip over also.  */

  if (current.block->gnutar_header.isextended)
    is_extended = true;

  /* Skip past the header in the archive.  */

  set_next_block_after (current.block);

  /* If we needed to skip any extended headers, do so now, by reading
     extended headers and skipping past them in the archive.  */

  if (is_extended)
    {
#if 0
      union block *exhdr;

      while (true)
	{
	  exhdr = find_next_block ();

	  if (!exhdr->sparse_header.isextended)
	    {
	      set_next_block_after (exhdr);
	      break;
	    }
	  set_next_block_after (exhdr);
	}
#endif
      skip_extended_headers ();
    }

  if (multi_volume_option)
    assign_string (&save_name, current.name);

  /* Skip to the next header on the archive.  */

  skip_file (current.stat.st_size);

  if (multi_volume_option)
    assign_string (&save_name, NULL);
}
Exemplo n.º 28
0
void
diff_archive (void)
{
  struct stat stat_data;
  int name_length;
  int status;

  errno = EPIPE;		/* FIXME: errno should be read-only */
				/* FIXME: remove perrors */

  set_next_block_after (current_header);
  decode_header (current_header, &current_stat, &current_format, 1);

  /* Print the block from `current_header' and `current_stat'.  */

  if (verbose_option)
    {
      if (now_verifying)
	fprintf (stdlis, _("Verify "));
      print_header ();
    }

  switch (current_header->header.typeflag)
    {
    default:
      WARN ((0, 0, _("Unknown file type '%c' for %s, diffed as normal file"),
		 current_header->header.typeflag, current_file_name));
      /* Fall through.  */

    case AREGTYPE:
    case REGTYPE:
    case GNUTYPE_SPARSE:
    case CONTTYPE:

      /* Appears to be a file.  See if it's really a directory.  */

      name_length = strlen (current_file_name) - 1;
      if (current_file_name[name_length] == PATHSEP)
	goto really_dir;

      if (!get_stat_data (&stat_data))
	{
	  if (current_header->oldgnu_header.isextended)
	    skip_extended_headers ();
	  skip_file ((long) current_stat.st_size);
	  goto quit;
	}

      if (!S_ISREG (stat_data.st_mode))
	{
	  report_difference (_("Not a regular file"));
	  skip_file ((long) current_stat.st_size);
	  goto quit;
	}

      stat_data.st_mode &= 07777;
      if (stat_data.st_mode != current_stat.st_mode)
	report_difference (_("Mode differs"));

#if !MSDOS && !WIN32
      /* stat() in djgpp's C library gives a constant number of 42 as the
	 uid and gid of a file.  So, comparing an FTP'ed archive just after
	 unpack would fail on MSDOS.  */
      if (stat_data.st_uid != current_stat.st_uid)
	report_difference (_("Uid differs"));
      if (stat_data.st_gid != current_stat.st_gid)
	report_difference (_("Gid differs"));
#endif

      if (stat_data.st_mtime != current_stat.st_mtime)
	report_difference (_("Mod time differs"));
      if (current_header->header.typeflag != GNUTYPE_SPARSE &&
	  stat_data.st_size != current_stat.st_size)
	{
	  report_difference (_("Size differs"));
	  skip_file ((long) current_stat.st_size);
	  goto quit;
	}

      diff_handle = open (current_file_name, O_NDELAY | O_RDONLY | O_BINARY);

      if (diff_handle < 0 && !absolute_names_option)
	{
	  char *tmpbuf = xmalloc (strlen (current_file_name) + 2);

	  *tmpbuf = PATHSEP;
	  strcpy (tmpbuf + 1, current_file_name);
	  diff_handle = open (tmpbuf, O_NDELAY | O_RDONLY);
	  free (tmpbuf);
	}
      if (diff_handle < 0)
	{
	  ERROR ((0, errno, _("Cannot open %s"), current_file_name));
	  if (current_header->oldgnu_header.isextended)
	    skip_extended_headers ();
	  skip_file ((long) current_stat.st_size);
	  report_difference (NULL);
	  goto quit;
	}

      /* Need to treat sparse files completely differently here.  */

      if (current_header->header.typeflag == GNUTYPE_SPARSE)
	diff_sparse_files (current_stat.st_size);
      else
	{
	  if (multi_volume_option)
	    {
	      assign_string (&save_name, current_file_name);
	      save_totsize = current_stat.st_size;
	      /* save_sizeleft is set in read_and_process.  */
	    }

	  read_and_process ((long) (current_stat.st_size), process_rawdata);

	  if (multi_volume_option)
	    assign_string (&save_name, NULL);
	}

      status = close (diff_handle);
      if (status < 0)
	ERROR ((0, errno, _("Error while closing %s"), current_file_name));

    quit:
      break;

#if !MSDOS
    case LNKTYPE:
      {
	dev_t dev;
	ino_t ino;

	if (!get_stat_data (&stat_data))
	  break;

	dev = stat_data.st_dev;
	ino = stat_data.st_ino;
	status = stat (current_link_name, &stat_data);
	if (status < 0)
	  {
	    if (errno == ENOENT)
	      report_difference (_("Does not exist"));
	    else
	      {
		WARN ((0, errno, _("Cannot stat file %s"), current_file_name));
		report_difference (NULL);
	      }
	    break;
	  }

	if (stat_data.st_dev != dev || stat_data.st_ino != ino)
	  {
	    char *message = (char *)
	      xmalloc (MESSAGE_BUFFER_SIZE + strlen (current_link_name));

	    sprintf (message, _("Not linked to %s"), current_link_name);
	    report_difference (message);
	    free (message);
	    break;
	  }

	break;
      }
#endif /* not MSDOS */

#ifdef S_ISLNK
    case SYMTYPE:
      {
	char linkbuf[NAME_FIELD_SIZE + 3]; /* FIXME: may be too short.  */

	status = readlink (current_file_name, linkbuf, (sizeof linkbuf) - 1);

	if (status < 0)
	  {
	    if (errno == ENOENT)
	      report_difference (_("No such file or directory"));
	    else
	      {
		WARN ((0, errno, _("Cannot read link %s"), current_file_name));
		report_difference (NULL);
	      }
	    break;
	  }

	linkbuf[status] = '\0';	/* null-terminate it */
	if (strncmp (current_link_name, linkbuf, (size_t) status) != 0)
	  report_difference (_("Symlink differs"));

	break;
      }
#endif /* not S_ISLNK */

#ifdef S_IFCHR
    case CHRTYPE:
      current_stat.st_mode |= S_IFCHR;
      goto check_node;
#endif /* not S_IFCHR */

#ifdef S_IFBLK
      /* If local system doesn't support block devices, use default case.  */

    case BLKTYPE:
      current_stat.st_mode |= S_IFBLK;
      goto check_node;
#endif /* not S_IFBLK */

#ifdef S_ISFIFO
      /* If local system doesn't support FIFOs, use default case.  */

    case FIFOTYPE:
# ifdef S_IFIFO
      current_stat.st_mode |= S_IFIFO;
# endif
      current_stat.st_rdev = 0;	/* FIXME: do we need this? */
      goto check_node;
#endif /* S_ISFIFO */

    check_node:
      /* FIXME: deal with umask.  */

      if (!get_stat_data (&stat_data))
	break;

      if (current_stat.st_rdev != stat_data.st_rdev)
	{
	  report_difference (_("Device numbers changed"));
	  break;
	}

      if (
#ifdef S_IFMT
	  current_stat.st_mode != stat_data.st_mode
#else
	  /* POSIX lossage.  */
	  (current_stat.st_mode & 07777) != (stat_data.st_mode & 07777)
#endif
	  )
	{
	  report_difference (_("Mode or device-type changed"));
	  break;
	}

      break;

    case GNUTYPE_DUMPDIR:
      {
	char *dumpdir_buffer = get_directory_contents (current_file_name, 0);

	if (multi_volume_option)
	  {
	    assign_string (&save_name, current_file_name);
	    save_totsize = current_stat.st_size;
	    /* save_sizeleft is set in read_and_process.  */
	  }

	if (dumpdir_buffer)
	  {
	    dumpdir_cursor = dumpdir_buffer;
	    read_and_process ((long) (current_stat.st_size), process_dumpdir);
	    free (dumpdir_buffer);
	  }
	else
	  read_and_process ((long) (current_stat.st_size), process_noop);

	if (multi_volume_option)
	  assign_string (&save_name, NULL);
	/* Fall through.  */
      }

    case DIRTYPE:
      /* Check for trailing /.  */

      name_length = strlen (current_file_name) - 1;

    really_dir:
      while (name_length && current_file_name[name_length] == PATHSEP)
	current_file_name[name_length--] = '\0';	/* zap / */

      if (!get_stat_data (&stat_data))
	break;

      if (!S_ISDIR (stat_data.st_mode))
	{
	  report_difference (_("No longer a directory"));
	  break;
	}

      if ((stat_data.st_mode & 07777) != (current_stat.st_mode & 07777))
	report_difference (_("Mode differs"));
      break;

    case GNUTYPE_VOLHDR:
      break;

    case GNUTYPE_MULTIVOL:
      {
	off_t offset;

	name_length = strlen (current_file_name) - 1;
	if (current_file_name[name_length] == PATHSEP)
	  goto really_dir;

	if (!get_stat_data (&stat_data))
	  break;

	if (!S_ISREG (stat_data.st_mode))
	  {
	    report_difference (_("Not a regular file"));
	    skip_file ((long) current_stat.st_size);
	    break;
	  }

	stat_data.st_mode &= 07777;
	offset = from_oct (1 + 12, current_header->oldgnu_header.offset);
	if (stat_data.st_size != current_stat.st_size + offset)
	  {
	    report_difference (_("Size differs"));
	    skip_file ((long) current_stat.st_size);
	    break;
	  }

	diff_handle = open (current_file_name, O_NDELAY | O_RDONLY | O_BINARY);

	if (diff_handle < 0)
	  {
	    WARN ((0, errno, _("Cannot open file %s"), current_file_name));
	    report_difference (NULL);
	    skip_file ((long) current_stat.st_size);
	    break;
	  }

	status = lseek (diff_handle, offset, 0);
	if (status != offset)
	  {
	    WARN ((0, errno, _("Cannot seek to %ld in file %s"),
		   offset, current_file_name));
	    report_difference (NULL);
	    break;
	  }

	if (multi_volume_option)
	  {
	    assign_string (&save_name, current_file_name);
	    save_totsize = stat_data.st_size;
	    /* save_sizeleft is set in read_and_process.  */
	  }

	read_and_process ((long) (current_stat.st_size), process_rawdata);

	if (multi_volume_option)
	  assign_string (&save_name, NULL);

	status = close (diff_handle);
	if (status < 0)
	  ERROR ((0, errno, _("Error while closing %s"), current_file_name));

	break;
      }
    }
}
Exemplo n.º 29
0
/* Implement the 'r' (add files to end of archive), and 'u' (add files
   to end of archive if they aren't there, or are more up to date than
   the version in the archive) commands.  */
void
update_archive (void)
{
  enum read_header previous_status = HEADER_STILL_UNREAD;
  bool found_end = false;

  name_gather ();
  open_archive (ACCESS_UPDATE);
  xheader_write_global ();

  while (!found_end)
    {
      enum read_header status = read_header (false);

      switch (status)
	{
	case HEADER_STILL_UNREAD:
	case HEADER_SUCCESS_EXTENDED:
	  abort ();

	case HEADER_SUCCESS:
	  {
	    struct name *name;

	    decode_header (current_header, &current_stat_info,
			   &current_format, 0);
	    archive_format = current_format;
	    
	    if (subcommand_option == UPDATE_SUBCOMMAND
		&& (name = name_scan (current_stat_info.file_name)) != NULL)
	      {
		struct stat s;

		chdir_do (name->change_dir);
		if (deref_stat (dereference_option,
				current_stat_info.file_name, &s) == 0
		    && s.st_mtime <= current_stat_info.stat.st_mtime)
		  add_avoided_name (current_stat_info.file_name);
	      }

	    skip_member ();
	    break;
	  }

	case HEADER_ZERO_BLOCK:
	  current_block = current_header;
	  found_end = true;
	  break;

	case HEADER_END_OF_FILE:
	  found_end = true;
	  break;

	case HEADER_FAILURE:
	  set_next_block_after (current_header);
	  switch (previous_status)
	    {
	    case HEADER_STILL_UNREAD:
	      WARN ((0, 0, _("This does not look like a tar archive")));
	      /* Fall through.  */

	    case HEADER_SUCCESS:
	    case HEADER_ZERO_BLOCK:
	      ERROR ((0, 0, _("Skipping to next header")));
	      /* Fall through.  */

	    case HEADER_FAILURE:
	      break;

	    case HEADER_END_OF_FILE:
	    case HEADER_SUCCESS_EXTENDED:
	      abort ();
	    }
	  break;
	}

      tar_stat_destroy (&current_stat_info);
      xheader_destroy (&extended_header);
      previous_status = status;
    }

  reset_eof ();
  time_to_start_writing = true;
  output_start = current_block->buffer;

  {
    char *file_name;

    while ((file_name = name_from_list ()) != NULL)
      {
	if (excluded_name (file_name))
	  continue;
	if (interactive_option && !confirm ("add", file_name))
	  continue;
	if (subcommand_option == CAT_SUBCOMMAND)
	  append_file (file_name);
	else
	  dump_file (file_name, 1, (dev_t) 0);
      }
  }

  write_eot ();
  close_archive ();
  names_notfound ();
}
Exemplo n.º 30
0
void test_lib__http2__hpack(void)
{
    h2o_mem_pool_t pool;
    h2o_mem_init_pool(&pool);

    note("decode_int");
    {
        h2o_iovec_t in;
        const uint8_t *p;
        int32_t out;
#define TEST(input, output) \
    in = h2o_iovec_init(H2O_STRLIT(input)); \
    p = (const uint8_t*)in.base; \
    out = decode_int(&p, p + in.len, 7); \
    ok(out == output); \
    ok(p == (const uint8_t*)in.base + in.len);
        TEST("\x00", 0);
        TEST("\x03", 3);
        TEST("\x81", 1);
        TEST("\x7f\x00", 127);
        TEST("\x7f\x01", 128);
        TEST("\x7f\x7f", 254);
        TEST("\x7f\x81\x00", 128);
        TEST("\x7f\x80\x01", 255);
        TEST("\x7f\xff\xff\xff\x7f", 0xfffffff + 127);
        /* failures */
        TEST("", -1);
        TEST("\x7f", -1);
        TEST("\x7f\xff", -1);
        TEST("\x7f\xff\xff\xff\xff", -1);
#undef TEST
    }

    note("decode_huffman");
    {
        h2o_iovec_t huffcode = { H2O_STRLIT("\xf1\xe3\xc2\xe5\xf2\x3a\x6b\xa0\xab\x90\xf4\xff") };
        h2o_iovec_t *decoded = decode_huffman(&pool, (const uint8_t*)huffcode.base, huffcode.len);
        ok(decoded->len == sizeof("www.example.com") -1);
        ok(strcmp(decoded->base, "www.example.com") == 0);
    }
    h2o_mem_clear_pool(&pool);

    note("decode_header (literal header field with indexing)");
    {
        struct st_h2o_decode_header_result_t result;
        h2o_hpack_header_table_t header_table;
        h2o_iovec_t in;
        int r;

        memset(&header_table, 0, sizeof(header_table));
        header_table.hpack_capacity = 4096;
        in = h2o_iovec_init(H2O_STRLIT("\x40\x0a\x63\x75\x73\x74\x6f\x6d\x2d\x6b\x65\x79\x0d\x63\x75\x73\x74\x6f\x6d\x2d\x68\x65\x61\x64\x65\x72"));
        const uint8_t *p = (const uint8_t*)in.base;
        r = decode_header(&pool, &result, &header_table, &p, p + in.len);
        ok(r == 0);
        ok(result.name->len == 10);
        ok(strcmp(result.name->base, "custom-key") == 0);
        ok(result.value->len == 13);
        ok(strcmp(result.value->base, "custom-header") == 0);
        ok(header_table.hpack_size == 55);
    }
    h2o_mem_clear_pool(&pool);

    note("decode_header (literal header field without indexing)");
    {
        struct st_h2o_decode_header_result_t result;
        h2o_hpack_header_table_t header_table;
        h2o_iovec_t in;
        int r;

        memset(&header_table, 0, sizeof(header_table));
        header_table.hpack_capacity = 4096;
        in = h2o_iovec_init(H2O_STRLIT("\x04\x0c\x2f\x73\x61\x6d\x70\x6c\x65\x2f\x70\x61\x74\x68"));
        const uint8_t *p = (const uint8_t*)in.base;
        r = decode_header(&pool, &result, &header_table, &p, p + in.len);
        ok(r == 0);
        ok(result.name == &H2O_TOKEN_PATH->buf);
        ok(result.value->len == 12);
        ok(strcmp(result.value->base, "/sample/path") == 0);
        ok(header_table.hpack_size == 0);
    }
    h2o_mem_clear_pool(&pool);

    note("decode_header (literal header field never indexed)");
    {
        struct st_h2o_decode_header_result_t result;
        h2o_hpack_header_table_t header_table;
        h2o_iovec_t in;
        int r;

        memset(&header_table, 0, sizeof(header_table));
        header_table.hpack_capacity = 4096;
        in = h2o_iovec_init(H2O_STRLIT("\x10\x08\x70\x61\x73\x73\x77\x6f\x72\x64\x06\x73\x65\x63\x72\x65\x74"));
        const uint8_t *p = (const uint8_t*)in.base;
        r = decode_header(&pool, &result, &header_table, &p, p + in.len);
        ok(r == 0);
        ok(result.name->len == 8);
        ok(strcmp(result.name->base, "password") == 0);
        ok(result.value->len == 6);
        ok(strcmp(result.value->base, "secret") == 0);
        ok(header_table.hpack_size == 0);
    }
    h2o_mem_clear_pool(&pool);

    note("decode_header (indexed header field)");
    {
        struct st_h2o_decode_header_result_t result;
        h2o_hpack_header_table_t header_table;
        h2o_iovec_t in;
        int r;

        memset(&header_table, 0, sizeof(header_table));
        header_table.hpack_capacity = 4096;
        in = h2o_iovec_init(H2O_STRLIT("\x82"));
        const uint8_t *p = (const uint8_t*)in.base;
        r = decode_header(&pool, &result, &header_table, &p, p + in.len);
        ok(r == 0);
        ok(result.name == &H2O_TOKEN_METHOD->buf);
        ok(result.value->len == 3);
        ok(strcmp(result.value->base, "GET") == 0);
        ok(header_table.hpack_size == 0);
    }
    h2o_mem_clear_pool(&pool);

    note("request examples without huffman coding");
    test_request(
        h2o_iovec_init(H2O_STRLIT("\x82\x86\x84\x41\x0f\x77\x77\x77\x2e\x65\x78\x61\x6d\x70\x6c\x65\x2e\x63\x6f\x6d")),
        h2o_iovec_init(H2O_STRLIT("\x82\x86\x84\xbe\x58\x08\x6e\x6f\x2d\x63\x61\x63\x68\x65")),
        h2o_iovec_init(H2O_STRLIT("\x82\x87\x85\xbf\x40\x0a\x63\x75\x73\x74\x6f\x6d\x2d\x6b\x65\x79\x0c\x63\x75\x73\x74\x6f\x6d\x2d\x76\x61\x6c\x75\x65")));

    note("request examples with huffman coding");
    test_request(
        h2o_iovec_init(H2O_STRLIT("\x82\x86\x84\x41\x8c\xf1\xe3\xc2\xe5\xf2\x3a\x6b\xa0\xab\x90\xf4\xff")),
        h2o_iovec_init(H2O_STRLIT("\x82\x86\x84\xbe\x58\x86\xa8\xeb\x10\x64\x9c\xbf")),
        h2o_iovec_init(H2O_STRLIT("\x82\x87\x85\xbf\x40\x88\x25\xa8\x49\xe9\x5b\xa9\x7d\x7f\x89\x25\xa8\x49\xe9\x5b\xb8\xe8\xb4\xbf")));

    note("encode_huffman");
    {
        h2o_iovec_t huffcode = { H2O_STRLIT("\xf1\xe3\xc2\xe5\xf2\x3a\x6b\xa0\xab\x90\xf4\xff") };
        char buf[sizeof("www.example.com")];
        size_t l = encode_huffman((uint8_t*)buf, (uint8_t*)H2O_STRLIT("www.example.com"));
        ok(l == huffcode.len);
        ok(memcmp(buf, huffcode.base, huffcode.len) == 0);
    }

    note("response examples with huffmann coding");
    {
        h2o_hpack_header_table_t header_table;
        h2o_res_t res;

        memset(&header_table, 0, sizeof(header_table));
        header_table.hpack_capacity = 256;

        memset(&res, 0, sizeof(res));
        res.status = 302;
        res.reason = "Found";
        h2o_add_header(&pool, &res.headers, H2O_TOKEN_CACHE_CONTROL, H2O_STRLIT("private"));
        h2o_add_header(&pool, &res.headers, H2O_TOKEN_DATE, H2O_STRLIT("Mon, 21 Oct 2013 20:13:21 GMT"));
        h2o_add_header(&pool, &res.headers, H2O_TOKEN_LOCATION, H2O_STRLIT("https://www.example.com"));
        check_flatten(&header_table, &res,
            H2O_STRLIT("\x08\x03\x33\x30\x32\x58\x85\xae\xc3\x77\x1a\x4b\x61\x96\xd0\x7a\xbe\x94\x10\x54\xd4\x44\xa8\x20\x05\x95\x04\x0b\x81\x66\xe0\x82\xa6\x2d\x1b\xff\x6e\x91\x9d\x29\xad\x17\x18\x63\xc7\x8f\x0b\x97\xc8\xe9\xae\x82\xae\x43\xd3"));

        memset(&res, 0, sizeof(res));
        res.status = 307;
        res.reason = "Temporary Redirect";
        h2o_add_header(&pool, &res.headers, H2O_TOKEN_CACHE_CONTROL, H2O_STRLIT("private"));
        h2o_add_header(&pool, &res.headers, H2O_TOKEN_DATE, H2O_STRLIT("Mon, 21 Oct 2013 20:13:21 GMT"));
        h2o_add_header(&pool, &res.headers, H2O_TOKEN_LOCATION, H2O_STRLIT("https://www.example.com"));
        check_flatten(&header_table, &res,
            H2O_STRLIT("\x08\x03\x33\x30\x37\xc0\xbf\xbe"));
#if 0
        h2o_iovec_init(H2O_STRLIT("\x48\x03\x33\x30\x37\xc1\xc0\xbf")),
        h2o_iovec_init(H2O_STRLIT("\x88\xc1\x61\x1d\x4d\x6f\x6e\x2c\x20\x32\x31\x20\x4f\x63\x74\x20\x32\x30\x31\x33\x20\x32\x30\x3a\x31\x33\x3a\x32\x32\x20\x47\x4d\x54\xc0\x5a\x04\x67\x7a\x69\x70\x77\x38\x66\x6f\x6f\x3d\x41\x53\x44\x4a\x4b\x48\x51\x4b\x42\x5a\x58\x4f\x51\x57\x45\x4f\x50\x49\x55\x41\x58\x51\x57\x45\x4f\x49\x55\x3b\x20\x6d\x61\x78\x2d\x61\x67\x65\x3d\x33\x36\x30\x30\x3b\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x31")));
#endif
    }

    h2o_mem_clear_pool(&pool);
}