示例#1
0
/*
  this function will be called upon a scheduled data collection 
  for a specific rule. it has to write measurement values from 
  'flowdata' into 'buf' and set len accordingly
*/
int exportData( void **exp, int *len, void *flowdata )
{
    uint32_t i;
    packetData_t *pkt;
    flowRec_t *data = (flowRec_t *) flowdata;

    /* check if enough buffer space is available and reserve extra memory if not */
    if (expSize < ROWSTRSIZE * (data->nrows + 1)) {
        uint8_t *newMemory = realloc(expData, ROWSTRSIZE * (data->nrows + 1));
	if (newMemory != NULL) {
	    expData = newMemory;
	    expSize = ROWSTRSIZE * data->nrows;
	} else {
	    /* not enough memory to write data to -> don't write data at all */
	    STARTEXPORT(expData);
	    ADD_LIST(0);
	    END_LIST();
	    ENDEXPORT(exp, len);
	    return -1;
	}
    }


    STARTEXPORT(expData);
    ADD_LIST( data->nrows );

    pkt = data->pkt;

    for (i = 0; i < data->nrows; i++) {

	ADD_UINT8(  pkt->ipversion );
	ADD_UINT8(  pkt->ttl );
	ADD_UINT16( pkt->pktlen );
	ADD_UINT16( pkt->iphdrlen );
	
	ADD_UINT16( pkt->proto );
	ADD_UINT16( pkt->tcpudphdrlen );
	
	ADD_STRING( pkt->srcip );
	ADD_UINT16( pkt->srcport );
	
	ADD_STRING( pkt->dstip );
	ADD_UINT16( pkt->dstport );

	ADD_UINT32( pkt->tcpseqno );
	ADD_STRING( printFlags(pkt->tcpflags) );

	pkt++;
    }

    END_LIST();
    ENDEXPORT(exp, len);

    data->nrows = 0;
    
    return 0;
}
示例#2
0
	/**@brief Once all options have been looked for call finishSetUp() so that any
	 *warnings or help messages can be print and to find out if set up was
	 *successful
	 * @param out The std::ostream out object to print to
	 *
	 */
	void finishSetUp(std::ostream &out = std::cout) {
		if (commands_.printingHelp() || commands_.gettingFlags() ) {
			printFlags(out);
			exit(1);
		}
		lookForInvalidOptionsDashInsens();
		printWarnings(out);
		if (failed_) {
			exit(1);
		}
	}
示例#3
0
	/**@brief Once all options have been looked for call finishSetUp() so that any
	 *warnings or help messages can be print and to find out if set up was
	 *successful
	 * @param out The std::ostream out object to print to
	 *
	 */
	void finishSetUp(std::ostream &out) {
		if (commands_.containsFlagCaseInsensitive("-getFlags")
				|| commands_.containsFlagCaseInsensitive("-flags")
				|| commands_.containsFlagCaseInsensitive("-h")
				|| commands_.containsFlagCaseInsensitive("-help")) {
			printFlags(out);
			exit(1);
		}
		lookForInvalidOptions();
		printWarnings(out);
		if (failed_) {
			exit(1);
		}
	}
