Beispiel #1
0
void
TIFFInput::readspec (bool read_meta)
{
    uint32 width = 0, height = 0, depth = 0;
    unsigned short nchans = 1;
    TIFFGetField (m_tif, TIFFTAG_IMAGEWIDTH, &width);
    TIFFGetField (m_tif, TIFFTAG_IMAGELENGTH, &height);
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_IMAGEDEPTH, &depth);
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_SAMPLESPERPIXEL, &nchans);

    if (read_meta) {
        // clear the whole m_spec and start fresh
        m_spec = ImageSpec ((int)width, (int)height, (int)nchans);
    } else {
        // assume m_spec is valid, except for things that might differ
        // between MIP levels
        m_spec.width = (int)width;
        m_spec.height = (int)height;
        m_spec.depth = (int)depth;
        m_spec.full_x = 0;
        m_spec.full_y = 0;
        m_spec.full_z = 0;
        m_spec.full_width = (int)width;
        m_spec.full_height = (int)height;
        m_spec.full_depth = (int)depth;
        m_spec.nchannels = (int)nchans;
    }

    float x = 0, y = 0;
    TIFFGetField (m_tif, TIFFTAG_XPOSITION, &x);
    TIFFGetField (m_tif, TIFFTAG_YPOSITION, &y);
    m_spec.x = (int)x;
    m_spec.y = (int)y;
    m_spec.z = 0;
    // FIXME? - TIFF spec describes the positions as in resolutionunit.
    // What happens if this is not unitless pixels?  Are we interpreting
    // it all wrong?

    if (TIFFGetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLWIDTH, &width) == 1
          && width > 0)
        m_spec.full_width = width;
    if (TIFFGetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLLENGTH, &height) == 1
          && height > 0)
        m_spec.full_height = height;

    if (TIFFIsTiled (m_tif)) {
        TIFFGetField (m_tif, TIFFTAG_TILEWIDTH, &m_spec.tile_width);
        TIFFGetField (m_tif, TIFFTAG_TILELENGTH, &m_spec.tile_height);
        TIFFGetFieldDefaulted (m_tif, TIFFTAG_TILEDEPTH, &m_spec.tile_depth);
    } else {
        m_spec.tile_width = 0;
        m_spec.tile_height = 0;
        m_spec.tile_depth = 0;
    }

    m_bitspersample = 8;
    TIFFGetField (m_tif, TIFFTAG_BITSPERSAMPLE, &m_bitspersample);
    m_spec.attribute ("oiio:BitsPerSample", (int)m_bitspersample);

    unsigned short sampleformat = SAMPLEFORMAT_UINT;
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_SAMPLEFORMAT, &sampleformat);
    switch (m_bitspersample) {
    case 1:
    case 2:
    case 4:
    case 6:
        // Make 1, 2, 4, 6 bpp look like byte images
    case 8:
        if (sampleformat == SAMPLEFORMAT_UINT)
            m_spec.set_format (TypeDesc::UINT8);
        else if (sampleformat == SAMPLEFORMAT_INT)
            m_spec.set_format (TypeDesc::INT8);
        else m_spec.set_format (TypeDesc::UINT8);  // punt
        break;
    case 10:
    case 12:
    case 14:
        // Make 10, 12, 14 bpp look like 16 bit images
    case 16:
        if (sampleformat == SAMPLEFORMAT_UINT)
            m_spec.set_format (TypeDesc::UINT16);
        else if (sampleformat == SAMPLEFORMAT_INT)
            m_spec.set_format (TypeDesc::INT16);
        else if (sampleformat == SAMPLEFORMAT_IEEEFP)
            m_spec.set_format (TypeDesc::HALF); // not to spec, but why not?
        else
            m_spec.set_format (TypeDesc::UNKNOWN);
        break;
    case 32:
        if (sampleformat == SAMPLEFORMAT_IEEEFP)
            m_spec.set_format (TypeDesc::FLOAT);
        else if (sampleformat == SAMPLEFORMAT_UINT)
            m_spec.set_format (TypeDesc::UINT32);
        else if (sampleformat == SAMPLEFORMAT_INT)
            m_spec.set_format (TypeDesc::INT32);
        else
            m_spec.set_format (TypeDesc::UNKNOWN);
        break;
    case 64:
        if (sampleformat == SAMPLEFORMAT_IEEEFP)
            m_spec.set_format (TypeDesc::DOUBLE);
        else
            m_spec.set_format (TypeDesc::UNKNOWN);
        break;
    default:
        m_spec.set_format (TypeDesc::UNKNOWN);
        break;
    }

    // If we've been instructed to skip reading metadata, because it is
    // guaranteed to be identical to what we already have in m_spec,
    // skip everything following.
    if (! read_meta)
        return;

    // Use the table for all the obvious things that can be mindlessly
    // shoved into the image spec.
    for (int i = 0;  tiff_tag_table[i].name;  ++i)
        find_tag (tiff_tag_table[i].tifftag,
                  tiff_tag_table[i].tifftype, tiff_tag_table[i].name);

    // Now we need to get fields "by hand" for anything else that is less
    // straightforward...

    m_photometric = (m_spec.nchannels == 1 ? PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB);
    TIFFGetField (m_tif, TIFFTAG_PHOTOMETRIC, &m_photometric);
    m_spec.attribute ("tiff:PhotometricInterpretation", (int)m_photometric);
    if (m_photometric == PHOTOMETRIC_PALETTE) {
        // Read the color map
        unsigned short *r = NULL, *g = NULL, *b = NULL;
        TIFFGetField (m_tif, TIFFTAG_COLORMAP, &r, &g, &b);
        ASSERT (r != NULL && g != NULL && b != NULL);
        m_colormap.clear ();
        m_colormap.insert (m_colormap.end(), r, r + (1 << m_bitspersample));
        m_colormap.insert (m_colormap.end(), g, g + (1 << m_bitspersample));
        m_colormap.insert (m_colormap.end(), b, b + (1 << m_bitspersample));
        // Palette TIFF images are always 3 channels (to the client)
        m_spec.nchannels = 3;
        m_spec.default_channel_names ();
        // FIXME - what about palette + extra (alpha?) channels?  Is that
        // allowed?  And if so, ever encountered in the wild?
    }

    TIFFGetFieldDefaulted (m_tif, TIFFTAG_PLANARCONFIG, &m_planarconfig);
    m_separate = (m_planarconfig == PLANARCONFIG_SEPARATE &&
                  m_spec.nchannels > 1 &&
                  m_photometric != PHOTOMETRIC_PALETTE);
    m_spec.attribute ("tiff:PlanarConfiguration", (int)m_planarconfig);
    if (m_planarconfig == PLANARCONFIG_SEPARATE)
        m_spec.attribute ("planarconfig", "separate");
    else
        m_spec.attribute ("planarconfig", "contig");

    int compress = 0;
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_COMPRESSION, &compress);
    m_spec.attribute ("tiff:Compression", compress);
    switch (compress) {
    case COMPRESSION_NONE :
        m_spec.attribute ("compression", "none");
        break;
    case COMPRESSION_LZW :
        m_spec.attribute ("compression", "lzw");
        break;
    case COMPRESSION_CCITTRLE :
        m_spec.attribute ("compression", "ccittrle");
        break;
    case COMPRESSION_DEFLATE :
    case COMPRESSION_ADOBE_DEFLATE :
        m_spec.attribute ("compression", "zip");
        break;
    case COMPRESSION_PACKBITS :
        m_spec.attribute ("compression", "packbits");
        break;
    default:
        break;
    }

    int rowsperstrip = -1;
    if (! m_spec.tile_width) {
        TIFFGetField (m_tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
        if (rowsperstrip > 0)
            m_spec.attribute ("tiff:RowsPerStrip", rowsperstrip);
    }

    // The libtiff docs say that only uncompressed images, or those with
    // rowsperstrip==1, support random access to scanlines.
    m_no_random_access = (compress != COMPRESSION_NONE && rowsperstrip != 1);

    short resunit = -1;
    TIFFGetField (m_tif, TIFFTAG_RESOLUTIONUNIT, &resunit);
    switch (resunit) {
    case RESUNIT_NONE : m_spec.attribute ("ResolutionUnit", "none"); break;
    case RESUNIT_INCH : m_spec.attribute ("ResolutionUnit", "in"); break;
    case RESUNIT_CENTIMETER : m_spec.attribute ("ResolutionUnit", "cm"); break;
    }

    get_matrix_attribute ("worldtocamera", TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA);
    get_matrix_attribute ("worldtoscreen", TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN);
    get_int_attribute ("tiff:subfiletype", TIFFTAG_SUBFILETYPE);
    // FIXME -- should subfiletype be "conventionized" and used for all
    // plugins uniformly? 

    // Do we care about fillorder?  No, the TIFF spec says, "We
    // recommend that FillOrder=2 (lsb-to-msb) be used only in
    // special-purpose applications".  So OIIO will assume msb-to-lsb
    // convention until somebody finds a TIFF file in the wild that
    // breaks this assumption.

    // Special names for shadow maps
    char *s = NULL;
    TIFFGetField (m_tif, TIFFTAG_PIXAR_TEXTUREFORMAT, &s);
    if (s)
        m_emulate_mipmap = true;
    if (s && ! strcmp (s, "Shadow")) {
        for (int c = 0;  c < m_spec.nchannels;  ++c)
            m_spec.channelnames[c] = "z";
    }

    unsigned short *sampleinfo = NULL;
    unsigned short extrasamples = 0;
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo);
    // std::cerr << "Extra samples = " << extrasamples << "\n";
    bool alpha_is_unassociated = false;  // basic assumption
    if (extrasamples) {
        // If the TIFF ExtraSamples tag was specified, use that to figure
        // out the meaning of alpha.
        int colorchannels = 3;
        if (m_photometric == PHOTOMETRIC_MINISWHITE ||
              m_photometric == PHOTOMETRIC_MINISBLACK ||
              m_photometric == PHOTOMETRIC_PALETTE ||
              m_photometric == PHOTOMETRIC_MASK)
            colorchannels = 1;
        for (int i = 0, c = colorchannels;
             i < extrasamples && c < m_spec.nchannels;  ++i, ++c) {
            // std::cerr << "   extra " << i << " " << sampleinfo[i] << "\n";
            if (sampleinfo[i] == EXTRASAMPLE_ASSOCALPHA) {
                // This is the alpha channel, associated as usual
                m_spec.alpha_channel = c;
            } else if (sampleinfo[i] == EXTRASAMPLE_UNASSALPHA) {
                // This is the alpha channel, but color is unassociated
                m_spec.alpha_channel = c;
                alpha_is_unassociated = true;
                m_spec.attribute ("oiio:UnassociatedAlpha", 1);
            } else {
                DASSERT (sampleinfo[i] == EXTRASAMPLE_UNSPECIFIED);
                // This extra channel is not alpha at all.  Undo any
                // assumptions we previously made about this channel.
                if (m_spec.alpha_channel == c) {
                    m_spec.channelnames[c] = Strutil::format("channel%d", c);
                    m_spec.alpha_channel = -1;
                }
            }
        }
        if (m_spec.alpha_channel >= 0)
            m_spec.channelnames[m_spec.alpha_channel] = "A";
    }
    // Will we need to do alpha conversions?
    m_convert_alpha = (m_spec.alpha_channel >= 0 && alpha_is_unassociated &&
                       ! m_keep_unassociated_alpha);

    // N.B. we currently ignore the following TIFF fields:
    // GrayResponseCurve GrayResponseUnit
    // MaxSampleValue MinSampleValue
    // NewSubfileType SubfileType(deprecated)
    // Colorimetry fields

    // Search for an EXIF IFD in the TIFF file, and if found, rummage 
    // around for Exif fields.