示例#4
0
文件: sig_default.c 项目: jsvisa/apue
int main(int argc, char **argv)
{
    char buf[100];
    ssize_t ret;
    struct sigaction  oldact;


    if ( signal(SIGINT, int_handler) == SIG_ERR ){
        printf("sigaction failed!\n");
        return -1;
    }
     if ( signal(SIGUSR1, int_handler) == SIG_ERR ){
        printf("sigaction failed!\n");
        return -1;
    }
    
    bzero( &oldact, sizeof(oldact));
    sigemptyset(&oldact.sa_mask);
    if ( -1 ==  sigaction(SIGINT, NULL,&oldact) ){
        printf("sigaction failed!\n");
        return -1;
    }

    printMask(oldact.sa_mask);
    printFlags(oldact.sa_flags);
	//检测SIGUSR1
    if ( -1 ==  sigaction(SIGUSR1, NULL,&oldact) ){
        printf("sigaction failed!\n");
        return -1;
    }

    printMask(oldact.sa_mask);
    printFlags(oldact.sa_flags);


    return 0;
}
示例#5
0
void printResourceList() {
    // print version and citation info
    fprintf(stdout, "BEAGLE version %s\n", beagleGetVersion());
    fprintf(stdout, "%s\n", beagleGetCitation());     

    // print resource list
    BeagleResourceList* rList;
    rList = beagleGetResourceList();
    fprintf(stdout, "Available resources:\n");
    for (int i = 0; i < rList->length; i++) {
        fprintf(stdout, "\tResource %i:\n\t\tName : %s\n", i, rList->list[i].name);
        fprintf(stdout, "\t\tDesc : %s\n", rList->list[i].description);
        fprintf(stdout, "\t\tFlags:");
        printFlags(rList->list[i].supportFlags);
        fprintf(stdout, "\n");
    }    
    fprintf(stdout, "\n");
    std::exit(0);
}
示例#6
0
int main( int argc, const char* argv[] )
{
    // print resource list
    BeagleResourceList* rList;
    rList = beagleGetResourceList();
    fprintf(stdout, "Available resources:\n");
    for (int i = 0; i < rList->length; i++) {
        fprintf(stdout, "\tResource %i:\n\t\tName : %s\n", i, rList->list[i].name);
        fprintf(stdout, "\t\tDesc : %s\n", rList->list[i].description);
        fprintf(stdout, "\t\tFlags:");
        printFlags(rList->list[i].supportFlags);
        fprintf(stdout, "\n");
    }    
    fprintf(stdout, "\n");    
    
    bool manualScaling = false;
    bool autoScaling = false;
	bool gRates = false; // generalized rate categories, separate root buffers
    
    // is nucleotides...
    int stateCount = 4;
	
    // get the number of site patterns
	int nPatterns = strlen(human);
    
    int rateCategoryCount = 4;
	
	int nRateCats = (gRates ? 1 : rateCategoryCount);
	int nRootCount = (!gRates ? 1 : rateCategoryCount);
	int nPartBuffs = 4 + nRootCount;
    int scaleCount = (manualScaling ? 2 + nRootCount : 0);
    
    // initialize the instance
    BeagleInstanceDetails instDetails;
    
    // create an instance of the BEAGLE library
	int instance = beagleCreateInstance(
                                  3,				/**< Number of tip data elements (input) */
                                  nPartBuffs,       /**< Number of partials buffers to create (input) */
                                  0,		        /**< Number of compact state representation buffers to create (input) */
                                  stateCount,		/**< Number of states in the continuous-time Markov chain (input) */
                                  nPatterns,		/**< Number of site patterns to be handled by the instance (input) */
                                  1,		        /**< Number of rate matrix eigen-decomposition buffers to allocate (input) */
                                  4,		        /**< Number of rate matrix buffers (input) */
								  nRateCats,		/**< Number of rate categories (input) */
                                  scaleCount,       /**< Number of scaling buffers */
                                  NULL,			    /**< List of potential resource on which this instance is allowed (input, NULL implies no restriction */
                                  0,			    /**< Length of resourceList list (input) */
                                  BEAGLE_FLAG_PRECISION_DOUBLE | BEAGLE_FLAG_PROCESSOR_GPU | (autoScaling ? BEAGLE_FLAG_SCALING_AUTO : 0),	/**< Bit-flags indicating preferred implementation charactertistics, see BeagleFlags (input) */
                                  0,                /**< Bit-flags indicating required implementation characteristics, see BeagleFlags (input) */
                                  &instDetails);
    if (instance < 0) {
	    fprintf(stderr, "Failed to obtain BEAGLE instance\n\n");
	    exit(1);
    }
        
    int rNumber = instDetails.resourceNumber;
    fprintf(stdout, "Using resource %i:\n", rNumber);
    fprintf(stdout, "\tRsrc Name : %s\n",instDetails.resourceName);
    fprintf(stdout, "\tImpl Name : %s\n", instDetails.implName);
    fprintf(stdout, "\tImpl Desc : %s\n", instDetails.implDescription);
    fprintf(stdout, "\tFlags:");
    printFlags(instDetails.flags);
    fprintf(stdout, "\n\n");
    
    if (!(instDetails.flags & BEAGLE_FLAG_SCALING_AUTO))
        autoScaling = false;
    
//    beagleSetTipStates(instance, 0, getStates(human));
//    beagleSetTipStates(instance, 1, getStates(chimp));
//    beagleSetTipStates(instance, 2, getStates(gorilla));
    
    // set the sequences for each tip using partial likelihood arrays
    double *humanPartials   = getPartials(human);
    double *chimpPartials   = getPartials(chimp);
    double *gorillaPartials = getPartials(gorilla);
    
	beagleSetTipPartials(instance, 0, humanPartials);
	beagleSetTipPartials(instance, 1, chimpPartials);
	beagleSetTipPartials(instance, 2, gorillaPartials);
    
//#ifdef _WIN32
//	std::vector<double> rates(rateCategoryCount);
//#else
//	double rates[rateCategoryCount];
//#endif
//    for (int i = 0; i < rateCategoryCount; i++) {
//        rates[i] = 1.0;
//    }
	double rates[4] = { 0.03338775, 0.25191592, 0.82026848, 2.89442785 };
    
	
    // create base frequency array
	double freqs[16] = { 0.25, 0.25, 0.25, 0.25,
						 0.25, 0.25, 0.25, 0.25,
						 0.25, 0.25, 0.25, 0.25,
		                 0.25, 0.25, 0.25, 0.25 };
    
    // create an array containing site category weights

	double* weights = (double*) malloc(sizeof(double) * rateCategoryCount);

    for (int i = 0; i < rateCategoryCount; i++) {
        weights[i] = 1.0/rateCategoryCount;
    }    

	double* patternWeights = (double*) malloc(sizeof(double) * nPatterns);
    
    for (int i = 0; i < nPatterns; i++) {
        patternWeights[i] = 1.0;
    }    
    
    
	// an eigen decomposition for the JC69 model
	double evec[4 * 4] = {
        1.0,  2.0,  0.0,  0.5,
        1.0,  -2.0,  0.5,  0.0,
        1.0,  2.0, 0.0,  -0.5,
        1.0,  -2.0,  -0.5,  0.0
	};
    
	double ivec[4 * 4] = {
        0.25,  0.25,  0.25,  0.25,
        0.125,  -0.125,  0.125,  -0.125,
        0.0,  1.0,  0.0,  -1.0,
        1.0,  0.0,  -1.0,  0.0
	};
    
	double eval[4] = { 0.0, -1.3333333333333333, -1.3333333333333333, -1.3333333333333333 };
    
    // set the Eigen decomposition
	beagleSetEigenDecomposition(instance, 0, evec, ivec, eval);
    
    beagleSetStateFrequencies(instance, 0, freqs);
    
    beagleSetCategoryWeights(instance, 0, weights);
    
    beagleSetPatternWeights(instance, patternWeights);
    
    // a list of indices and edge lengths
	int nodeIndices[4] = { 0, 1, 2, 3 };
	double edgeLengths[4] = { 0.1, 0.1, 0.2, 0.1 };
	
	int* rootIndices = (int*) malloc(sizeof(int) * nRootCount);
    int* categoryWeightsIndices = (int*) malloc(sizeof(int) * nRootCount);
    int* stateFrequencyIndices = (int*) malloc(sizeof(int) * nRootCount);
	int* cumulativeScalingIndices = (int*) malloc(sizeof(int) * nRootCount);
	
	for (int i = 0; i < nRootCount; i++) {
		
		rootIndices[i] = 4 + i;
        categoryWeightsIndices[i] = 0;
        stateFrequencyIndices[i] = 0;
		cumulativeScalingIndices[i] = (manualScaling ? 2 + i : BEAGLE_OP_NONE);
		
		beagleSetCategoryRates(instance, &rates[i]);
		
		// tell BEAGLE to populate the transition matrices for the above edge lengths
		beagleUpdateTransitionMatrices(instance,     // instance
								 0,             // eigenIndex
								 nodeIndices,   // probabilityIndices
								 NULL,          // firstDerivativeIndices
								 NULL,          // secondDerivativeIndices
								 edgeLengths,   // edgeLengths
								 4);            // count
		
		// create a list of partial likelihood update operations
		// the order is [dest, destScaling, source1, matrix1, source2, matrix2]
		BeagleOperation operations[2] = {
			3, (manualScaling ? 0 : BEAGLE_OP_NONE), BEAGLE_OP_NONE, 0, 0, 1, 1,
			rootIndices[i], (manualScaling ? 1 : BEAGLE_OP_NONE), BEAGLE_OP_NONE, 2, 2, 3, 3
		};
		
		if (manualScaling)
			beagleResetScaleFactors(instance, cumulativeScalingIndices[i]);
		
		// update the partials
		beagleUpdatePartials(instance,      // instance
					   operations,     // eigenIndex
					   2,              // operationCount
					   cumulativeScalingIndices[i]);// cumulative scaling index
	}
		 
    if (autoScaling) {
        int scaleIndices[2] = {3, 4};
        beagleAccumulateScaleFactors(instance, scaleIndices, 2, BEAGLE_OP_NONE);
    }
    
	double *patternLogLik = (double*)malloc(sizeof(double) * nPatterns);
	double logL = 0.0;    
    int returnCode = 0;
    
    // calculate the site likelihoods at the root node
	returnCode = beagleCalculateRootLogLikelihoods(instance,               // instance
	                            (const int *)rootIndices,// bufferIndices
	                            (const int *)categoryWeightsIndices,                // weights
	                            (const int *)stateFrequencyIndices,                  // stateFrequencies
								cumulativeScalingIndices,// cumulative scaling index
	                            nRootCount,                      // count
	                            &logL);         // outLogLikelihoods
    
    if (returnCode < 0) {
	    fprintf(stderr, "Failed to calculate root likelihood\n\n");
    } else {

        beagleGetSiteLogLikelihoods(instance, patternLogLik);
        double sumLogL = 0.0;
        for (int i = 0; i < nPatterns; i++) {
            sumLogL += patternLogLik[i] * patternWeights[i];
//            std::cerr << "site lnL[" << i << "] = " << patternLogLik[i] << '\n';
        }
      
        fprintf(stdout, "logL = %.5f (PAUP logL = -1498.89812)\n", logL);
        fprintf(stdout, "sumLogL = %.5f\n", sumLogL);  
    }
    
// no rate heterogeneity:	
//	fprintf(stdout, "logL = %.5f (PAUP logL = -1574.63623)\n\n", logL);
	
    free(weights);
    free(patternWeights);    
    free(rootIndices);
    free(categoryWeightsIndices);
    free(stateFrequencyIndices);
    free(cumulativeScalingIndices);    
    
	free(patternLogLik);
	free(humanPartials);
	free(chimpPartials);
	free(gorillaPartials);
    
    beagleFinalizeInstance(instance);

#ifdef _WIN32
    std::cout << "\nPress ENTER to exit...\n";
    fflush( stdout);
    fflush( stderr);
    getchar();
#endif
    
}
示例#7
0
int main(int argc, char *argv[])
{
  //int ret;
  int c;
  unsigned short i=0, ac;
  unsigned short rom_adr, startAdr=i8086_BEGINADR;  /* Mem-Viewer Startadresse  */
  char str[6];
  char cfgStr[i8086_CFG_MAX_VALUE_LEN];
  unsigned short adr;
  codeView cv;                             /* Code-Viewer Data */

  if (argc<2)
  {
                    printf("i8086emu "VERSION_NUMBER);
                    printf("\nUsage: %s [OPTIONS] FILENAME\n", argv[0]);
                    printf("\nOptions:");
                    printf("\n -c\t\t\tCodeViewer deaktivieren");
                    printf("\n -o XXXXh\t\tStartadresse");
                    printf("\n -r XXXXh\t\tStartadresse ROM-File");
                    printf("\n -d file\t\tDUMP-File");
                    printf("\n --version\t\tshow version information");
                    printf("\n --help\t\t\tthis help information");
                    printf("\n");

    exit(1);
  }
  
  
  signal(SIGTERM, resetAll);
  signal(SIGINT, resetAll);
  signal(SIGQUIT, resetAll);
  signal(SIGSEGV, resetAll);
  
  i8086clearLog(); /* Log-File leeren. */
  i8086init(); /* Prozessor initialisieren. */
  oldPortHandler = i8086SetMsgFunc(i8086_SIG_PORT_OUT, portSignalHandler);

  /* Config-File laden */
  if (i8086ReadStrConfig(cfgStr, CONFIG_FILE, "ROMFILE")!=0)
  {
    rom_adr = i8086ReadHexConfig(CONFIG_FILE, "ROMSTARTADR", 0xc000);
    LoadRomFile(cfgStr, rom_adr);
  }
  else /* Wenn ROM -> kein Core-Dump */
    if (i8086ReadStrConfig(cfgStr, CONFIG_FILE, "COREDUMP")!=0)
      LoadCoreDumpFile(cfgStr);
  startAdr = i8086ReadHexConfig(CONFIG_FILE, "PROGSTARTADR", 0x0100);
    
  for (ac=1; ac<argc; ac++) /* Programmargumente auswerten und speichern */
  {
    char *str;
    
    if(strcmp(argv[ac],"--version")==0)
    {
                    printf("i8086emu "VERSION_NUMBER"\n"
                    "Copyright (C) 2004 JMH, RD, FB, CST\n"
                    "i8086emu comes with NO WARRANTY,\n"
                    "to the extent permitted by law.\n"
                    "You may redistribute copies of i8086emu\n"
                    "under the terms of the GNU General Public License.\n");
                    exit(1);
    }
    if(strcmp(argv[ac],"--help")==0)
    {
                    printf("i8086emu "VERSION_NUMBER);
                    printf("\nUsage: %s [OPTIONS] FILENAME\n", argv[0]);
                    printf("\nOptions:");
                    printf("\n -c\t\t\tCodeViewer deaktivieren");
                    printf("\n -o XXXXh\t\tStartadresse");
                    printf("\n -r XXXXh\t\tStartadresse ROM-File");
                    printf("\n -d file\t\tDUMP-File");
                    printf("\n --version\t\tshow version information");
                    printf("\n --help\t\t\tthis help information");
                    printf("\n");

    exit(1);
    }          
    if (strcmp(argv[ac], "-c")==0)          /* CodeViewer deaktivieren */
      args |= HIDE_CODE_VIEWER;
    if ((str=strstr(argv[ac], "-o"))!=NULL) /* Startadresse des Programmes setzen */
    {
      str = strtok(str, "-o");
      if (str!=NULL)
        startAdr = strtoul(str, NULL, 16);
    }
    if ((str=strstr(argv[ac], "-r"))!=NULL) /* ROM laden */
    {
      //int adr;
      if (argc<ac+2)
      {
        printf("\n -r XXXXh file -> Startadresse ROM-File");
        exit(1);
      }
      rom_adr = strtoul(argv[ac+1], NULL, 16);
      LoadRomFile(argv[ac+2], rom_adr);
    }
    if ((str=strstr(argv[ac], "-d"))!=NULL) /* Core-Dump laden */
    {
      if (argc<ac+1)
      {
        printf("\n -d file -> DUMP-File");
        exit(1);
      }       
      LoadCoreDumpFile(argv[ac+1]);
    }
  }

  if (i8086loadBinFile(core, argv[argc-1], startAdr)!=i8086_SUC_FILELOAD)
  {
    i8086error(argv[argc-1], i8086_ERR_STR_FILENF);    
  }
  if (args & LOAD_ROM) /* ROM verarbeiten */
    startAdr = rom_adr;
  core->pc = startAdr;
    
  initscr();
  clear();
  refresh();
  createWin();

  printReg();
  printFlags();
  printLeds(0);
  printSwitches();
  printDisplay();
  printMem(startAdr);
  cv.startAdr = 0;//i8086_BEGINADR;
  cv.endAdr = 0;

  printCode(core, commands, &cv);
  //i8086PushMsg(1, 1);

  noecho();     /* getch echo aus */
  curs_set(0);  /* Cursor ausschalten */

  keypad(stdscr,1);
  //while (/*c=='g' ||*/ (c=getch/*ar*/())!='q')

  //sendepuffer ist leer
  //core->ports.x[0xD2]=3;

  while ((c==ERR && i%50000!=0) || (c=getch/*ar*/())!='q') //automode nur aller 50000 takte abbrechbar, reicht aber aus, sonst wars zu langsam
  {
    i++;
    if (c==KEY_F(9))
      nodelay(stdscr,TRUE);
    else if (c=='n')
      nodelay(stdscr,FALSE);
    else if (c==KEY_F(8))
    {
    	adr=i8086GetSegRegister_fast(core,i8086_REG_CS, 1)+core->pc;
    	stepover=adr+commands[core->mem[adr]]->size;
	if (commands[core->mem[adr]]->hasMod!=0)
		stepover+=getAdditionalCmdLength(core, core->mem[adr], core->mem[adr+1]);
    	nodelay(stdscr,TRUE);
    }

    if (c==ERR||c=='n') /* next Opcode */
      if (i8086execCommand(core, commands)==i8086_ERR_ILGOPCODE)
      {
        sprintf(str, "%hd", core->mem[core->pc + i8086GetSegRegister_fast(core, i8086_REG_CS, 1)]);
        i8086error(i8086_ERR_STR_ILGOPCODE, str);
        //resetAll(0);
      }

    if (i8086GetSegRegister_fast(core,i8086_REG_CS, 1)+core->pc==breakpoint || i8086GetSegRegister_fast(core,i8086_REG_CS, 1)+core->pc==stepover)
    {
    	i=0;
    	nodelay(stdscr,FALSE);
	    c=0;
    }

    if (c=='r') /* set Registervalue */
      setReg();
    else if (c==KEY_F(1)) /* Print Help */
      printHelp();
    else if (c==KEY_F(2)) //Breakpoint setzen
      {
      	setBreakpoint();
	c=0;
      }
    else if (c=='m') /* Anfangsadresse von Speicherviewer setzen */
      startAdr=readMem();
    else if (c=='w') /* Wert von Speicherzelle setzen */
      setMem();
    else if (c==KEY_F(3)) /* CoreDump */
      coreDump();
    else if ((c>='0')&&(c<='7')) /* Schalter An/Aus */
    {
      unsigned char dual[] = {1,2,4,8,16,32,64,128};
      core->ports.x[0] = core->ports.x[0] ^ dual[atoi((char*)&c)];
    }
    else if (c==KEY_F(12))	//Reset Taste
    {
    	i=0;
    	core->pc=0x0c000;
	i8086SetSegRegister(core,i8086_REG_CS,0xc00);
	i8086SetRegister(core,i8086_REG_AX,1,0);
	//i8086SetRegister(core,i8086_REG_BX,1,0);
	//i8086SetRegister(core,i8086_REG_CX,1,0);
	//i8086SetRegister(core,i8086_REG_DX,1,0);
	//nodelay(stdscr,TRUE);
    }

    handleKeyboard(core,c);

    if (c!=ERR)
    {
      printReg();
      printFlags();
      printSwitches();
      printDisplay();
      printMem(startAdr);
      printCode(core, commands, &cv);
    //printLeds();
    }
  }

  resetAll(0);

  return EXIT_SUCCESS;
}
示例#8
0
int processPacket( char *packet, metaData_t *meta, void *flowdata )
{
    /*fprintf(stderr, "dummy : processPacket (l = %d)\n", meta->len);*/

    uint8_t  *pos;
    packetData_t *pkt;

#ifdef DEBUG2
    fprintf(stderr, "show_ascii::processPacket (l = %d)\n" 
	    "frame type = 0x%04x / offs[0 1 2 3] = %d %d %d %d\n", 
	    meta->len, ntohs(((uint16_t *)packet)[6]),
	    meta->offs[L_LINK], meta->offs[L_NET], 
	    meta->offs[L_TRANS], meta->offs[L_DATA]);
#endif

    /* get a storage location (data row) for the packet attributes */
    if ((pkt = fetchRow(flowdata)) == NULL) {
	return -1;
    }
    
    switch(meta->layers[L_NET]) {

    case N_IP:  /* IPv4 */
	{
	/* map IPv4 header structure onto packet in memory */
	struct iphdr *iphdr = (struct iphdr*) (packet + meta->offs[L_NET]); /* skip Layer 2 header */
	
	pkt->ipversion = iphdr->version;
	pkt->ttl       = iphdr->ttl;
	pkt->pktlen    = ntohs(iphdr->tot_len);
	pkt->iphdrlen  = iphdr->ihl * 4;

	inet_ntop(AF_INET, &(iphdr->saddr), pkt->srcip, INET_ADDRSTRLEN);
	inet_ntop(AF_INET, &(iphdr->daddr), pkt->dstip, INET_ADDRSTRLEN);
	break;
	}
    case N_IP6: /* IPv6 */
	{
	/* map IPv6 header structure onto packet in memory */
	struct ip6_hdr *ip6hdr = (struct ip6_hdr*) (packet + meta->offs[L_NET]); /* skip Layer 2 header */
	
	pkt->ipversion = ntohl(ip6hdr->ip6_flow) >> 28;
	pkt->ttl       = ip6hdr->ip6_hlim; /* hop limit */
	pkt->pktlen    = ntohs(ip6hdr->ip6_plen) + IPV6HDR_SIZE;
	pkt->iphdrlen  = IPV6HDR_SIZE;

	inet_ntop(AF_INET6, &(ip6hdr->ip6_src), pkt->srcip, INET6_ADDRSTRLEN);
	inet_ntop(AF_INET6, &(ip6hdr->ip6_dst), pkt->dstip, INET6_ADDRSTRLEN);
	break;
	}
    default:    /* layer 3 type is neither IPv4 nor IPv6 */
        return 0;
    }

    pkt->proto = packet[meta->offs[L_NET] + 9]; /* store protocol type */
    pos = packet + meta->offs[L_TRANS]; /* set pos to Layer 3 start, i.e. TCP/UDP header */

    if (pkt->proto == IPPROTO_TCP) {

	/* discard packet if snapsize is too small (need >=14 TCP header bytes) */
	if (meta->cap_len < (unsigned) meta->offs[L_TRANS] + 14) {
	    printf( "[show_ascii]: snapsize to small - discarding TCP packet\n");
	    return 0;
	}

	pkt->srcport = ntohs(((uint16_t *)(pos))[0]);
	pkt->dstport = ntohs(((uint16_t *)(pos))[1]);
	
	pkt->tcpudphdrlen = (pos[12] & 0xf0) / 4;
	/* divide by 4 equals: shift down 4 bits and multiply by 4 */
	
	pkt->tcpseqno = ntohl(((uint32_t *)(pos))[1]);
	pkt->tcpflags = (pos[13] & 0x3f);
	
    } else if (pkt->proto == IPPROTO_UDP) {
	
	/* discard packet if snapsize is too small (need >=6 UDP header bytes) */
	if (meta->cap_len < (unsigned) meta->offs[L_TRANS] + 6) {
	    printf( "[show_ascii]: snapsize to small - discarding UDP packet\n");
	    return 0;
	}

	pkt->srcport = ntohs(((uint16_t *)(pos))[0]);
	pkt->dstport = ntohs(((uint16_t *)(pos))[1]);
	
	pkt->tcpudphdrlen = 8; /* fixed header size for UDP packets */
	pkt->tcpseqno = 0;
	pkt->tcpflags = 0;

    } else if (pkt->proto == IPPROTO_ICMP) {
	
	/* discard packet if snapsize is too small (need >=2 ICMP header bytes) */
	if (meta->cap_len < (unsigned) meta->offs[L_TRANS] + 2) {
	    printf( "[show_ascii]: snapsize to small - discarding IMCP packet\n");
	    return 0;
	}

	pkt->srcport = ((uint8_t *)(pos))[0]; // store ICMP type as srcport
	pkt->dstport = ((uint8_t *)(pos))[1]; // store ICMP code as dstport
	
    } else { /* it's neither UDP nor TCP nor ICMP */
	
	pkt->tcpudphdrlen = 0;
	strcpy(pkt->srcip, "not TCP|UDP|ICMP");
	strcpy(pkt->dstip, "not TCP|UDP|ICMP");
	pkt->srcport  = 0;
	pkt->dstport  = 0;
	pkt->tcpseqno = 0;
	pkt->tcpflags = 0;
    }
    
    /* remember that we have stored a line of export data */
    ((flowRec_t *)flowdata)->nrows += 1;
    
#ifdef DEBUG

    /* also print packet attributes to stderr */

    fprintf( stderr,
	     "IPv%u, ttl=%u, pktlen=%u, iphdrlen=%u, proto=%u, tcp/udp-hdrlen=%u,\n"
	     "srcip=%s, srcport=%u, dstip=%s, dstport=%d, tcpseqno=%u, tcpflags=%s\n",
	     pkt->ipversion,
	     pkt->ttl,
	     pkt->pktlen,
	     pkt->iphdrlen,
	     pkt->proto,
	     pkt->tcpudphdrlen,
	     pkt->srcip,
	     pkt->srcport,
	     pkt->dstip,
	     pkt->dstport,
	     pkt->tcpseqno,
	     printFlags(pkt->tcpflags));


    /* write printable characters from packet body to stdout (use . for non-printable chars) */

    if (meta->offs[L_DATA] != -1) { /* is there data inside the TCP/UDP packet? */
	uint16_t i, len;

	len = meta->cap_len - meta->offs[L_DATA];
	pos = packet + meta->offs[L_DATA];
	
	for (i = 0; i < len; i++) {
	    buffer[i] = map[pos[i]];
	}
	buffer[i] = 0;
	fprintf(stderr, "packet body (%d bytes): %s\n\n", len, buffer);
    }
#endif  /* DEBUG */

    return 0;
}
示例#9
0
int main(int argc, char* argv[])
{
//    LPWSTR szFileName;//声音文件名
    MMCKINFO mmckinfoParent;
    MMCKINFO mmckinfoSubChunk;
    DWORD dwFmtSize;
    HMMIO m_hmmio;//音频文件句柄
    DWORD m_WaveLong;
    HPSTR lpData;//音频数据
    HANDLE m_hData=NULL;
    HANDLE m_hFormat;
    WAVEFORMATEX * lpFormat;
    DWORD m_dwDataOffset;
    DWORD m_dwDataSize;
    WAVEHDR pWaveOutHdr;
    WAVEOUTCAPS pwoc;
    HWAVEOUT hWaveOut;
    int SoundOffset=0;
    int SoundLong=0;
    int DevsNum;
    //打开波形文件
    if(!(m_hmmio=mmioOpen(argv[1],NULL,MMIO_READ|MMIO_ALLOCBUF)))
    {
    //File open Error
        printf("Failed to open the file.");//错误处理函数
        return false;
    }
    //检查打开文件是否是声音文件
    mmckinfoParent.fccType =mmioFOURCC('W','A','V','E');
    if(mmioDescend(m_hmmio,(LPMMCKINFO)&mmckinfoParent,NULL,MMIO_FINDRIFF))
    {
        printf("NOT WAVE FILE AND QUIT");
        return 0;
    }
    //寻找 'fmt' 块
    mmckinfoSubChunk.ckid =mmioFOURCC('f','m','t',' ');
    if(mmioDescend(m_hmmio,&mmckinfoSubChunk,&mmckinfoParent,MMIO_FINDCHUNK))
    {
        printf("Can't find 'fmt' chunk");
        return 0;
    }
    //获得 'fmt '块的大小,申请内存
    dwFmtSize=mmckinfoSubChunk.cksize ;
    m_hFormat=LocalAlloc(LMEM_MOVEABLE,LOWORD(dwFmtSize));
    if(!m_hFormat)
    {
        printf("failed alloc memory");
        return 0;
    }
    lpFormat=(WAVEFORMATEX*)LocalLock(m_hFormat);
    if(!lpFormat)
    {
        printf("failed to lock the memory");
        return 0;
    }
    if((unsigned long)mmioRead(m_hmmio,(HPSTR)lpFormat,dwFmtSize)!=dwFmtSize)
    {
        printf("failed to read format chunk");
        return 0;
    }
    //离开 fmt 块
    mmioAscend(m_hmmio,&mmckinfoSubChunk,0);
    //寻找 'data' 块
    mmckinfoSubChunk.ckid=mmioFOURCC('d','a','t','a');
    if(mmioDescend(m_hmmio,&mmckinfoSubChunk,&mmckinfoParent,MMIO_FINDCHUNK))
    {
        printf("Can't find 'data' chunk");
        return 0;
    }
    //获得 'data'块的大小
    m_dwDataSize=mmckinfoSubChunk.cksize ;
    m_dwDataOffset =mmckinfoSubChunk.dwDataOffset ;
    if(m_dwDataSize==0L)
    {
        printf("no data in the 'data' chunk");
        return 0;
    }
    //为音频数据分配内存
    lpData=new char[m_dwDataSize];
    if(!lpData)
    {
        printf("\ncan not alloc mem");
        return 0;
    }
    if(mmioSeek(m_hmmio,m_dwDataOffset,SEEK_SET)<0)
    {
        printf("Failed to read the data chunk");
        return 0;
    }
//    m_WaveLong=mmioRead(m_hmmio,lpData,SoundLong);
    m_WaveLong=mmioRead(m_hmmio,lpData,m_dwDataSize);
   
    if(m_WaveLong<0)
    {
        printf("Failed to read the data chunk");
        return 0;
    }
    //检查音频设备,返回音频输出设备的性能
    if(waveOutGetDevCaps(WAVE_MAPPER,&pwoc,sizeof(WAVEOUTCAPS))!=0)
    {
        printf("Unable to allocate or lock memory");
        return 0;
    }

    //检查音频输出设备是否能播放指定的音频文件
    DevsNum = WAVE_MAPPER;
    if(waveOutOpen(&hWaveOut,DevsNum,lpFormat,NULL,NULL,CALLBACK_NULL)!=0)
    {
        printf("Failed to OPEN the wave out devices");
//        return 0;
    }
    //准备待播放的数据
    pWaveOutHdr.lpData =(HPSTR)lpData;
    pWaveOutHdr.dwBufferLength =m_WaveLong;
    pWaveOutHdr.dwFlags =0;
	pWaveOutHdr.dwLoops = 10;
    if(waveOutPrepareHeader(hWaveOut,&pWaveOutHdr,sizeof(WAVEHDR))!=0)
    {
        printf("Failed to prepare the wave data buffer");
        return 0;
    }
	printFlags(pWaveOutHdr.dwFlags, "after [waveOutPrepareHeader]");

	pWaveOutHdr.dwFlags |= (WHDR_BEGINLOOP | WHDR_ENDLOOP);
    //播放音频数据文件
    if(waveOutWrite(hWaveOut,&pWaveOutHdr,sizeof(WAVEHDR))!=0)
    {
        printf("Failed to write the wave data buffer");
        return 0;
    }
	printFlags(pWaveOutHdr.dwFlags, "after [waveOutWrite]");
    //关闭音频输出设备,释放内存
//     printf("\npress any key");
//     getchar();
	Sleep(20000);
	printFlags(pWaveOutHdr.dwFlags, "after [Sleep]");

	if(waveOutUnprepareHeader(hWaveOut, &pWaveOutHdr, sizeof(pWaveOutHdr)) != 0)
	{
		printf("Failed to unPrepare the wave data buffer");
        return 0;
	}
	printFlags(pWaveOutHdr.dwFlags, "after [waveOutUnprepareHeader]");

    waveOutReset(hWaveOut);
	printFlags(pWaveOutHdr.dwFlags, "after [waveOutReset]");

    waveOutClose(hWaveOut);
	printFlags(pWaveOutHdr.dwFlags, "after [waveOutClose]");

    LocalUnlock(m_hFormat);
    LocalFree(m_hFormat);
    delete [] lpData;

    return 0;
}