#if TIFFLIB_VERSION > 20050912    /* compat with old TIFF libs - skip Exif */
    int exifoffset = 0;
    if (TIFFGetField (m_tif, TIFFTAG_EXIFIFD, &exifoffset) &&
            TIFFReadEXIFDirectory (m_tif, exifoffset)) {
        for (int i = 0;  exif_tag_table[i].name;  ++i)
            find_tag (exif_tag_table[i].tifftag, exif_tag_table[i].tifftype,
                      exif_tag_table[i].name);
        // I'm not sure what state TIFFReadEXIFDirectory leaves us.
        // So to be safe, close and re-seek.
        TIFFClose (m_tif);
        m_tif = TIFFOpen (m_filename.c_str(), "rm");
        TIFFSetDirectory (m_tif, m_subimage);

        // A few tidbits to look for
        ImageIOParameter *p;
        if ((p = m_spec.find_attribute ("Exif:ColorSpace", TypeDesc::INT))) {
            // Exif spec says that anything other than 0xffff==uncalibrated
            // should be interpreted to be sRGB.
            if (*(const int *)p->data() != 0xffff)
                m_spec.attribute ("oiio::ColorSpace", "sRGB");
        }
    }
#endif

#if TIFFLIB_VERSION >= 20051230
    // Search for IPTC metadata in IIM form -- but older versions of
    // libtiff botch the size, so ignore it for very old libtiff.
    int iptcsize = 0;
    const void *iptcdata = NULL;
    if (TIFFGetField (m_tif, TIFFTAG_RICHTIFFIPTC, &iptcsize, &iptcdata)) {
        std::vector<uint32> iptc ((uint32 *)iptcdata, (uint32 *)iptcdata+iptcsize);
        if (TIFFIsByteSwapped (m_tif))
            TIFFSwabArrayOfLong ((uint32*)&iptc[0], iptcsize);
        decode_iptc_iim (&iptc[0], iptcsize*4, m_spec);
    }
#endif

    // Search for an XML packet containing XMP (IPTC, Exif, etc.)
    int xmlsize = 0;
    const void *xmldata = NULL;
    if (TIFFGetField (m_tif, TIFFTAG_XMLPACKET, &xmlsize, &xmldata)) {
        // std::cerr << "Found XML data, size " << xmlsize << "\n";
        if (xmldata && xmlsize) {
            std::string xml ((const char *)xmldata, xmlsize);
            decode_xmp (xml, m_spec);
        }
    }

#if 0
    // Experimental -- look for photoshop data
    int photoshopsize = 0;
    const void *photoshopdata = NULL;
    if (TIFFGetField (m_tif, TIFFTAG_PHOTOSHOP, &photoshopsize, &photoshopdata)) {
        std::cerr << "Found PHOTOSHOP data, size " << photoshopsize << "\n";
        if (photoshopdata && photoshopsize) {
//            std::string photoshop ((const char *)photoshopdata, photoshopsize);
//            std::cerr << "PHOTOSHOP:\n" << photoshop << "\n---\n";
        }
    }
#endif
}
Beispiel #2
0
int main(int argc, char *argv[]) 
{

	uid_t uid;
	uint8_t SN[10];
	uint16_t CType=0;
	uint8_t SN_len=0;
	char status;
	int tmp,i;

	char str[255];
	char *p;
	char sn_str[23];
	pid_t child;
	int max_page=0;
	uint8_t page_step=0;

	FILE * fmem_str;
	char save_mem=0;
	char fmem_path[255];
	uint8_t use_gpio=0;
	uint8_t gpio=255;
	uint32_t spi_speed=10000000L;
	int fd = -1 ;

//by myself
	unsigned char blockaddr = (unsigned char)atoi(argv[1]);
	unsigned char key_passwd = (unsigned char)atoi(argv[2]) ;
	int n = 0;
	unsigned char statu = 0;
	unsigned char data_test[16];

	for(n = 0; n < 6; n++) {
		data_test[n] = 0x00;
	}
	data_test[6] = 0xff ;
	data_test[7] = 0x07;
	data_test[8] = 0x80 ;
	data_test[9] = 0x69 ;

	for(n=10;n<16;n++){
		data_test[n] = 0xFF ;
	}
	
#if 1
	if(argc < 3) {
		printf("command error and try again like this : ./a.out 1 \n");
		return -1;
	}
#endif
	if( (fd = spi_open() )< 0) return -1 ;
	/*
	 * spi mode
	 */
	unsigned char mode = 3;
//	unsigned char mode = 1;
	unsigned char mode_t ;
	unsigned char bits = 8 ;
	unsigned int  speed = 120000000 ;
	int ret = -1 ;
	ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
	if (ret == -1)
		printf("can't set spi mode");

	ret = ioctl(fd, SPI_IOC_RD_MODE, &mode_t);
	if (ret == -1)
		printf("can't get spi mode");

	/*
	 * bits per word
	 */
	ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
	if (ret == -1)
		printf("can't set bits per word");

	unsigned char bits_t ;
	ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits_t);
	if (ret == -1)
		printf("can't get bits per word");

	/*
	 * max speed hz
	 */
	ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		printf("can't set max speed hz");

	unsigned int  speed_t ;
	ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed_t);
	if (ret == -1)
		printf("can't get max speed hz");

	printf("spidev hw info : mode:%d  bits:%d speed:%d\n",mode_t,bits_t,speed_t) ;

//many changes in InitRc522 function, please check it.	
	printf("we will read block [%d] value !\n",blockaddr);

	printf("rc522 is soft_rest ....\n");
	PcdReset();
#if 1	
	printf("rc522 open antenna ... \n");
	usleep(100*1000);
	PcdAntennaOn();
	
	memset(Tmpbuff,0,20);

	printf("now find tag .....\n");
	while(1) {
	 statu = PcdRequest(PICC_REQALL,Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("find the tag and the tag type is :");
		for(n = 0; n < (sizeof(Tmpbuff) / sizeof(Tmpbuff[0])); n++) {
			printf("0x%x ",Tmpbuff[n]);
		}
		printf("\n");
	 }else {
	 	continue ;
	 }
	 
	 printf("Now is running Anticoll ....\n");
	 statu = PcdAnticoll(PICC_ANTICOLL1, Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("Anticoll success and the tag sn is ");
		for(n = 0; n < (sizeof(Tmpbuff) / sizeof(Tmpbuff[0])); n++) {
			printf("0x%x ",Tmpbuff[n]);
		}
		printf("\n");
	 }else {
		printf("Anticoll faild !\n");
	 	continue ;
	 }

	 printf("Now start select an tag .... \n");
	 statu = PcdSelect(PICC_ANTICOLL1, Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("select tag is success !\n");
	 }else {
	 	printf("sorry,select tag faild !\n");
		continue ;
	 }

	 printf("Now start authstate ... \n");
	 statu = PcdAuthState(PICC_AUTHENT1A, blockaddr, key, Tmpbuff);
	// statu = PcdAuthState(PICC_AUTHENT1B, blockaddr, key, Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("authstate success !\n");
	 }else {
	 	printf("authstate faild and continue find tag....\n");
		continue ;
	 }
#if 1
	 if(key_passwd == 3 ) {
		 printf("Now start write [%d] blockaddr... \n",key_passwd);
		 statu = PcdWrite(key_passwd, data_test);
		 if(statu == TAG_OK) {
				printf("write success !\n");
		 }else {
		 	printf("write faild !\n");
			continue ;
		 }

		statu = PcdRead(key_passwd,Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("read success and the data is ");
		for(n = 0; n < 16; n++) {
			printf("0x%x ",Tmpbuff[n]);
		}
		printf("\n");
	 }else {
	 	printf("read faild and continue find tag ....\n");
		continue ;
	 }

	 }else {
		 printf("[%d] address is only read !\n",blockaddr);
	 }
#endif
	 printf("Now start read [%d] addresss ... \n",blockaddr);
	 statu = PcdRead(blockaddr,Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("read success and the data is ");
		for(n = 0; n < 16; n++) {
			printf("0x%x ",Tmpbuff[n]);
		}
		printf("\n");
	 }else {
	 	printf("read faild and continue find tag ....\n");
		continue ;
	 }

	 printf("Now sleep the picc \n");
	 PcdHalt();
	 break ;
	}

//	InitRc522();
#if 0

	while(1) {
		status= find_tag(&CType);
		printf("status is [%d] :Ctype [%x] \n",status,CType) ;
		if (status==TAG_NOTAG) {
			printf("find tag again !\n") ;
			usleep(200000);
			continue;
		}else if ((status!=TAG_OK)&&(status!=TAG_COLLISION)) {
			printf("status!=TAG_OK)&&(status!=TAG_COLLISION again \n") ;
			continue;
		}
		printf("Ctype is %d\n",CType);
		if (select_tag_sn(SN,&SN_len)!=TAG_OK) {
			printf("select_tag_sn(SN,&SN_len)!=TAG_OK) again \n") ;
			continue;
		}

		read_tag_str(0,str);
		printf("str:%s\n",str) ;
		PcdHalt();
		break  ;
	}
#endif
#endif
	printf("now start close spi orpe.....\n");
	spi_close() ; 

	return 0;

}
Beispiel #3
0
isc_result_t
dst__privstruct_writefile(const dst_key_t *key, const dst_private_t *priv,
			  const char *directory)
{
	FILE *fp;
	isc_result_t result;
	char filename[ISC_DIR_NAMEMAX];
	char buffer[MAXFIELDSIZE * 2];
	isc_fsaccess_t access;
	isc_stdtime_t when;
	isc_uint32_t value;
	isc_buffer_t b;
	isc_region_t r;
	int major, minor;
	mode_t mode;
	int i, ret;

	REQUIRE(priv != NULL);

	ret = check_data(priv, dst_key_alg(key), ISC_FALSE, key->external);
	if (ret < 0)
		return (DST_R_INVALIDPRIVATEKEY);
	else if (ret != ISC_R_SUCCESS)
		return (ret);

	isc_buffer_init(&b, filename, sizeof(filename));
	result = dst_key_buildfilename(key, DST_TYPE_PRIVATE, directory, &b);
	if (result != ISC_R_SUCCESS)
		return (result);

	result = isc_file_mode(filename, &mode);
	if (result == ISC_R_SUCCESS && mode != 0600) {
		/* File exists; warn that we are changing its permissions */
		isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
			      DNS_LOGMODULE_DNSSEC, ISC_LOG_WARNING,
			      "Permissions on the file %s "
			      "have changed from 0%o to 0600 as "
			      "a result of this operation.",
			      filename, (unsigned int)mode);
	}

	if ((fp = fopen(filename, "w")) == NULL)
		return (DST_R_WRITEERROR);

	access = 0;
	isc_fsaccess_add(ISC_FSACCESS_OWNER,
			 ISC_FSACCESS_READ | ISC_FSACCESS_WRITE,
			 &access);
	(void)isc_fsaccess_set(filename, access);

	dst_key_getprivateformat(key, &major, &minor);
	if (major == 0 && minor == 0) {
		major = DST_MAJOR_VERSION;
		minor = DST_MINOR_VERSION;
	}

	/* XXXDCL return value should be checked for full filesystem */
	fprintf(fp, "%s v%d.%d\n", PRIVATE_KEY_STR, major, minor);

	fprintf(fp, "%s %d ", ALGORITHM_STR, dst_key_alg(key));

	/* XXXVIX this switch statement is too sparse to gen a jump table. */
	switch (dst_key_alg(key)) {
	case DST_ALG_RSAMD5:
		fprintf(fp, "(RSA)\n");
		break;
	case DST_ALG_DH:
		fprintf(fp, "(DH)\n");
		break;
	case DST_ALG_DSA:
		fprintf(fp, "(DSA)\n");
		break;
	case DST_ALG_RSASHA1:
		fprintf(fp, "(RSASHA1)\n");
		break;
	case DST_ALG_NSEC3RSASHA1:
		fprintf(fp, "(NSEC3RSASHA1)\n");
		break;
	case DST_ALG_NSEC3DSA:
		fprintf(fp, "(NSEC3DSA)\n");
		break;
	case DST_ALG_RSASHA256:
		fprintf(fp, "(RSASHA256)\n");
		break;
	case DST_ALG_RSASHA512:
		fprintf(fp, "(RSASHA512)\n");
		break;
	case DST_ALG_ECCGOST:
		fprintf(fp, "(ECC-GOST)\n");
		break;
	case DST_ALG_ECDSA256:
		fprintf(fp, "(ECDSAP256SHA256)\n");
		break;
	case DST_ALG_ECDSA384:
		fprintf(fp, "(ECDSAP384SHA384)\n");
		break;
	case DST_ALG_HMACMD5:
		fprintf(fp, "(HMAC_MD5)\n");
		break;
	case DST_ALG_HMACSHA1:
		fprintf(fp, "(HMAC_SHA1)\n");
		break;
	case DST_ALG_HMACSHA224:
		fprintf(fp, "(HMAC_SHA224)\n");
		break;
	case DST_ALG_HMACSHA256:
		fprintf(fp, "(HMAC_SHA256)\n");
		break;
	case DST_ALG_HMACSHA384:
		fprintf(fp, "(HMAC_SHA384)\n");
		break;
	case DST_ALG_HMACSHA512:
		fprintf(fp, "(HMAC_SHA512)\n");
		break;
	default:
		fprintf(fp, "(?)\n");
		break;
	}

	for (i = 0; i < priv->nelements; i++) {
		const char *s;

		s = find_tag(priv->elements[i].tag);

		r.base = priv->elements[i].data;
		r.length = priv->elements[i].length;
		isc_buffer_init(&b, buffer, sizeof(buffer));
		result = isc_base64_totext(&r, sizeof(buffer), "", &b);
		if (result != ISC_R_SUCCESS) {
			fclose(fp);
			return (DST_R_INVALIDPRIVATEKEY);
		}
		isc_buffer_usedregion(&b, &r);

	       fprintf(fp, "%s %.*s\n", s, (int)r.length, r.base);
	}

	if (key->external)
	       fprintf(fp, "External:\n");

	/* Add the metadata tags */
	if (major > 1 || (major == 1 && minor >= 3)) {
		for (i = 0; i < NUMERIC_NTAGS; i++) {
			result = dst_key_getnum(key, i, &value);
			if (result != ISC_R_SUCCESS)
				continue;
			fprintf(fp, "%s %u\n", numerictags[i], value);
		}
		for (i = 0; i < TIMING_NTAGS; i++) {
			result = dst_key_gettime(key, i, &when);
			if (result != ISC_R_SUCCESS)
				continue;

			isc_buffer_init(&b, buffer, sizeof(buffer));
			result = dns_time32_totext(when, &b);
			if (result != ISC_R_SUCCESS) {
			       fclose(fp);
			       return (DST_R_INVALIDPRIVATEKEY);
			}

			isc_buffer_usedregion(&b, &r);

			fprintf(fp, "%s %.*s\n", timetags[i], (int)r.length,
				r.base);
		}
	}

	fflush(fp);
	result = ferror(fp) ? DST_R_WRITEERROR : ISC_R_SUCCESS;
	fclose(fp);
	return (result);
}
Beispiel #4
0
/* wav input */
static int wav_read_header(AVFormatContext *s,
                           AVFormatParameters *ap)
{
    int64_t size, av_uninit(data_size);
    int64_t sample_count=0;
    int rf64;
    unsigned int tag;
    AVIOContext *pb = s->pb;
    AVStream *st;
    WAVContext *wav = s->priv_data;

    /* check RIFF header */
    tag = avio_rl32(pb);

    rf64 = tag == MKTAG('R', 'F', '6', '4');
    if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
        return -1;
    avio_rl32(pb); /* file size */
    tag = avio_rl32(pb);
    if (tag != MKTAG('W', 'A', 'V', 'E'))
        return -1;

    if (rf64) {
        if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
            return -1;
        size = avio_rl32(pb);
        if (size < 16)
            return -1;
        avio_rl64(pb); /* RIFF size */
        data_size = avio_rl64(pb);
        sample_count = avio_rl64(pb);
        avio_seek(pb, size - 16, SEEK_CUR); /* skip rest of ds64 chunk */
    }

    /* parse fmt header */
    size = find_tag(pb, MKTAG('f', 'm', 't', ' '));
    if (size < 0)
        return -1;
    st = av_new_stream(s, 0);
    if (!st)
        return AVERROR(ENOMEM);

    ff_get_wav_header(pb, st->codec, size);
    st->need_parsing = AVSTREAM_PARSE_FULL;

    av_set_pts_info(st, 64, 1, st->codec->sample_rate);

    for (;;) {
        if (url_feof(pb))
            return -1;
        size = next_tag(pb, &tag);
        if (tag == MKTAG('d', 'a', 't', 'a')){
            break;
        }else if (tag == MKTAG('f','a','c','t') && !sample_count){
            sample_count = avio_rl32(pb);
            size -= 4;
        }
        avio_seek(pb, size, SEEK_CUR);
    }
    if (rf64)
        size = data_size;
    if (size < 0)
        return -1;
    if (!size) {
        wav->data_end = INT64_MAX;
    } else
        wav->data_end= avio_tell(pb) + size;

    if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))
        sample_count = (size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
    if (sample_count)
        st->duration = sample_count;
    return 0;
}
static gboolean
file_is_der_or_pem (const char *filename,
                    gboolean privkey,
                    gboolean *out_privkey_encrypted)
{
	int fd;
	unsigned char buffer[8192];
	ssize_t bytes_read;
	gboolean success = FALSE;

	fd = open (filename, O_RDONLY);
	if (fd < 0)
		return FALSE;

	bytes_read = read (fd, buffer, sizeof (buffer) - 1);
	if (bytes_read < 400)  /* needs to be lower? */
		goto out;
	buffer[bytes_read] = '\0';

	/* Check for DER signature */
	if (bytes_read > 2 && buffer[0] == 0x30 && buffer[1] == 0x82) {
		success = TRUE;
		goto out;
	}

	/* Check for PEM signatures */
	if (privkey) {
		if (find_tag (pem_rsa_key_begin, (const char *) buffer, bytes_read)) {
			success = TRUE;
			if (out_privkey_encrypted)
				*out_privkey_encrypted = pem_file_is_encrypted ((const char *) buffer, bytes_read);
			goto out;
		}

		if (find_tag (pem_dsa_key_begin, (const char *) buffer, bytes_read)) {
			success = TRUE;
			if (out_privkey_encrypted)
				*out_privkey_encrypted = pem_file_is_encrypted ((const char *) buffer, bytes_read);
			goto out;
		}

		if (find_tag (pem_pkcs8_enc_key_begin, (const char *) buffer, bytes_read)) {
			success = TRUE;
			if (out_privkey_encrypted)
				*out_privkey_encrypted = TRUE;
			goto out;
		}

		if (find_tag (pem_pkcs8_dec_key_begin, (const char *) buffer, bytes_read)) {
			success = TRUE;
			if (out_privkey_encrypted)
				*out_privkey_encrypted = FALSE;
			goto out;
		}
	} else {
		if (find_tag (pem_cert_begin, (const char *) buffer, bytes_read)) {
			success = TRUE;
			goto out;
		}
	}

out:
	close (fd);
	return success;
}
Beispiel #6
0
int
dst__privstruct_writefile(const dst_key_t *key, const dst_private_t *priv,
			  const char *directory)
{
	FILE *fp;
	int ret, i;
	isc_result_t iret;
	char filename[ISC_DIR_NAMEMAX];
	char buffer[MAXFIELDSIZE * 2];
	isc_buffer_t b;
	isc_fsaccess_t access;

	REQUIRE(priv != NULL);

	if (check_data(priv, dst_key_alg(key), ISC_FALSE) < 0)
		return (DST_R_INVALIDPRIVATEKEY);

	isc_buffer_init(&b, filename, sizeof(filename));
	ret = dst_key_buildfilename(key, DST_TYPE_PRIVATE, directory, &b);
	if (ret != ISC_R_SUCCESS)
		return (ret);

	if ((fp = fopen(filename, "w")) == NULL)
		return (DST_R_WRITEERROR);

	access = 0;
	isc_fsaccess_add(ISC_FSACCESS_OWNER,
			 ISC_FSACCESS_READ | ISC_FSACCESS_WRITE,
			 &access);
	(void)isc_fsaccess_set(filename, access);

	/* XXXDCL return value should be checked for full filesystem */
	fprintf(fp, "%s v%d.%d\n", PRIVATE_KEY_STR, MAJOR_VERSION,
		MINOR_VERSION);

	fprintf(fp, "%s %d ", ALGORITHM_STR, dst_key_alg(key));
	/* XXXVIX this switch statement is too sparse to gen a jump table. */
	switch (dst_key_alg(key)) {
	case DST_ALG_RSAMD5:
		fprintf(fp, "(RSA)\n");
		break;
	case DST_ALG_DH:
		fprintf(fp, "(DH)\n");
		break;
	case DST_ALG_DSA:
		fprintf(fp, "(DSA)\n");
		break;
	case DST_ALG_RSASHA1:
		fprintf(fp, "(RSASHA1)\n");
		break;
	case DST_ALG_NSEC3DSA:
		fprintf(fp, "(NSEC3DSA)\n");
		break;
	case DST_ALG_NSEC3RSASHA1:
		fprintf(fp, "(NSEC3RSASHA1)\n");
		break;
	case DST_ALG_RSASHA256:
		fprintf(fp, "(RSASHA256)\n");
		break;
	case DST_ALG_RSASHA512:
		fprintf(fp, "(RSASHA512)\n");
		break;
	case DST_ALG_HMACMD5:
		fprintf(fp, "(HMAC_MD5)\n");
		break;
	case DST_ALG_HMACSHA1:
		fprintf(fp, "(HMAC_SHA1)\n");
		break;
	case DST_ALG_HMACSHA224:
		fprintf(fp, "(HMAC_SHA224)\n");
		break;
	case DST_ALG_HMACSHA256:
		fprintf(fp, "(HMAC_SHA256)\n");
		break;
	case DST_ALG_HMACSHA384:
		fprintf(fp, "(HMAC_SHA384)\n");
		break;
	case DST_ALG_HMACSHA512:
		fprintf(fp, "(HMAC_SHA512)\n");
		break;
	default:
		fprintf(fp, "(?)\n");
		break;
	}

	for (i = 0; i < priv->nelements; i++) {
		isc_buffer_t b;
		isc_region_t r;
		const char *s;

		s = find_tag(priv->elements[i].tag);

		r.base = priv->elements[i].data;
		r.length = priv->elements[i].length;
		isc_buffer_init(&b, buffer, sizeof(buffer));
		iret = isc_base64_totext(&r, sizeof(buffer), "", &b);
		if (iret != ISC_R_SUCCESS) {
			fclose(fp);
			return (DST_R_INVALIDPRIVATEKEY);
		}
		isc_buffer_usedregion(&b, &r);

		fprintf(fp, "%s ", s);
		isc_util_fwrite(r.base, 1, r.length, fp);
		fprintf(fp, "\n");
	}

	fflush(fp);
	iret = ferror(fp) ? DST_R_WRITEERROR : ISC_R_SUCCESS;
	fclose(fp);
	return (iret);
}
Beispiel #7
0
void
child_deliver_cmd_hook(pid_t pid, struct account *a, unused struct msg *msg,
    struct child_deliver_data *data, int *result)
{
	struct mail_ctx			*mctx = data->mctx;
	struct mail			*m = data->mail;
	struct match_command_data	*cmddata = data->cmddata;
	int				 flags, status, found = 0;
	char				*s, *cause, *lbuf, *out, *err, tag[24];
	size_t				 llen;
	struct cmd		 	*cmd = NULL;
	struct rmlist			 rml;
	u_int				 i;

	/* If this is the parent, do nothing. */
	if (pid != 0) {
		xfree(mctx);
		return;
	}

	/* Sort out the command. */
	s = replacepath(
	    &cmddata->cmd, m->tags, m, &m->rml, find_tag(m->tags, "home"));
        if (s == NULL || *s == '\0') {
		log_warnx("%s: empty command", a->name);
		goto error;
        }

	log_debug2("%s: %s: started (ret=%d re=%s)", a->name, s, cmddata->ret,
	    cmddata->re.str == NULL ? "none" : cmddata->re.str);
	flags = CMD_ONCE;
	if (cmddata->pipe)
		flags |= CMD_IN;
	if (cmddata->re.str != NULL)
		flags |= CMD_OUT;
	cmd = cmd_start(s, flags, m->data, m->size, &cause);
	if (cmd == NULL) {
		log_warnx("%s: %s: %s", a->name, s, cause);
		goto error;
	}

	llen = IO_LINESIZE;
	lbuf = xmalloc(llen);

	for (;;) {
		/* Stop early if looking for regexp only. */
		if (found && cmddata->ret == -1) {
			log_debug3("%s: %s: found. stopping early", a->name, s);
			status = 1;
			break;
		}

		status = cmd_poll(
		    cmd, &out, &err, &lbuf, &llen, conf.timeout, &cause);
		if (status == -1) {
			log_warnx("%s: %s: %s", a->name, s, cause);
			goto error;
		}
       		if (status != 0)
			break;
		if (err != NULL)
			log_warnx("%s: %s: %s", a->name, s, err);
		if (out == NULL)
			continue;
		log_debug3("%s: %s: out: %s", a->name, s, out);
		if (found)
			continue;

		found = re_string(&cmddata->re, out, &rml, &cause);
		if (found == -1) {
			log_warnx("%s: %s", a->name, cause);
			goto error;
		}
		if (found != 1)
			continue;
		/* Save the matches. */
		if (!rml.valid)
			continue;
		for (i = 0; i < NPMATCH; i++) {
			if (!rml.list[i].valid)
				break;
			xsnprintf(tag, sizeof tag, "command%u", i);
			add_tag(&m->tags, tag, "%.*s", (int) (rml.list[i].eo -
			    rml.list[i].so), out + rml.list[i].so);
		}
	}
	status--;

	log_debug2("%s: %s: returned %d, found %d", a->name, s, status, found);

	cmd_free(cmd);
	xfree(s);
	xfree(lbuf);

	status = cmddata->ret == status;
	if (cmddata->ret != -1 && cmddata->re.str != NULL)
		*result = (found && status) ? MATCH_TRUE : MATCH_FALSE;
	else if (cmddata->ret != -1 && cmddata->re.str == NULL)
		*result = status ? MATCH_TRUE : MATCH_FALSE;
	else if (cmddata->ret == -1 && cmddata->re.str != NULL)
		*result = found ? MATCH_TRUE : MATCH_FALSE;
	else
		*result = MATCH_ERROR;
	return;

error:
	if (cause != NULL)
		xfree(cause);
	if (cmd != NULL)
		cmd_free(cmd);
	if (s != NULL)
		xfree(s);
	if (lbuf != NULL)
		xfree(lbuf);
	*result = MATCH_ERROR;
}
Beispiel #8
0
/////////////////////////////////////////////////////////////////////
//	Retrieve analog calibration data and rewrite to the flash
/////////////////////////////////////////////////////////////////////
void main()
{
	auto unsigned long fileptr, tempPtr, xmemPtr, index;
	auto unsigned long len;
	auto int i;
	auto char serialNumber[64];

	//------------------------------------------------------------------------
	//		Initialize the Controller
	//------------------------------------------------------------------------
	brdInit();

   BitWrPortI(PEDR, &PEDRShadow, 0, 5);	//set low to enable rs232 device

	seropen(BAUDRATE);	//set baud rates for the serial ports to be used
	serwrFlush();		//clear Rx and Tx data buffers
	serrdFlush();

	//------------------------------------------------------------------------
	//		Allocate and Clear XMEM
	//------------------------------------------------------------------------

	// Allocate XMEM memory for the file that will be read in from the PC
	xmemPtr = xalloc(FILEBUFSIZE);

	// Clear the buffer in XMEM
	for(index =0; index < FILEBUFSIZE; index++)
	{
		root2xmem(xmemPtr + index, "\x00", 1);
	}

	//------------------------------------------------------------------------
	//		Download the Data File from the PC
	//------------------------------------------------------------------------
	sprintf(string, "\r\nWaiting...Please Send Data file\n\r");
	serwrite(string, strlen(string));

	// Get the calibration data file from the PC and put it into XMEM
	if(!(len = getfile(xmemPtr)))
	{
		caldata_error(string, "\r\n\nEncounter an error while reading calibration file");
		exit(1);
	}
	fileptr = xmemPtr;
	sprintf(string, "\r\n\nDownload Complete\n\n\r");
	serwrite(string, strlen(string));

	//------------------------------------------------------------------------
	//	 Parse data file and write to calibrations to flash
	//------------------------------------------------------------------------
	sprintf(string, "\r\nParsing data file\n\r");
	serwrite(string, strlen(string));

	tempPtr = find_tag(fileptr, len);

	sprintf(string, "\r\n\nExiting....Calibration data successfully written\n\n\r");
	serwrite(string, strlen(string));
	while (serwrFree() != OUTBUFSIZE);
   while((RdPortI(SXSR)&0x08) || (RdPortI(SXSR)&0x04));
	serclose();
}
Beispiel #9
0
char *
replace(char *src, struct strb *tags, struct mail *m, struct rmlist *rml)
{
	const char	*tptr, *alias;
	char		*ptr, *tend, *dst, ch;
	size_t	 	 i, off, len, tlen;
	int		 strip;

	if (src == NULL)
		return (NULL);
	if (*src == '\0')
		return (xstrdup(""));

	off = 0;
	len = REPLBUFSIZE;
	dst = xmalloc(len);

	strip = 1;
	for (ptr = src; *ptr != '\0'; ptr++) {
		switch (*ptr) {
		case '%':
			break;
		default:
			ENSURE_FOR(dst, len, off, 1);
			dst[off++] = *ptr;
			continue;
		}

		switch (ch = *++ptr) {
		case '\0':
			goto out;
		case '%':
			ENSURE_FOR(dst, len, off, 1);
			dst[off++] = '%';
			continue;
		case '[':
			if ((tend = strchr(ptr, ']')) == NULL) {
				ENSURE_FOR(dst, len, off, 2);
				dst[off++] = '%';
				dst[off++] = '[';
				continue;
			}
			ptr++;

			if (*ptr == ':') {
				strip = 0;
				ptr++;
			}
			if (ptr == tend)
				continue;

			*tend = '\0';
			if ((tptr = find_tag(tags, ptr)) == NULL) {
				*tend = ']';
				ptr = tend;
				continue;
			}
			tlen = strlen(tptr);
			*tend = ']';

			ptr = tend;
			break;
		case ':':
			ch = *++ptr;
			if (ch >= '0' && ch <= '9') {
				tptr = submatch(ch, m, rml, &tlen);
				if (tptr == NULL)
					continue;
				strip = 0;
				break;
			}

			ENSURE_FOR(dst, len, off, 1);
			dst[off++] = ch;
			continue;
		default:
			if (ch >= '0' && ch <= '9') {
				tptr = submatch(ch, m, rml, &tlen);
				if (tptr == NULL)
					continue;
				break;
			}

			alias = NULL;
			if (ALIAS_IDX((u_char) ch) != -1)
				alias = aliases[ALIAS_IDX((u_char) ch)];
			if (alias == NULL)
				continue;

			if ((tptr = find_tag(tags, alias)) == NULL)
				continue;
			tlen = strlen(tptr);
			break;
		}

		if (tlen == 0)
			continue;
		ENSURE_FOR(dst, len, off, tlen);
		if (!strip) {
			memcpy(dst + off, tptr, tlen);
			off += tlen;
			continue;
		}
		for (i = 0; i < tlen; i++) {
			if (strchr(conf.strip_chars, tptr[i]) == NULL)
				dst[off++] = tptr[i];
		}
	}

out:
	ENSURE_FOR(dst, len, off, 1);
	dst[off] = '\0';

	return (dst);
}
Beispiel #10
0
static int wav_read_packet(AVFormatContext *s,
                           AVPacket *pkt)
{
    int ret, size;
    int64_t left;
    AVStream *st;
    WAVDemuxContext *wav = s->priv_data;

    if (wav->smv_data_ofs > 0) {
        int64_t audio_dts, video_dts;
smv_retry:
        audio_dts = s->streams[0]->cur_dts;
        video_dts = s->streams[1]->cur_dts;
        if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
            audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);
            video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);
            wav->smv_last_stream = video_dts >= audio_dts;
        }
        wav->smv_last_stream = !wav->smv_last_stream;
        wav->smv_last_stream |= wav->audio_eof;
        wav->smv_last_stream &= !wav->smv_eof;
        if (wav->smv_last_stream) {
            uint64_t old_pos = avio_tell(s->pb);
            uint64_t new_pos = wav->smv_data_ofs +
                               wav->smv_block * wav->smv_block_size;
            if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
                ret = AVERROR_EOF;
                goto smv_out;
            }
            size = avio_rl24(s->pb);
            ret  = av_get_packet(s->pb, pkt, size);
            if (ret < 0)
                goto smv_out;
            pkt->pos -= 3;
            pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg;
            wav->smv_block++;
            pkt->stream_index = 1;
smv_out:
            avio_seek(s->pb, old_pos, SEEK_SET);
            if (ret == AVERROR_EOF) {
                wav->smv_eof = 1;
                goto smv_retry;
            }
            return ret;
        }
    }

    st = s->streams[0];

    left = wav->data_end - avio_tell(s->pb);
    if (wav->ignore_length)
        left= INT_MAX;
    if (left <= 0) {
        if (CONFIG_W64_DEMUXER && wav->w64)
            left = find_guid(s->pb, guid_data) - 24;
        else
            left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
        if (left < 0) {
            wav->audio_eof = 1;
            if (wav->smv_data_ofs > 0 && !wav->smv_eof)
                goto smv_retry;
            return AVERROR_EOF;
        }
        wav->data_end= avio_tell(s->pb) + left;
    }

    size = MAX_SIZE;
    if (st->codec->block_align > 1) {
        if (size < st->codec->block_align)
            size = st->codec->block_align;
        size = (size / st->codec->block_align) * st->codec->block_align;
    }
    size = FFMIN(size, left);
    ret  = av_get_packet(s->pb, pkt, size);
    if (ret < 0)
        return ret;
    pkt->stream_index = 0;

    return ret;
}
Beispiel #11
0
void convert_file(char *source_filename) {
  char html_filename[NAME_MAX + 1];
  char *relative_filename;
  char *base_filename;
  char *ext, *p;
  int is_c = 0;
  int is_asm = 0;
  FILE *src;
  FILE *out;
  int line_num;
  char line[STRSIZE];
  char filename[STRSIZE];
  char token[STRSIZE];
  char url[STRSIZE];
  int in_comment;
  
  relative_filename = source_filename + source_prefix_len;
  ext = "";
  base_filename = relative_filename;
  p = relative_filename;
  while (*p) {
    if (*p == '/') {
      base_filename = p + 1;
      ext = "";
    }
    if (*p == '.') ext = p;
    p++;
  }
  
  strcpy(html_filename, output_dir);
  strcat(html_filename, "/");
  strcat(html_filename, relative_filename);
  strcat(html_filename, ".html");

  if (strcmp(ext, ".c") == 0) is_c = 1;
  if (strcmp(ext, ".h") == 0) is_c = 1;
  if (strcmp(ext, ".cpp") == 0) is_c = 1;
  if (strcmp(ext, ".asm") == 0) is_asm = 1;
  if (strcmp(ext, ".s") == 0) is_asm = 1;

  if (!is_c && !is_asm) return;
  
  src = fopen(source_filename, "rt");
  if (!src) {
    perror(source_filename);
    return;
  }
  
  out = fopen(html_filename, "wb");
  if (!out) {
    perror(html_filename);
    return;
  }

  fprintf(out, "<html>\r\n");
  fprintf(out, "<head>\r\n");
  fprintf(out, "<title>%s - %s</title>\r\n", base_filename, title);
  fprintf(out, "<style type='text/css'>\r\n");
  fprintf(out, "a:link {text-decoration: none; color:inherit}\r\n");
  fprintf(out, "a:visited {text-decoration: none; color:inherit}\r\n");
  fprintf(out, "a:active {text-decoration: none; color:inherit}\r\n");
  fprintf(out, "</style>\r\n");
  fprintf(out, "</head>\r\n");
  fprintf(out, "<body>\r\n");
  if (source_index) {
    fprintf(out, "<p style='float: right'><a href='/sanos/source/index.html'>Goto sanos source index</a></p>");
  }
  fprintf(out, "<pre>\r\n");
  
  line_num = 1;
  in_comment = 0;
  while (fgets(line, sizeof line, src)) {
    char *p = line;
    char *end = line;
    while (*end && *end != '\r' && *end != '\n') end++;
    *end = 0;
    
    if (in_comment) {
      char *comment_start = p;
      fprintf(out, "<font color='green'>");
      while (p < end) {
        if (p[0] == '*' && p[1] == '/') {
          p += 2;
          output_html(out, comment_start, p);
          in_comment = 0;
          fprintf(out, "</font>");
          break;
        }
        p++;
      }
    }

    fprintf(out, "<a name=':%d'></a>", line_num);
    
    if (!is_c) {
      output_html(out, p, end);
      p = end;
    }

    while (p < end) {
      if (p[0] == '/' && p[1] == '/') {
        fprintf(out, "<font color='green'>");
        output_html(out, p, end);
        fprintf(out, "</font>");
        p = end;
      } else if (p[0] == '/' && p[1] == '*') {
        char *comment_start = p;
        fprintf(out, "<font color='green'>");
        while (p < end) {
          if (p[0] == '*' && p[1] == '/') {
            p += 2;
            output_html(out, comment_start, p);
            in_comment = 0;
            fprintf(out, "</font>");
            break;
          }
          p++;
        }
      } else if (*p == '\'' || *p == '"') {
        char *start = p++;
        while (*p && *p != *start) {
          if (*p == '\\' && *(p + 1)) p++;
          p++;
        }
        if (*p) p++;
        fprintf(out, "<font color='brown'>");
        output_html(out, start, p);
        fprintf(out, "</font>");
      } else if (*p == '#' || *p == '_' || isalpha(*p)) {
        char *start = p++;
        while (*p && (*p == '_' || isalnum(*p))) p++;
        memcpy(token, start, p - start);
        token[p - start] = 0;
        if (is_keyword(token)) {
          fprintf(out, "<font color='blue'>");
          output_html(out, start, p);
          fprintf(out, "</font>");
          
          if (strncmp(start, "#include", 8) == 0) {
            start = p;
            while (isspace(*p)) p++;
            output_html(out, start, p);
            
            if (*p == '"' || *p == '<') {
              int stdincl = *p == '<';
              output_html(out, p, p + 1);
              start = ++p;
              while (*p && *p != '>' && *p != '"') p++;
              if (stdincl) {
                char *base;
                
                strcpy(filename, include_dir);
                strcat(filename, "/");
                base = filename + strlen(filename);
                memcpy(base, start, p - start);
                base[p - start] = 0;
              } else {
                int pathlen = base_filename - relative_filename;
                int fnlen = p - start;
                memcpy(filename, relative_filename, pathlen);
                memcpy(filename + pathlen, start, fnlen);
                filename[pathlen + fnlen] = 0;
              }
              relative_url(relative_filename, filename, url);
              fprintf(out, "<a href='%s.html'>", url);
              output_html(out, start, p);
              fprintf(out, "</a>");
              if (*p) {
                output_html(out, p, p + 1);
                p++;
              }
            }
          }
        } else {
          struct tag *tag = find_tag(token, relative_filename);
          if (tag) {
            int self;
            
            relative_url(relative_filename, tag->file, url);
            self = strcmp(url, base_filename) == 0 && tag->line == line_num;
            if (!self) fprintf(out, "<a href='%s.html#:%d'>", url, tag->line);
            output_html(out, start, p);
            if (!self) fprintf(out, "</a>");
          } else {
            output_html(out, start, p);
          }
        }
      } else {
        output_html(out, p, p + 1);
        p++;
      }
    }
    if (in_comment) fprintf(out, "</font>");
    fprintf(out, "\r\n", line);
    line_num++;
  }
  
  fprintf(out, "</pre>\r\n");
  fprintf(out, "</body>\r\n");
  fprintf(out, "</html>\r\n");

  fclose(src);
  fclose(out);
}
Beispiel #12
0
void
TIFFInput::readspec ()
{
    uint32 width = 0, height = 0, depth = 0;
    unsigned short nchans = 1;
    TIFFGetField (m_tif, TIFFTAG_IMAGEWIDTH, &width);
    TIFFGetField (m_tif, TIFFTAG_IMAGELENGTH, &height);
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_IMAGEDEPTH, &depth);
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_SAMPLESPERPIXEL, &nchans);

    m_spec = ImageSpec ((int)width, (int)height, (int)nchans);

    float x = 0, y = 0;
    TIFFGetField (m_tif, TIFFTAG_XPOSITION, &x);
    TIFFGetField (m_tif, TIFFTAG_YPOSITION, &y);
    m_spec.x = (int)x;
    m_spec.y = (int)y;
    m_spec.z = 0;
    // FIXME? - TIFF spec describes the positions as in resolutionunit.
    // What happens if this is not unitless pixels?  Are we interpreting
    // it all wrong?

    if (TIFFGetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLWIDTH, &width) == 1
          && width > 0)
        m_spec.full_width = width;
    if (TIFFGetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLLENGTH, &height) == 1
          && height > 0)
        m_spec.full_height = height;

    if (TIFFIsTiled (m_tif)) {
        TIFFGetField (m_tif, TIFFTAG_TILEWIDTH, &m_spec.tile_width);
        TIFFGetField (m_tif, TIFFTAG_TILELENGTH, &m_spec.tile_height);
        TIFFGetFieldDefaulted (m_tif, TIFFTAG_TILEDEPTH, &m_spec.tile_depth);
    } else {
        m_spec.tile_width = 0;
        m_spec.tile_height = 0;
        m_spec.tile_depth = 0;
    }

    m_bitspersample = 8;
    TIFFGetField (m_tif, TIFFTAG_BITSPERSAMPLE, &m_bitspersample);
    m_spec.attribute ("oiio:BitsPerSample", (int)m_bitspersample);

    unsigned short sampleformat = SAMPLEFORMAT_UINT;
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_SAMPLEFORMAT, &sampleformat);
    switch (m_bitspersample) {
    case 1:
    case 2:
    case 4:
        // Make 1, 2, 4 bpp look like byte images
    case 8:
        if (sampleformat == SAMPLEFORMAT_UINT)
            m_spec.set_format (TypeDesc::UINT8);
        else if (sampleformat == SAMPLEFORMAT_INT)
            m_spec.set_format (TypeDesc::INT8);
        else m_spec.set_format (TypeDesc::UINT8);  // punt
        break;
    case 16:
        if (sampleformat == SAMPLEFORMAT_UINT)
            m_spec.set_format (TypeDesc::UINT16);
        else if (sampleformat == SAMPLEFORMAT_INT)
            m_spec.set_format (TypeDesc::INT16);
        break;
    case 32:
        if (sampleformat == SAMPLEFORMAT_IEEEFP)
            m_spec.set_format (TypeDesc::FLOAT);
        break;
    case 64:
        if (sampleformat == SAMPLEFORMAT_IEEEFP)
            m_spec.set_format (TypeDesc::DOUBLE);
        break;
    default:
        m_spec.set_format (TypeDesc::UNKNOWN);
        break;
    }

    // Use the table for all the obvious things that can be mindlessly
    // shoved into the image spec.
    for (int i = 0;  tiff_tag_table[i].name;  ++i)
        find_tag (tiff_tag_table[i].tifftag,
                  tiff_tag_table[i].tifftype, tiff_tag_table[i].name);

    // Now we need to get fields "by hand" for anything else that is less
    // straightforward...

    m_photometric = (m_spec.nchannels == 1 ? PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB);
    TIFFGetField (m_tif, TIFFTAG_PHOTOMETRIC, &m_photometric);
    m_spec.attribute ("tiff:PhotometricInterpretation", (int)m_photometric);
    if (m_photometric == PHOTOMETRIC_PALETTE) {
        // Read the color map
        unsigned short *r = NULL, *g = NULL, *b = NULL;
        TIFFGetField (m_tif, TIFFTAG_COLORMAP, &r, &g, &b);
        ASSERT (r != NULL && g != NULL && b != NULL);
        m_colormap.clear ();
        m_colormap.insert (m_colormap.end(), r, r + (1 << m_bitspersample));
        m_colormap.insert (m_colormap.end(), g, g + (1 << m_bitspersample));
        m_colormap.insert (m_colormap.end(), b, b + (1 << m_bitspersample));
        // Palette TIFF images are always 3 channels (to the client)
        m_spec.nchannels = 3;
        m_spec.default_channel_names ();
    }

    TIFFGetFieldDefaulted (m_tif, TIFFTAG_PLANARCONFIG, &m_planarconfig);
    m_spec.attribute ("tiff:PlanarConfiguration", (int)m_planarconfig);
    if (m_planarconfig == PLANARCONFIG_SEPARATE)
        m_spec.attribute ("planarconfig", "separate");
    else
        m_spec.attribute ("planarconfig", "contig");

    int compress = 0;
    TIFFGetFieldDefaulted (m_tif, TIFFTAG_COMPRESSION, &compress);
    m_spec.attribute ("tiff:Compression", compress);
    switch (compress) {
    case COMPRESSION_NONE :
        m_spec.attribute ("compression", "none");
        break;
    case COMPRESSION_LZW :
        m_spec.attribute ("compression", "lzw");
        break;
    case COMPRESSION_CCITTRLE :
        m_spec.attribute ("compression", "ccittrle");
        break;
    case COMPRESSION_DEFLATE :
    case COMPRESSION_ADOBE_DEFLATE :
        m_spec.attribute ("compression", "zip");
        break;
    case COMPRESSION_PACKBITS :
        m_spec.attribute ("compression", "packbits");
        break;
    default:
        break;
    }

    int rowsperstrip = -1;
    if (! m_spec.tile_width) {
        TIFFGetField (m_tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
        if (rowsperstrip > 0)
            m_spec.attribute ("tiff:RowsPerStrip", rowsperstrip);
    }

    // The libtiff docs say that only uncompressed images, or those with
    // rowsperstrip==1, support random access to scanlines.
    m_no_random_access = (compress != COMPRESSION_NONE && rowsperstrip != 1);

    short resunit = -1;
    TIFFGetField (m_tif, TIFFTAG_RESOLUTIONUNIT, &resunit);
    switch (resunit) {
    case RESUNIT_NONE : m_spec.attribute ("ResolutionUnit", "none"); break;
    case RESUNIT_INCH : m_spec.attribute ("ResolutionUnit", "in"); break;
    case RESUNIT_CENTIMETER : m_spec.attribute ("ResolutionUnit", "cm"); break;
    }

    get_matrix_attribute ("worldtocamera", TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA);
    get_matrix_attribute ("worldtoscreen", TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN);
    get_int_attribute ("tiff:subfiletype", TIFFTAG_SUBFILETYPE);
    // FIXME -- should subfiletype be "conventionized" and used for all
    // plugins uniformly? 

    // FIXME: do we care about fillorder for 1-bit and 4-bit images?

    // Special names for shadow maps
    char *s = NULL;
    TIFFGetField (m_tif, TIFFTAG_PIXAR_TEXTUREFORMAT, &s);
    if (s)
        m_emulate_mipmap = true;
    if (s && ! strcmp (s, "Shadow")) {
        for (int c = 0;  c < m_spec.nchannels;  ++c)
            m_spec.channelnames[c] = "z";
    }

    // N.B. we currently ignore the following TIFF fields:
    // ExtraSamples
    // GrayResponseCurve GrayResponseUnit
    // MaxSampleValue MinSampleValue
    // NewSubfileType SubfileType(deprecated)
    // Colorimetry fields

    // Search for an EXIF IFD in the TIFF file, and if found, rummage 
    // around for Exif fields.
#if TIFFLIB_VERSION > 20050912    /* compat with old TIFF libs - skip Exif */
    int exifoffset = 0;
    if (TIFFGetField (m_tif, TIFFTAG_EXIFIFD, &exifoffset) &&
            TIFFReadEXIFDirectory (m_tif, exifoffset)) {
        for (int i = 0;  exif_tag_table[i].name;  ++i)
            find_tag (exif_tag_table[i].tifftag, exif_tag_table[i].tifftype,
                      exif_tag_table[i].name);
        // I'm not sure what state TIFFReadEXIFDirectory leaves us.
        // So to be safe, close and re-seek.
        TIFFClose (m_tif);
        m_tif = TIFFOpen (m_filename.c_str(), "rm");
        TIFFSetDirectory (m_tif, m_subimage);

        // A few tidbits to look for
        ImageIOParameter *p;
        if ((p = m_spec.find_attribute ("Exif:ColorSpace", TypeDesc::INT))) {
            // Exif spec says that anything other than 0xffff==uncalibrated
            // should be interpreted to be sRGB.
            if (*(const int *)p->data() != 0xffff)
                m_spec.attribute ("oiio::ColorSpace", "sRGB");
        }
    }
#endif

#if TIFFLIB_VERSION >= 20051230
    // Search for IPTC metadata in IIM form -- but older versions of
    // libtiff botch the size, so ignore it for very old libtiff.
    int iptcsize = 0;
    const void *iptcdata = NULL;
    if (TIFFGetField (m_tif, TIFFTAG_RICHTIFFIPTC, &iptcsize, &iptcdata)) {
        std::vector<uint32> iptc ((uint32 *)iptcdata, (uint32 *)iptcdata+iptcsize);
        if (TIFFIsByteSwapped (m_tif))
            TIFFSwabArrayOfLong ((uint32*)&iptc[0], iptcsize);
        decode_iptc_iim (&iptc[0], iptcsize*4, m_spec);
    }
#endif

    // Search for an XML packet containing XMP (IPTC, Exif, etc.)
    int xmlsize = 0;
    const void *xmldata = NULL;
    if (TIFFGetField (m_tif, TIFFTAG_XMLPACKET, &xmlsize, &xmldata)) {
        // std::cerr << "Found XML data, size " << xmlsize << "\n";
        if (xmldata && xmlsize) {
            std::string xml ((const char *)xmldata, xmlsize);
            decode_xmp (xml, m_spec);
        }
    }

#if 0
    // Experimental -- look for photoshop data
    int photoshopsize = 0;
    const void *photoshopdata = NULL;
    if (TIFFGetField (m_tif, TIFFTAG_PHOTOSHOP, &photoshopsize, &photoshopdata)) {
        std::cerr << "Found PHOTOSHOP data, size " << photoshopsize << "\n";
        if (photoshopdata && photoshopsize) {
//            std::string photoshop ((const char *)photoshopdata, photoshopsize);
//            std::cerr << "PHOTOSHOP:\n" << photoshop << "\n---\n";
        }
    }
#endif
}
Beispiel #13
0
void    scr_ga( void )
{
    char        *   p;
    char        *   pn;
    char            savetag;
    char            saveatt;
    int             k;
    int             len;
    condcode        cc;
    gaflags         att_flags;
    gavalflags      val_flags;
    gavalentry  *   gaval;
    gaentry     *   gawk;


    savetag = ' ';
    saveatt = ' ';
    att_flags = 0;
    val_flags = 0;
    garginit();                         // find end of CW

    cc = getarg();                      // Tagname or *

    if( cc == omit || (*tok_start == '*' && tag_entry == NULL) ) {
        // no operands or tagname * and no previous definition
        tag_name_missing_err();
    }
    if( tag_entry == NULL ) {           // error during previous .gt

        scan_restart = scan_stop + 1;   // ignore .ga
        return;
    }


    /***********************************************************************/
    /*  isolate tagname  use previous if tagname *                         */
    /***********************************************************************/

    p = tok_start;

    if( *p == '*' ) {                   // single * as tagname
        if( arg_flen > 1 ) {
            xx_err( err_tag_name_inv );
            return;
        }
        savetag = '*';                  // remember for possible quick access
        if( GlobalFlags.firstpass && input_cbs->fmflags & II_research ) {
            out_msg("  using tagname %s\n", tagname );
        }
    } else {
        savetag = ' ';                  // no quick access

        init_tag_att();            // forget previous values for quick access

        pn      = tagname;
        len     = 0;

        while( *p && is_macro_char( *p ) ) {
            if( len < TAG_NAME_LENGTH ) {
                *pn++ = tolower( *p++ );// copy lowercase tagname
                *pn   = '\0';
            } else {
                break;
            }
            len++;
        }
        for( k = len; k < TAG_NAME_LENGTH; k++ ) {
            tagname[k] = '\0';
        }
        tagname[TAG_NAME_LENGTH] = '\0';

        if( len < arg_flen ) {
            xx_err( err_tag_name_inv );// name contains invalid or too many chars
            return;
        }
        tag_entry = find_tag( &tag_dict, tagname );
        if( tag_entry == NULL ) {
            nottag_err();               // tagname not defined
            return;
        }
    }

    /***********************************************************************/
    /* isolate attname  use previous if attname *                          */
    /***********************************************************************/

    cc = getarg();                      // Attribute  name or *

    if( cc == omit || (*tok_start == '*' && att_entry == NULL) ) {
        // no operands or attname * and no previous definition
        xx_err( err_att_name_inv );
        return;
    }

    p = tok_start;

    if( *p == '*' ) {                   // single * as attname
        if( arg_flen > 1 ) {
            xx_err( err_att_name_inv );
            return;
        }
        saveatt = '*';                  // remember for possible quick access
        if( GlobalFlags.firstpass && input_cbs->fmflags & II_research ) {
            out_msg("  using attname %s\n", attname );
        }
        att_flags = att_entry->attflags;
    } else {
        saveatt = ' ';                  // no quick access
        att_entry = NULL;
        pn      = attname;
        len     = 0;

        while( *p && is_macro_char( *p ) ) {
            if( len < ATT_NAME_LENGTH ) {
                *pn++ = tolower( *p++ );// copy lowercase tagname
                *pn   = '\0';
            } else {
                break;
            }
            len++;
        }
        for( k = len; k < ATT_NAME_LENGTH; k++ ) {
            attname[k] = '\0';
        }
        attname[ATT_NAME_LENGTH] = '\0';

        if( len < arg_flen ) {
            xx_err( err_att_name_inv );// attname with invalid or too many chars
            cc = neg;
            return;
        }
    }


    /***********************************************************************/
    /*   process options A and options B                                   */
    /***********************************************************************/

    if( cc != omit ) {
        if( saveatt != '*' ) {          // no quickaccess for attribute
            gawk = NULL;
            for( gawk = tag_entry->attribs; gawk != NULL;
                 gawk = gawk->next ) {

                if( !stricmp( attname, gawk->name ) ) {
                    att_flags = gawk->attflags; // get possible uppercase option
                    break;
                }
            }
        } else {
            att_flags = att_entry->attflags;
        }
        cc = scan_att_optionsA( &att_flags );   // process options A

        if( cc != omit ) {

            cc = scan_att_optionsB( &val_flags, cc, &att_flags );// process option B
            if( cc != omit ) {
                xx_err( err_tag_toomany );  // excess parameters
                return;
            }
        }
    }

    /***********************************************************************/
    /*  scanning complete     add/modify attribute in dictionary           */
    /***********************************************************************/
    if( saveatt != '*' ) {              // no quickaccess for attribute
        for( att_entry = tag_entry->attribs; att_entry != NULL;
             att_entry = att_entry->next ) {

            if( !stricmp( attname, att_entry->name ) ) {
                break;
            }
        }
    }
    if( att_entry == NULL ) {           // new attribute
        att_entry = mem_alloc( sizeof( gaentry ) );

        att_entry->next = tag_entry->attribs;
        tag_entry->attribs = att_entry;

        att_entry->vals = NULL;
        att_entry->attflags = att_flags;
        strcpy( att_entry->name, attname );
    } else {
        att_entry->attflags = att_flags;// update flags
    }

    gaval = mem_alloc( sizeof (gavalentry ) );

    if( att_entry->vals == NULL ) {
        att_entry->vals = gaval;
    } else {
        gavalentry  *   valwk;

        for( valwk = att_entry->vals;  valwk != NULL;
                                       valwk = valwk->next ) {
            if( valwk->next == NULL ) {
                break;                      // last entry found
            }
        }
        valwk->next = gaval;
    }
    gaval->next = NULL;

    gaval->valflags = val_flags;
    if( val_flags & val_length ) {
        gaval->a.length = ranges[0];
    } else if( val_flags & val_range ) {
        for( k = 0; k < 4; k++ ) {
            gaval->a.range[k] = ranges[k];
        }
    } else if( val_flags & val_value ) {
        strcpy_s( gaval->a.value, sizeof( gaval->a.value ), stringval );
    } else if( val_flags & val_valptr ) {
        gaval->a.valptr = valptr;
    }
    scan_restart = scan_stop + 1;
    return;
}
Beispiel #14
0
Vector2D VisualToolBase::GetLineOrigin(AssDialogue *diag) {
	auto blocks = diag->ParseTags();
	return vec_or_bad(find_tag(blocks, "\\org"), 0, 1);
}
Beispiel #15
0
symbol_t *
find_enum (symbol_t *tag)
{
	return find_tag (ty_enum, tag, 0);
}