Пример #1
0
//PtpClock * ptpdStartup(int argc, char **argv, Integer16 *ret, RunTimeOpts *rtOpts)
PtpClock * ptpdStartup(Integer16 *ret, RunTimeOpts *rtOpts)
{
  int c, fd = -1, nondaemon = 0, noclose = 0;
  char * optarg;	/*zhenwei*/
  
  
  /* parse command line arguments */
  /* zhenwei
  while( (c = getopt(argc, argv, "?cf:dDxta:w:b:u:l:o:e:hy:m:gps:i:v:n:k:r")) != -1 ) {
    switch(c) {
    case '?':
      printf(
"\nUsage:  ptpd [OPTION]\n\n"
"-?                show this page\n"
"\n"
"-c                run in command line (non-daemon) mode\n"
"-f FILE           send output to FILE\n"
"-d                display stats\n"
"-D                display stats in .csv format\n"
"\n"
"-x                do not reset the clock if off by more than one second\n"
"-t                do not adjust the system clock\n"
"-a NUMBER,NUMBER  specify clock servo P and I attenuations\n"
"-w NUMBER         specify one way delay filter stiffness\n"
"\n"
"-b NAME           bind PTP to network interface NAME\n"
"-u ADDRESS        also send uni-cast to ADDRESS\n"
"-l NUMBER,NUMBER  specify inbound, outbound latency in nsec\n"
"\n"
"-o NUMBER         specify current UTC offset\n"
"-e NUMBER         specify epoch NUMBER\n"
"-h                specify half epoch\n"
"\n"
"-y NUMBER         specify sync interval in 2^NUMBER sec\n"
"-m NUMBER         specify max number of foreign master records\n"
"\n"
"-g                run as slave only\n"
"-p                make this a preferred clock\n"
"-s NUMBER         specify system clock stratum\n"
"-i NAME           specify system clock identifier\n"
"-v NUMBER         specify system clock allen variance\n"
"\n"
"-n NAME           specify PTP subdomain name (not related to IP or DNS)\n"
"\n"
"-k NUMBER,NUMBER  send a management message of key, record, then exit\n"
"\n"
      );
      *ret = 0;
      return 0;
      
    case 'c':
      nondaemon = 1;
      break;
    
    case 'f':
#if !defined __ADSPBF527__    
      if((fd = creat(optarg, 0400)) != -1)
      {
        dup2(fd, STDOUT_FILENO);
        dup2(fd, STDERR_FILENO);
        noclose = 1;
      }
      else
        PERROR("could not open output file");
      break;
#endif
    
    case 'd':
#ifndef PTPD_DBG
      rtOpts->displayStats = TRUE;
#endif
      break;
      
    case 'D':
#ifndef PTPD_DBG
      rtOpts->displayStats = TRUE;
      rtOpts->csvStats = TRUE;
#endif
      break;
      
    case 'x':
      rtOpts->noResetClock = TRUE;
      break;
      
    case 't':
      rtOpts->noAdjust = TRUE;
      break;
      
    case 'a':
      rtOpts->ap = strtol(optarg, &optarg, 0);
      if(optarg[0])
        rtOpts->ai = strtol(optarg+1, 0, 0);
      break;
      
    case 'w':
      rtOpts->s = strtol(optarg, &optarg, 0);
      break;
      
    case 'b':
      memset(rtOpts->ifaceName, 0, IFACE_NAME_LENGTH);
      strncpy(rtOpts->ifaceName, optarg, IFACE_NAME_LENGTH);
      break;
      
    case 'u':
      strncpy(rtOpts->unicastAddress, optarg, NET_ADDRESS_LENGTH);
      break;
      
    case 'l':
      rtOpts->inboundLatency.nanoseconds = strtol(optarg, &optarg, 0);
      if(optarg[0])
        rtOpts->outboundLatency.nanoseconds = strtol(optarg+1, 0, 0);
      break;
      
    case 'o':
      rtOpts->currentUtcOffset = strtol(optarg, &optarg, 0);
      break;
      
    case 'e':
      rtOpts->epochNumber = strtoul(optarg, &optarg, 0);
      break;
      
    case 'h':
      rtOpts->halfEpoch = TRUE;
      break;
      
    case 'y':
      rtOpts->syncInterval = strtol(optarg, 0, 0);
      break;
      
    case 'm':
      rtOpts->max_foreign_records = strtol(optarg, 0, 0);
      if(rtOpts->max_foreign_records < 1)
        rtOpts->max_foreign_records = 1;
      break;
      
    case 'g':
      rtOpts->slaveOnly = TRUE;
      break;
      
    case 'p':
      rtOpts->clockPreferred = TRUE;
      break;
      
    case 's':
      rtOpts->clockStratum = strtol(optarg, 0, 0);
      if(rtOpts->clockStratum <= 0)
        rtOpts->clockStratum = 255;
      break;
      
    case 'i':
      memset(rtOpts->clockIdentifier, 0, PTP_CODE_STRING_LENGTH);
      strncpy(rtOpts->clockIdentifier, optarg, PTP_CODE_STRING_LENGTH);
      break;
      
    case 'v':
      rtOpts->clockVariance = strtol(optarg, 0, 0);
      break;
      
    case 'n':
      memset(rtOpts->subdomainName, 0, PTP_SUBDOMAIN_NAME_LENGTH);
      strncpy(rtOpts->subdomainName, optarg, PTP_SUBDOMAIN_NAME_LENGTH);
      break;
      
    case 'k':
      rtOpts->probe = TRUE;
      
      rtOpts->probe_management_key = strtol(optarg, &optarg, 0);
      if(optarg[0])
        rtOpts->probe_record_key = strtol(optarg+1, 0, 0);
      
      nondaemon = 1;
      break;
      
    case 'r':
      ERROR("The '-r' option has been removed because it is now the default behaviour.\n");
      ERROR("Use the '-x' option to disable clock resetting.\n");
      *ret = 1;
      return 0;
      
    default:
      *ret = 1;
      return 0;
    }
  }
  */
  
  // options set up
 // rtOpts->displayStats = TRUE;
 //	rtOpts->slaveOnly = TRUE;
  
 	strncpy((char*)&rtOpts->unicastAddress, myIP, NET_ADDRESS_LENGTH);  
 
  
  
  ptpClock = (PtpClock*)calloc(1, sizeof(PtpClock));
  if(!ptpClock)
  {
    PERROR("failed to allocate memory for protocol engine data\n");
    *ret = 2;
    return 0;
  }
  else
  {
    DBG("allocated %d bytes for protocol engine data\n", (int)sizeof(PtpClock));
    ptpClock->foreign = (ForeignMasterRecord*)calloc(rtOpts->max_foreign_records, sizeof(ForeignMasterRecord));
    if(!ptpClock->foreign)
    {
      PERROR("failed to allocate memory for foreign master data\n");
      *ret = 2;
      free(ptpClock);
      return 0;
    }
    else
    {
      DBG("allocated %d bytes for foreign master data\n", (int)(rtOpts->max_foreign_records*sizeof(ForeignMasterRecord)));
    }
  }


  *ret = 0;
  return ptpClock;
}
Пример #2
0
/** main function
 * \param argc ?
 * \param argv ?
 * \return 0
*/
int
main(int argc, char **argv)
{
     int i;
     char *ol = "csgVS";
     extern char *optarg;
     extern int optind;
     struct sigaction sa;

     argv_global  = xstrdup(argv[0]);
     all_argv = argv;
     sprintf(conf.confpath, "%s/"DEF_CONF, getenv("HOME"));

     while((i = getopt(argc, argv, "hviSc:s:g:C:V:")) != -1)
     {

          /* For options who need WMFS running */
          if(strchr(ol, i) && !(dpy = XOpenDisplay(NULL)))
               errx(EXIT_FAILURE, "cannot open X server.");

          switch(i)
          {
          case 'h':
          default:
               printf("usage: %s [-ihvS] [-C <file>] [-c <uicb function> <cmd> ] [-g <argument>] [-s <screen_num> <string>] [-V <viwmfs cmd]\n"
                      "   -C <file>                 Load a configuration file\n"
                      "   -c <uicb_function> <cmd>  Execute an uicb function to control WMFS\n"
                      "   -g <argument>             Show information about wmfs status\n"
                      "   -s <screen_num> <string>  Set the bar(s) statustext\n"
                      "   -V <viwmfs cmd>           Manage WMFS with vi-like command\n"
                      "   -S                        Update status script\n"
                      "   -h                        Show this page\n"
                      "   -i                        Show informations\n"
                      "   -v                        Show WMFS version\n", argv[0]);
               exit(EXIT_SUCCESS);
               break;

          case 'i':
               printf("WMFS - Window Manager From Scratch By Martin Duquesnoy\n");
               exit(EXIT_SUCCESS);
               break;

          case 'v':
               printf("WMFS "WMFS_VERSION"\n");
               exit(EXIT_SUCCESS);
               break;

          case 'S':
               update_status();
               XCloseDisplay(dpy);
               exit(EXIT_SUCCESS);
               break;

          case 'C':
               strncpy(conf.confpath, optarg, sizeof(conf.confpath));
               break;

          case 'c':
               exec_uicb_function(optarg, argv[optind]);
               XCloseDisplay(dpy);
               exit(EXIT_SUCCESS);
               break;

          case 's':
               if(argc > 3)
                    set_statustext(atoi(optarg), argv[3]);
               else
                    set_statustext(-1, optarg);
               XCloseDisplay(dpy);
               exit(EXIT_SUCCESS);
               break;

          case 'g':
               getinfo(optarg);
               XCloseDisplay(dpy);
               exit(EXIT_SUCCESS);
               break;
          case 'V':
               viwmfs(argc, argv);
               XCloseDisplay(dpy);
               exit(EXIT_SUCCESS);
               break;
          }
     }

     /* Check if WMFS can open X server */
     if(!(dpy = XOpenDisplay(NULL)))
          errx(EXIT_FAILURE, "cannot open X server.");

     /* Set signal handler */
     memset(&sa, 0, sizeof(sa));
     sa.sa_handler = signal_handle;
     sigemptyset(&sa.sa_mask);
     sigaction(SIGQUIT, &sa, NULL);
     sigaction(SIGTERM, &sa, NULL);
     sigaction(SIGCHLD, &sa, NULL);

     /* Check if an other WM is already running; set the error handler */
     XSetErrorHandler(errorhandler);

     /* Let's Go ! */
     init();
     scan();
     mainloop();
     quit();

     return 0;
}
Пример #3
0
static void parse_wiggle_format_line(WIGGLE_READER_T *reader, const char *line) {

  reader->format = INVALID_FMT;
  int status = regexec(
    &fixed_format_regex,
    line,
    NUM_MATCHES,
    matches,
    0
  );
  if (!status) {
    reader->format = FIXED_WIGGLE_FMT;
  }
  else if (status != REG_NOMATCH ) {
    regerror(status, &fixed_format_regex, error_message, ERROR_MESSAGE_SIZE);
    die(
      "Error checking for fixed step wiggle file: %s\n"
      "error message is %s\n",
      reader->filename, 
      error_message
    );
  }
  else {
    status = regexec(&var_format_regex, line, NUM_MATCHES, matches, 0);
    if (!status) {
      reader->format = VAR_WIGGLE_FMT;
    }
    else if (status != REG_NOMATCH ) {
      regerror(status, &var_format_regex, error_message, ERROR_MESSAGE_SIZE);
      die(
        "Error checking for variable step wiggle file: %s\n"
        "error message is %s\n",
        reader->filename, 
        error_message
      );
    }
  }

  if (reader->format == FIXED_WIGGLE_FMT) {
    const int CHROM_GROUP = 1;
    int len = matches[CHROM_GROUP].rm_eo - matches[CHROM_GROUP].rm_so;
    catch_match_too_long(len, line, reader->filename);
    myfree(reader->chrom);
    reader->chrom = mm_malloc(len + 1);
    char *last 
      = strncpy(reader->chrom, line + matches[CHROM_GROUP].rm_so, len) + len;
    *last = 0; // Terminate string
    const int START_GROUP = 2;
    len = matches[START_GROUP].rm_eo - matches[START_GROUP].rm_so;
    catch_match_too_long(len, line, reader->filename);
    last = strncpy(buffer, line + matches[START_GROUP].rm_so, len) + len;
    *last = 0; // Terminate string
    reader->start = strtod(buffer, NULL);
    const int STEP_GROUP = 3;
    len = matches[STEP_GROUP].rm_eo - matches[STEP_GROUP].rm_so;
    catch_match_too_long(len, line, reader->filename);
    last = strncpy(buffer, line + matches[STEP_GROUP].rm_so, len) + len;
    *last = 0; // Terminate string
    reader->step = strtod(buffer, NULL);
    // Optional match, may not be present
    const int SPAN_GROUP = 5;
    len = matches[SPAN_GROUP].rm_eo - matches[SPAN_GROUP].rm_so;
    if (len > 0) {
      catch_match_too_long(len, line, reader->filename);
      last = strncpy(buffer, line + matches[SPAN_GROUP].rm_so, len) + len;
      *last = 0; // Terminate string
      reader->span = strtod(buffer, NULL);
    }
  }
  else if (reader->format == VAR_WIGGLE_FMT) {
    const int CHROM_GROUP = 1;
    int len = matches[CHROM_GROUP].rm_eo - matches[CHROM_GROUP].rm_so;
    catch_match_too_long(len, line, reader->filename);
    // Check if chromosome has changed since last call.
    if (reader->chrom == NULL 
        || strncmp(reader->chrom, line + matches[CHROM_GROUP].rm_so, len) != 0) {
      myfree(reader->chrom);
      reader->chrom = mm_malloc(len + 1);
    }
    char *last 
      = strncpy(reader->chrom, line + matches[CHROM_GROUP].rm_so, len) + len;
    *last = 0; // Terminate string
    // Optional match, may not be present
    const int SPAN_GROUP = 3;
    len = matches[SPAN_GROUP].rm_eo - matches[SPAN_GROUP].rm_so;
    if (len > 0) {
      catch_match_too_long(len, line, reader->filename);
      last = strncpy(buffer, line + matches[SPAN_GROUP].rm_so, len) + len;
      *last = 0; // Terminate string
      reader->span = strtod(buffer, NULL);
    }
  }
  else {
    die(
      "Unable to determine type of wiggle format in %s.\n",
      reader->filename
    );
  }
}
Пример #4
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int 
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif
int iScreenLogLevel;		// level of screen diagnostics
int iFileLogLevel;			// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file
int Rslt = 0;   			// function result code >= 0 represents success, < 0 on failure

etPMode PMode;				// processing mode
etFMode FMode;				// format output mode

int TruncLength;			// truncate regions to be no longer than this length
int OfsLoci;				// offset region loci by this many bases
int DeltaLen;				// change region lengths by this many bases

int MovAvgFilter;			// apply this moving average window size filter
int BaselineFilter;			// use this window size when normalising for baseline
char szTrackTitle[cMaxDatasetSpeciesChrom];			// title to identify predicted nucleosome track
double Dyadratio;
double Dyad2ratio;
double Dyad3ratio;
char szRsltsFile[_MAX_PATH];
char szInConfFile[_MAX_PATH];
char szInGenomeFile[_MAX_PATH];

char szInclRegionFile[_MAX_PATH]; //  only report predicted nucleosomes if intersecting with regions in this file


// command line args
struct arg_lit  *help    = arg_lit0("hH","help",                "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_int *pmode = arg_int0("m","mode","<int>",		    "processing mode: 0 - predict from minor groove (default = 0)");
struct arg_file *inGenomefile = arg_file1("i","in","<file>",	"input from this bioseq genome file");
struct arg_file *inConfFile = arg_file1("I","conf","<file>",	"input conformation characteristics from this file");

struct arg_file *inclRegionFile = arg_file0("r","inclregions","<file>",	"only report predicted nucleosomes if intersecting with regions in this file");
struct arg_int  *trunclength = arg_int0("T","trunclength","<int>","truncate regions to be no longer than this length (default 147)");
struct arg_int  *ofsloci   = arg_int0("u","offset","<int>",	    "offset region loci by this many bases, -2048 to +2048 (default 0)");
struct arg_int  *deltalen  = arg_int0("U","deltalen","<int>",	"delta region lengths by this many bases, -2048 to +2048 (default 0)");

struct arg_dbl *dyadratio=arg_dbl0("d", "dyadratio",	"<double>","dyad minor grooves must be at least this ratio to background (default 1.020");
struct arg_dbl *dyad2ratio=arg_dbl0("D", "dyad2ratio",	"<double>","immediately flanking minor grooves must be at least this ratio to background (default 1.015");
struct arg_dbl *dyad3ratio=arg_dbl0("e", "dyad3ratio",	"<double>","remainder flanking minor grooves must be at least this ratio to background (default 1.010");

struct arg_int *movavgfilter = arg_int0("a","avgwindow","<int>","apply lowpass filter as a moving average window of this size, 0 if none else 5..100 (default: 10)");
struct arg_int *baselinefilter = arg_int0("A","basewindow","<int>","baseline normalisation window size, 0 if none else 25..5000 (default: 250)");

struct arg_file *outfile = arg_file1("o","out","<file>",		"output nucleosome predictions to this file");
struct arg_int *format = arg_int0("M","format","<int>",		    "output format: 0 - UCSC bedGraph dyads, 1 - UCSC BED dyads, 2 - CSV dyads,  3 - UCSC bedGraph nucleosomes, 4 - UCSC BED nucleosomes, 5 - CSV nucleosomes, 6 - CSV scores (default: 0)");
struct arg_str  *title = arg_str0("t","title","<string>",       "track title");

struct arg_end *end = arg_end(20);

void *argtable[] = {help,version,FileLogLevel,LogFile,
					pmode,format,movavgfilter,baselinefilter,title,dyadratio,dyad2ratio,dyad3ratio,inGenomefile,inConfFile,outfile,
					inclRegionFile,trunclength,ofsloci,deltalen,
					end};

char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s ", gszProcName);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s @myparams.txt\n\n",gszProcName);
		exit(1);
        }

    /* special case: '--version' takes precedence error reporting */ 
if (version->count > 0)
        {
		printf("\n%s Version %d.%2.2d",gszProcName,cProgVer/100,cProgVer%100);
		exit(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}
	
	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	PMode = (etPMode)(pmode->count ? pmode->ival[0] : 0);
	if(PMode < 0 || PMode >= ePMplaceholder)
		{
		printf("\nError: Processing mode '-m%d' specified outside of range %d..%d",PMode,0,(int)ePMplaceholder-1);
		exit(1);
		}

	FMode = (etFMode)(format->count ? format->ival[0] : eFMbedGraphDyads);
	if(FMode < eFMbedGraphDyads || FMode >= eFMplaceholder)
		{
		printf("\nError: Output format mode '-m%d' specified outside of range %d..%d",FMode,eFMbedGraphDyads,(int)eFMplaceholder-1);
		exit(1);
		}

		MovAvgFilter = movavgfilter->count ? movavgfilter->ival[0] : 10;
	if(MovAvgFilter != 0 && (MovAvgFilter < 5 || MovAvgFilter > 100))
		{
		printf("\nError: Moving average filter width '-a%d' specified outside of range 0 or 5..100",MovAvgFilter);
		exit(1);
		}


	BaselineFilter = baselinefilter->count ? baselinefilter->ival[0] : 250;
	if(BaselineFilter != 0 && (BaselineFilter < 25 || MovAvgFilter > 5000))
		{
		printf("\nError: Baseline normalisation window width '-A%d' specified outside of range 0 or 25..5000",BaselineFilter);
		exit(1);
		}

	Dyadratio = dyadratio->count ? dyadratio->dval[0] : cDfltDyadratio;
	Dyad2ratio = dyad2ratio->count ? dyad2ratio->dval[0] : cDfltDyad2ratio;
	Dyad3ratio = dyad3ratio->count ? dyad3ratio->dval[0] : cDfltDyad3ratio;
	if(Dyadratio < 1.0f || Dyad2ratio < 1.0f || Dyad3ratio < 1.0f)
		{
		printf("\nError: All dyad and flanking threshold ratios must be at least 1.0");
		exit(1);
		}


	if(!title->count)
		{
		printf("\nError: no track title has been specified with '-t<title>' option");
		exit(1);
		}
	if(strlen(title->sval[0]) >= cMaxDatasetSpeciesChrom)
		{
		printf("\nError: track title '%s' is too long, must be shorter than %d chars",title->sval[0],cMaxDatasetSpeciesChrom-1);
		exit(1);
		}
	strncpy(szTrackTitle,title->sval[0],sizeof(szTrackTitle));
	szTrackTitle[sizeof(szTrackTitle)-1] = '\0';
	CUtility::TrimQuotedWhitespcExtd(szTrackTitle);
	CUtility::ReduceWhitespace(szTrackTitle);
	if(szTrackTitle[0] == '\0')
		{
		printf("\nError: specified track title is empty or whitespace only");
		exit(1);
		}

	strcpy(szInGenomeFile,inGenomefile->filename[0]);
	strcpy(szInConfFile,inConfFile->filename[0]);
	strcpy(szRsltsFile,outfile->filename[0]);

	if(inclRegionFile->count)
		{
		strncpy(szInclRegionFile,inclRegionFile->filename[0],_MAX_PATH);
		szInclRegionFile[_MAX_PATH-1] = '\0';

		OfsLoci = ofsloci->count ? ofsloci->ival[0] : 0;
		if(abs(OfsLoci) > 1024)
			{
			printf("Error: loci offset '-u%d' must be in the range -2048 to +2048",OfsLoci);
			exit(1);
			}

		DeltaLen = deltalen->count ? deltalen->ival[0] : 0;
		if(abs(DeltaLen) > 1024)
			{
			printf("Error: delta length '-U%d' must be in the range -2048 to +2048",DeltaLen);
			exit(1);
			}

		TruncLength = trunclength->count ? trunclength->ival[0] : 147;
		if(TruncLength < 147)
			{
			printf("Error: regions truncation length '-T%d' must be at least 147",TruncLength);
			exit(1);
			}
		}
	else
		{
		szInclRegionFile[0] = '\0';
		OfsLoci = 0;
		DeltaLen = 0;
		TruncLength = 0;
		}
	


		// now that command parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem.");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile);
		exit(1);
		}

// show user current resource limits
#ifndef _WIN32
	gDiagnostics.DiagOut(eDLInfo, gszProcName, "Resources: %s",CUtility::ReportResourceLimits());
#endif

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %d.%2.2d Processing parameters:",cProgVer/100,cProgVer%100);
	const char *pszDescr;
	switch(PMode) {
		case ePMdefault:				
			pszDescr = "Default - predict from minor groove";
			break;
		}

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"processing mode is : '%s'",pszDescr);

	switch(FMode) {
		case eFMbedGraphDyads:				
			pszDescr = "UCSC bedGraph dyads";
			break;
		case eFMbedDyads:					
			pszDescr = "UCSC BED dyads";
			break;
		case eFMcsvDyads:					
			pszDescr = "CSV dyads";
			break;
		case eFMbedGraphNucs:					
			pszDescr = "UCSC bedGraph nucleosomes";
			break;
		case eFMbedNucs:					
			pszDescr = "UCSC BED nucleosomes";
			break;
		case eFMcsvNucs:					
			pszDescr = "CSV nucleosomes";
			break;
		case eFMMcsvScores:					
			pszDescr = "CSV dyad scores along genome";
			break;

		}
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"output format is : '%s'",pszDescr);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"moving average filter width : %d",MovAvgFilter);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"baseline noramlisation width : %d",BaselineFilter);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"dyad name: '%s'",szTrackTitle);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"dyad minor groove threshold: %1.4f",Dyadratio);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"dyad immediately flanking minor groove threshold: %1.4f",Dyad2ratio);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"dyad remainder flanking minor groove threshold: %1.4f",Dyad3ratio);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"input genome file: '%s'",szInGenomeFile);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"input conformation file: '%s'",szInConfFile);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"output predicted nucleosomes file: '%s'",szRsltsFile);
	
	if(szInclRegionFile[0] != '0')
		{
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Offset region start loci by : %d",OfsLoci);
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Delta region length by : %d",DeltaLen);
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Truncate region length: %d",TruncLength);
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"include regions file: '%s'",szInclRegionFile);
		}
#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	gStopWatch.Start();
	Rslt = Process(PMode,FMode,MovAvgFilter,BaselineFilter,szTrackTitle,Dyadratio,Dyad2ratio,Dyad3ratio,szInGenomeFile,szInConfFile,szRsltsFile,
									szInclRegionFile,OfsLoci,DeltaLen,TruncLength);
	gStopWatch.Stop();
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nend of help\n");
	exit(1);
	}
return 0;
}
Пример #5
0
/** Reads the opcode list and generates output code based on the spec */
void generateCodeTable (FILE *opcodes, FILE *code)
{
	char line[MAX_LINE];
	char last[MAX_LINE];
	char tmp[MAX_LINE];
	char name[MAX_LINE];
	char parm[5], subst[20];
	int i;
	char *p, *q;
	char **cmds;
	regmatch_t matches[MAX_MATCH];
	Item *item;

	printf("Generating opcode implementations...");
	last[0] = 0;
	do
	{			
		fgets(line, MAX_LINE, opcodes);
		trim(line);
		
		if (feof(opcodes))
			break;
				
		for (q = line, p = q+OPCODE_OFFSET; *p; *q++ = *p++);	/* Skip the hex part */
		*q = 0;
		
		/* Avoid duplicate opcodes */
		if (strcmp(last, line) == 0)
			continue;		
		strcpy(last, line);
			
		/* Find the appropriate pattern */
		for (i = 0; i < nItems; i++)
		{
			if (regexec(&items[i].re, line, MAX_MATCH, matches, REG_EXTENDED) == 0)
			{	
				if (matches[0].rm_so == 0 && matches[0].rm_eo == strlen(line))	/* Match only entire line (fixes problem with INC HL being matched to INC H */
				{
					/*printf("%s : match %s\n", &line, items[i].pat);*/
					break;
				}
			}
		}
		
		if (i >= nItems)
        {
			fatal2(line, " didn't match anything");
            continue;
        }
			
		item = &items[i];
		
		/* Print function stub */
		fixName(line, name);
        fprintf(code, "void Z80CPU::%s ()\n{\n", name);
				
		/* Substitute submatches in each output line and print the code */
		cmds = item->line;
		strcpy(parm, "%0");
		while (*cmds)
		{
			if (!printCall(*cmds, code))
			{
				strncpy(tmp, *cmds, MAX_LINE);
				q = tmp;
		
				for (i = 1; i < MAX_MATCH; i++)
				{
					parm[1] = i + '0';
					strncpy(subst, &line[matches[i].rm_so], matches[i].rm_eo - matches[i].rm_so);
					subst[matches[i].rm_eo - matches[i].rm_so] = 0;
					
					substStr(tmp, parm, subst);
				}
				fprintf(code, "%s\n", tmp);
			}
			
			cmds++;	
		}
		
		fprintf(code, "}\n\n\n");
	} while(1);
	printf("done\n");
}
Пример #6
0
void InitializeKeyStrings()
{
    print("Initializing key strings..");
    for(int keyCode = 0; keyCode < KEY::KEY_AMOUNT; ++keyCode)
    {
        if(keyCode >= KEY::A && keyCode <= KEY::Z) {
            char key[2];
            key[0] = char('A' + keyCode - KEY::A);
            key[1] = '\0';
            strncpy(keyString[keyCode], key, 16);
        }
        else if(keyCode >= KEY::a && keyCode <= KEY::z) {
            char key[2];
            key[0] = char('a' + keyCode - KEY::a);
            key[1] = '\0';
            strncpy(keyString[keyCode], key, 16);
        }
        else if(keyCode >= KEY::F1 && keyCode <= KEY::F12) {
            char key[4];
            key[0] = 'F';
            int index = 1;
            if(keyCode >= KEY::F10) {
                key[index++] = '1';
                key[index++] = char('0' + keyCode - KEY::F10);
            }
            else
                key[index++] = char('1' + keyCode - KEY::F1);
            key[index++] = '\0';
            strncpy(keyString[keyCode], key, 16);
        }
        else
        {
            switch(keyCode)
            {
            case KEY::NULL_KEY:
                strncpy(keyString[keyCode], "NULL_KEY",     16);
                break;

            case KEY::Zero:
                strncpy(keyString[keyCode], "Zero",         16);
                break;
            case KEY::One:
                strncpy(keyString[keyCode], "One",          16);
                break;
            case KEY::Two:
                strncpy(keyString[keyCode], "Two",          16);
                break;
            case KEY::Three:
                strncpy(keyString[keyCode], "Three",        16);
                break;
            case KEY::Four:
                strncpy(keyString[keyCode], "Four",         16);
                break;
            case KEY::Five:
                strncpy(keyString[keyCode], "Five",         16);
                break;
            case KEY::Six:
                strncpy(keyString[keyCode], "Six",          16);
                break;
            case KEY::Seven:
                strncpy(keyString[keyCode], "Seven",        16);
                break;
            case KEY::Eight:
                strncpy(keyString[keyCode], "Eight",        16);
                break;
            case KEY::Nine:
                strncpy(keyString[keyCode], "Nine",         16);
                break;

            case KEY::Enter:
                strncpy(keyString[keyCode], "Enter",        16);
                break;
            case KEY::Space:
                strncpy(keyString[keyCode], "Space",        16);
                break;
            case KEY::Control:
                strncpy(keyString[keyCode], "Control",      16);
                break;
            case KEY::Shift:
                strncpy(keyString[keyCode], "Shift",        16);
                break;
            case KEY::Escape:
                strncpy(keyString[keyCode], "Escape",       16);
                break;
            case KEY::Alt:
                strncpy(keyString[keyCode], "Alt",          16);
                break;
            case KEY::Tab:
                strncpy(keyString[keyCode], "Tab",          16);
                break;
            case KEY::Backspace:
                strncpy(keyString[keyCode], "Backspace",    16);
                break;

            case KEY::Plus:
                strncpy(keyString[keyCode], "Plus",         16);
                break;
            case KEY::Minus:
                strncpy(keyString[keyCode], "Minus",        16);
                break;
            case KEY::Multiply:
                strncpy(keyString[keyCode], "Multiply",     16);
                break;
            case KEY::Divided:
                strncpy(keyString[keyCode], "Divided",      16);
                break;

            case KEY::Period:
                strncpy(keyString[keyCode], "Period",       16);
                break;
            case KEY::Comma:
                strncpy(keyString[keyCode], "Comma",        16);
                break;

            case KEY::Home:
                strncpy(keyString[keyCode], "Home",         16);
                break;
            case KEY::End:
                strncpy(keyString[keyCode], "End",          16);
                break;
            //case KEY::A: case
            default:
                break;
            }
            // Add NUll terminator in the end
            char end = '\0';
            strcat(keyString[keyCode], &end);
        }
    }
    initialized = true;
}
Пример #7
0
const char *disambiguate_h(SourceFile *sourcefile) {
  char *p, *pe, *bof;
  int length;

  // If the directory contains a matching *.m file, likely Objective C.
  length = strlen(sourcefile->filename);
  if (strcmp(sourcefile->ext, "h") == 0) {
    char path[length];
    strncpy(path, sourcefile->filename, length);
    path[length] = '\0';
    *(path + length - 1) = 'm';
    char **filenames = sourcefile->filenames;
    if (filenames) {
      int i;
      for (i = 0; filenames[i] != NULL; i++)
        if (strcmp(path, filenames[i]) == 0)
          return LANG_OBJECTIVE_C;
    }
  }

  // Attempt to detect based on file contents.
  char line[81], buf[81];
  bof = ohcount_sourcefile_get_contents(sourcefile);
  p = bof;
  pe = p;
  char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
  while (pe < eof) {
    // Get a line at a time.
    while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
    length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
    strncpy(line, p, length);
    line[length] = '\0';
    char *eol = line + strlen(line);
    char *line_end = pe;

    // Look for C++ headers.
    if (*line == '#') {
      p = line + 1;
      while (*p == ' ' || *p == '\t') p++;
      if (strncmp(p, "include", 7) == 0 &&
          (*(p + 7) == ' ' || *(p + 7) == '\t')) {
        // /^#\s*include\s+[<"][^>"]+[>"]/
        p += 8;
        while (*p == ' ' || *p == '\t') p++;
        if (*p == '<' || *p == '"') {
          // Is the header file a C++ header file?
          p++;
          pe = p;
          while (pe < eol && *pe != '>' && *pe != '"') pe++;
          length = pe - p;
          strncpy(buf, p, length);
          buf[length] = '\0';
          if (ohcount_hash_is_cppheader(buf, length))
            return LANG_CPP;
          // Is the extension for the header file a C++ file?
          p = pe;
          while (p > line && *(p - 1) != '.') p--;
          length = pe - p;
          strncpy(buf, p, length);
          buf[length] = '\0';
          struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
          if (re && strcmp(re->value, LANG_CPP) == 0)
            return LANG_CPP;
        }
      }
    }

    // Look for C++ keywords.
    p = line;
    while (p < eol) {
      if (islower(*p) && p != bof && !isalnum(*(p - 1)) && *(p - 1) != '_') {
        pe = p;
        while (islower(*pe)) pe++;
        if (!isalnum(*pe) && *pe != '_') {
          length = pe - p;
          strncpy(buf, p, length);
          buf[length] = '\0';
          if (strcmp(buf, "class") == 0 ||
              strcmp(buf, "namespace") == 0 ||
              strcmp(buf, "template") == 0 ||
              strcmp(buf, "typename") == 0)
            return LANG_CPP;
        }
        p = pe + 1;
      } else p++;
    }

    // Next line.
    pe = line_end;
    while (*pe == '\r' || *pe == '\n') pe++;
    p = pe;
  }

  // Nothing to suggest C++.
  return LANG_C;
}
Пример #8
0
int main(void){
    
    int server_Socket, accept_Socket;
    unsigned int length, count;
    struct sockaddr_in server_Struct, client_Struct;
    char got_charachter[1000];
    char web_Site[]="HTTP/1.1 200 OK\r\n\r\n";
    unsigned short int port_No=5000;
    char *position_of_GET,*position_of_HTTP;
    char nameof_File[100];
    
    server_Socket=socket(AF_INET,SOCK_STREAM,0);
    
    
    server_Struct.sin_family=AF_INET;
    server_Struct.sin_addr.s_addr=htonl(INADDR_ANY);
    server_Struct.sin_port=htons(port_No);
    length=sizeof(server_Struct);
   
    
    printf("\n Server is now binding....");
    bind(server_Socket,(struct sockaddr *)&server_Struct,length);
   
    printf("\n Server listen....");
    //printf("\n Server mit IP %s on port %d ",ip_Adress,port_No);
    listen(server_Socket,5);
    
    while(1){
        
        printf("\n Server accept.....");
        fflush(stdout);
        accept_Socket=accept(server_Socket,(struct sockaddr *)&client_Struct, &length);
      
        printf(" connected to %s",inet_ntoa(client_Struct.sin_addr));
        
        count=read(accept_Socket,got_charachter,sizeof(got_charachter));
        got_charachter[count]=0;
        printf("server got the charachters %s",got_charachter);
        
        
       if(position_of_GET=strstr(got_charachter,"GET"))
       {
         printf("\n GET command start at char %ld\n\n",(position_of_GET-got_charachter)+1);
              if(position_of_HTTP=strstr(got_charachter,"HTTP"))
              {
                printf("\n GET command start at char %ld\n\n",(position_of_HTTP-got_charachter)+1);
                length=position_of_HTTP-position_of_GET-6;
                strncpy(nameof_File,position_of_GET+4,length+1);
                nameof_File[length+1]=0;
                printf("\n The name of File you asked for %s is not available at this moment",nameof_File);
              }
                else
              {
                      printf("\n HTTP has no HTTP \n\n");
              }
       }
       else
       {
           printf("\n HTTP has no GET \n\n");
       }
       
       printf("\n\n\n");
        write(accept_Socket,web_Site,sizeof(web_Site));
        printf("\n\n server close()....");
        close(accept_Socket);
    
        
        
        
    }

    
    
    
    
    return (0);
}
Пример #9
0
static void check_content_type_and_change_protocol(struct ndpi_detection_module_struct
						   *ndpi_struct, struct ndpi_flow_struct *flow)
{
#ifdef NDPI_PROTOCOL_MPEG
  struct ndpi_packet_struct *packet = &flow->packet;
#endif
#ifdef NDPI_PROTOCOL_AVI
#endif
  //      struct ndpi_id_struct         *src=ndpi_struct->src;
  //      struct ndpi_id_struct         *dst=ndpi_struct->dst;

  u_int8_t a;

  if (packet->content_line.ptr != NULL && packet->content_line.len != 0) {
    NDPI_LOG(NDPI_PROTOCOL_HTTP, ndpi_struct, NDPI_LOG_DEBUG, "Content Type Line found %.*s\n",
	    packet->content_line.len, packet->content_line.ptr);
#ifdef NDPI_PROTOCOL_MPEG
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_MPEG) != 0)
      mpeg_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_FLASH
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_FLASH) != 0)
      flash_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_QUICKTIME
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_QUICKTIME) != 0)
      qt_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_REALMEDIA
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_REALMEDIA) != 0)
      realmedia_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_WINDOWSMEDIA
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_WINDOWSMEDIA) != 0)
      windowsmedia_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_MMS
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_MMS) != 0)
      mms_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_OFF
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_OFF) != 0)
      off_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_OGG
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_OGG) != 0)
      ogg_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_MOVE
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_MOVE) != 0)
      move_parse_packet_contentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_WEBM
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_WEBM) != 0)
      webm_parse_packet_contentline(ndpi_struct, flow);
#endif
  }
  /* check user agent here too */
  if (packet->user_agent_line.ptr != NULL && packet->user_agent_line.len != 0) {
    NDPI_LOG(NDPI_PROTOCOL_HTTP, ndpi_struct, NDPI_LOG_DEBUG, "User Agent Type Line found %.*s\n",
	    packet->user_agent_line.len, packet->user_agent_line.ptr);
#ifdef NDPI_PROTOCOL_XBOX
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_XBOX) != 0)
      xbox_parse_packet_useragentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_WINDOWS_UPDATE    
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_WINDOWS_UPDATE) != 0)
      windows_update_packet_useragentline(ndpi_struct, flow);
#endif
#ifdef NDPI_PROTOCOL_WINDOWSMEDIA
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_WINDOWSMEDIA) != 0)
      winmedia_parse_packet_useragentline(ndpi_struct, flow);
#endif

  }
  /* check for host line */
  if (packet->host_line.ptr != NULL) {
    u_int len;

    NDPI_LOG(NDPI_PROTOCOL_HTTP, ndpi_struct, NDPI_LOG_DEBUG, "HOST Line found %.*s\n",
	    packet->host_line.len, packet->host_line.ptr);
#ifdef NDPI_PROTOCOL_QQ
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_QQ) != 0) {
      qq_parse_packet_URL_and_hostname(ndpi_struct, flow);
    }
#endif

    /* Copy result for nDPI apps */
    len = ndpi_min(packet->host_line.len, sizeof(flow->host_server_name)-1);
    strncpy((char*)flow->host_server_name, (char*)packet->host_line.ptr, len);
    flow->host_server_name[len] = '\0';

    parseHttpSubprotocol(ndpi_struct, flow);
    
    if(packet->detected_protocol_stack[0] != NDPI_PROTOCOL_HTTP) {
      ndpi_int_http_add_connection(ndpi_struct, flow, packet->detected_protocol_stack[0]);
      return; /* We have identified a sub-protocol so we're done */
    }
  }
   
  /* check for accept line */
  if (packet->accept_line.ptr != NULL) {
    NDPI_LOG(NDPI_PROTOCOL_HTTP, ndpi_struct, NDPI_LOG_DEBUG, "Accept Line found %.*s\n",
	    packet->accept_line.len, packet->accept_line.ptr);
#ifdef NDPI_PROTOCOL_RTSP
    if (NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_struct->detection_bitmask, NDPI_PROTOCOL_RTSP) != 0) {
      rtsp_parse_packet_acceptline(ndpi_struct, flow);
    }
#endif
  }
  /* search for line startin with "Icy-MetaData" */
#ifdef NDPI_PROTOCOL_MPEG
  for (a = 0; a < packet->parsed_lines; a++) {
    if (packet->line[a].len > 11 && memcmp(packet->line[a].ptr, "Icy-MetaData", 12) == 0) {
      NDPI_LOG(NDPI_PROTOCOL_MPEG, ndpi_struct, NDPI_LOG_DEBUG, "MPEG: Icy-MetaData found.\n");
      ndpi_int_http_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_MPEG);
      return;
    }
  }
#ifdef NDPI_PROTOCOL_AVI
#endif
#endif

}
Пример #10
0
void RegisterCListFonts()
{
	FontIDT fontid = {0};
	ColourIDT colourid = {0};
	char idstr[10];
	int i;

	fontid.cbSize = sizeof(FontIDT);
	fontid.flags = FIDF_ALLOWREREGISTER | FIDF_APPENDNAME | FIDF_NOAS | FIDF_SAVEPOINTSIZE | FIDF_ALLOWEFFECTS;

	for (i = 0; i <= CLIST_FONTID_MAX; i++) {

		switch (fontListOrder[i])
		{
		case FONTID_GROUPS:
		case FONTID_GROUPCOUNTS:
			fontid.flags &= ~FIDF_CLASSMASK;
			fontid.flags |= FIDF_CLASSHEADER;
			break;
		case FONTID_DIVIDERS:
			fontid.flags &= ~FIDF_CLASSMASK;
			fontid.flags |= FIDF_CLASSSMALL;
			break;
		default:
			fontid.flags &= ~FIDF_CLASSMASK;
			fontid.flags |= FIDF_CLASSGENERAL;
			break;
		}

		strncpy(fontid.dbSettingsGroup, "CLC", sizeof(fontid.dbSettingsGroup));
		_tcsncpy(fontid.group, _T("Contact List"), SIZEOF(fontid.group));
		_tcsncpy(fontid.name, szClistFontIdDescr[fontListOrder[i]], SIZEOF(fontid.name));
		sprintf(idstr, "Font%d", fontListOrder[i]);
		strncpy(fontid.prefix, idstr, SIZEOF(fontid.prefix));
		fontid.order = fontListOrder[i];

		CallService(MS_FONT_REGISTERT, (WPARAM)&fontid, 0);
	}

	// and colours
	colourid.cbSize = sizeof(ColourIDT);
	colourid.order = 0;
	strncpy(colourid.dbSettingsGroup, "CLC", sizeof(colourid.dbSettingsGroup));

	strncpy(colourid.setting, "BkColour", sizeof(colourid.setting));
	_tcsncpy(colourid.name, LPGENT("Background"), SIZEOF(colourid.name));
	_tcsncpy(colourid.group, LPGENT("Contact List"), SIZEOF(colourid.group));
	colourid.defcolour = CLCDEFAULT_BKCOLOUR;
	CallService(MS_COLOUR_REGISTERT, (WPARAM)&colourid, 0);

	strncpy(colourid.setting, "SelTextColour", sizeof(colourid.setting));
	_tcsncpy(colourid.name, LPGENT("Selected Text"), SIZEOF(colourid.name));
	colourid.order = 1;
	colourid.defcolour = CLCDEFAULT_SELTEXTCOLOUR;
	CallService(MS_COLOUR_REGISTERT, (WPARAM)&colourid, 0);

	strncpy(colourid.setting, "HotTextColour", sizeof(colourid.setting));
	_tcsncpy(colourid.name, LPGENT("Hottrack Text"), SIZEOF(colourid.name));
	colourid.order = 1;
	colourid.defcolour = CLCDEFAULT_HOTTEXTCOLOUR;
	CallService(MS_COLOUR_REGISTERT, (WPARAM)&colourid, 0);

	strncpy(colourid.setting, "QuickSearchColour", sizeof(colourid.setting));
	_tcsncpy(colourid.name, LPGENT("Quicksearch Text"), SIZEOF(colourid.name));
	colourid.order = 1;
	colourid.defcolour = CLCDEFAULT_QUICKSEARCHCOLOUR;
	CallService(MS_COLOUR_REGISTERT, (WPARAM)&colourid, 0);

	HookEvent(ME_FONT_RELOAD, FS_FontsChanged);
}
Пример #11
0
int consensus_read_config(node* cur_node,const char* config_path){
    config_t config_file;
    config_init(&config_file);

    if(!config_read_file(&config_file,config_path)){
        goto goto_config_error;
    }
    uint32_t group_size;
    if(!config_lookup_int(&config_file,"group_size",(int*)&group_size)){
        goto goto_config_error;
    }

    cur_node->group_size = group_size;
    cur_node->peer_pool = (peer*)malloc(group_size*sizeof(peer));
    if(NULL==cur_node->peer_pool){
        goto goto_config_error;
    }

    if(group_size<=cur_node->node_id){
        err_log("CONSENSUS : Configuration Reading Error : Invalid Node Id.\n");
        goto goto_config_error;
    }

    config_setting_t *consensus_global_config = NULL;
    consensus_global_config = config_lookup(&config_file,"consensus_global_config");
    
    if(NULL!=consensus_global_config){
        long long temp;
        if(config_setting_lookup_int64(consensus_global_config,"progress_timeval_s",&temp)){
            cur_node->config.make_progress_timeval.tv_sec = temp;
        }
        if(config_setting_lookup_int64(consensus_global_config,"progress_timeval_us",&temp)){
            cur_node->config.make_progress_timeval.tv_usec = temp;
        }
        if(config_setting_lookup_int64(consensus_global_config,"reconnect_timeval_s",&temp)){
            cur_node->config.reconnect_timeval.tv_sec = temp;
        }
        if(config_setting_lookup_int64(consensus_global_config,"reconnect_timeval_us",&temp)){
            cur_node->config.reconnect_timeval.tv_usec = temp;
        }
        if(config_setting_lookup_int64(consensus_global_config,"ping_timeval_s",&temp)){
            cur_node->config.ping_timeval.tv_sec = temp;
        }
        if(config_setting_lookup_int64(consensus_global_config,"ping_timeval_us",&temp)){
            cur_node->config.ping_timeval.tv_usec = temp;
        }
        if(config_setting_lookup_int64(consensus_global_config,"expected_ping_timeval_s",&temp)){
            cur_node->config.expect_ping_timeval.tv_sec = temp;
        }
        if(config_setting_lookup_int64(consensus_global_config,"expected_ping_timeval_us",&temp)){
            cur_node->config.expect_ping_timeval.tv_usec = temp;
        }
    }

    config_setting_t *nodes_config;
    nodes_config = config_lookup(&config_file,"consensus_config");

    if(NULL==nodes_config){
        err_log("CONSENSUS : Cannot Find Nodes Settings.\n");
        goto goto_config_error;
    }    

    if(NULL==nodes_config){
        err_log("CONSENSUS : Cannot Find Net Address Section.\n");
        goto goto_config_error;
    }
    peer* peer_pool = cur_node->peer_pool;
    for(uint32_t i=0;i<group_size;i++){ 
        config_setting_t *node_config = config_setting_get_elem(nodes_config,i);
        if(NULL==node_config){
            err_log("CONSENSUS : Cannot Find Node%u's Address.\n",i);
            goto goto_config_error;
        }

        const char* peer_ipaddr;
        int peer_port;
        if(!config_setting_lookup_string(node_config,"ip_address",&peer_ipaddr)){
            goto goto_config_error;
        }
        if(!config_setting_lookup_int(node_config,"port",&peer_port)){
            goto goto_config_error;
        }
        peer_pool[i].my_node = cur_node;
        peer_pool[i].peer_id = i; 
        peer_pool[i].base = cur_node->base; 
        peer_pool[i].reconnect = NULL;
        peer_pool[i].active = 0;
        peer_pool[i].my_buff_event = NULL;
        peer_pool[i].sock_id = -1;
        peer_pool[i].peer_address = (struct sockaddr_in*)malloc(sizeof(struct
                    sockaddr_in));
        peer_pool[i].sock_len = sizeof(struct sockaddr_in);
        peer_pool[i].peer_address->sin_family =AF_INET;
        inet_pton(AF_INET,peer_ipaddr,&peer_pool[i].peer_address->sin_addr);
        peer_pool[i].peer_address->sin_port = htons(peer_port);

        if(i==cur_node->node_id){
            config_setting_lookup_int(node_config,"sys_log",&cur_node->sys_log);
            config_setting_lookup_int(node_config,"stat_log",&cur_node->stat_log);
            const char* db_name;
            if(!config_setting_lookup_string(node_config,"db_name",&db_name)){
                goto goto_config_error;
            }
            size_t db_name_len = strlen(db_name);
            cur_node->db_name = (char*)malloc(sizeof(char)*(db_name_len+1));
            if(cur_node->db_name==NULL){
                goto goto_config_error;
            }
            if(NULL==strncpy(cur_node->db_name,db_name,db_name_len)){
                free(cur_node->db_name);
                goto goto_config_error;
            }

            cur_node->db_name[db_name_len] = '\0';
            cur_node->my_address.sin_port = htons(peer_port);
            cur_node->my_address.sin_family = AF_INET;
            inet_pton(AF_INET,peer_ipaddr,&cur_node->my_address.sin_addr);
        }
    }

    config_destroy(&config_file);
    return 0;

goto_config_error:
    err_log("CONSENSUS : %s:%d - %s\n", config_error_file(&config_file),
            config_error_line(&config_file), config_error_text(&config_file));
    config_destroy(&config_file);
    return -1;
};
Пример #12
0
int BfastBAFConvert(int argc, char *argv[])
{
	FILE *fpIn=NULL, *fpOut=NULL;
	gzFile fpInGZ=NULL, fpOutGZ=NULL;
	long long int counter;
	char inputFileName[MAX_FILENAME_LENGTH]="\0";
	char outputFileName[MAX_FILENAME_LENGTH]="\0";
	char fastaFileName[MAX_FILENAME_LENGTH]="\0";
	char outputID[MAX_FILENAME_LENGTH]="\0";
	char *readGroupFileName=NULL, *readGroup=NULL, *readGroupString=NULL;
	char *last;
	int outputType=1; // BAF2TEXT
	int outputSubType=TextOutput;
	int inputType=BinaryInput;
	int c, argnum;
	AlignedRead a;
	RGBinary rg;
	char fileExtension[256]="\0";

	// Get parameters
	while((c = getopt(argc, argv, "f:o:r:O:h")) >= 0) {
		switch(c) {
			case 'O': outputType = atoi(optarg); break;
			case 'f': strcpy(fastaFileName, optarg); break;
			case 'o': strcpy(outputID, optarg); break;
			case 'r': readGroupFileName=strdup(optarg); break;
			case 'h':
					  BfastBAFConvertUsage(); return 1;
			default: fprintf(stderr, "Unrecognized option: -%c\n", c); return 1;
		}
	}

	if(argc == optind) {
		BfastBAFConvertUsage(); return 1;
	}

	/* Only read in the brg if necessary */
	switch(outputType) {
		case 2:
		case 3:
		case 4:
			if(0 == strlen(fastaFileName)) {
				PrintError(Name, "fastaFileName", "Required command line argument", Exit, InputArguments);
			}
			RGBinaryReadBinary(&rg,
					NTSpace,
					fastaFileName);
			break;
		default:
			break;
	}

	/* Set types and file extension */
	switch(outputType) {
		case 0:
			outputType=BAF;
			inputType=TextInput;
			outputSubType=BinaryOutput;
			strcat(fileExtension, BFAST_ALIGNED_FILE_EXTENSION);
			break;
		case 1:
			outputType=BAF;
			inputType=BinaryInput;
			outputSubType=TextOutput;
			strcat(fileExtension, "txt");
			break;
		case 2:
			outputType=SAM;
			inputType=BinaryInput;
			outputSubType=TextOutput;
			strcat(fileExtension, BFAST_SAM_FILE_EXTENSION);
			if(NULL != readGroupFileName) {
				readGroup=ReadInReadGroup(readGroupFileName);
				readGroupString=ParseReadGroup(readGroup);
			}
			break;
		default:
			PrintError(Name, NULL, "Could not understand output type", Exit, OutOfRange);
	}

	for(argnum=optind;argnum<argc;argnum++) {
		strcpy(inputFileName, argv[argnum]);

		/* Create output file name */
		last = StrStrGetLast(inputFileName,
				BFAST_ALIGNED_FILE_EXTENSION);
		if(NULL == last) {
			last = StrStrGetLast(inputFileName, "txt");
			if(NULL == last) {
				PrintError(Name, inputFileName, "Could not recognize file extension", Exit, OutOfRange);
			}
		}

		outputFileName[0]='\0';
		strncpy(outputFileName, inputFileName, (last - inputFileName));
		outputFileName[(last-inputFileName)]='\0';
		strcat(outputFileName, fileExtension);

		/* Open the input file */
		if(BinaryInput == inputType) {
			if(!(fpInGZ=gzopen(inputFileName, "rb"))) {
				PrintError(Name, inputFileName, "Could not open file for reading", Exit, OpenFileError);
			}
		}
		else {
			if(!(fpIn=fopen(inputFileName, "rb"))) {
				PrintError(Name, inputFileName, "Could not open file for reading", Exit, OpenFileError);
			}
		}
		/* Open the output file */
		if(BinaryOutput == outputSubType) {
			if(!(fpOutGZ=gzopen(outputFileName, "wb"))) {
				PrintError(Name, outputFileName, "Could not open file for writing", Exit, OpenFileError);
			}
		}
		else {
			if(!(fpOut=fopen(outputFileName, "wb"))) {
				PrintError(Name, outputFileName, "Could not open file for writing", Exit, OpenFileError);
			}
		}

		fprintf(stderr, "Input:%s\nOutput:%s\n", inputFileName, outputFileName);

		/* Print Header */
		AlignedReadConvertPrintHeader(fpOut, &rg, outputType, readGroup);
		/* Initialize */
		AlignedReadInitialize(&a);
		counter = 0;
		fprintf(stderr, "Currently on:\n0");
		/* Read in each match */
		while((TextInput == inputType && EOF != AlignedReadReadText(&a, fpIn)) ||
				(BinaryInput == inputType && EOF != AlignedReadRead(&a, fpInGZ))) {
			if(counter%BAFCONVERT_ROTATE_NUM==0) {
				fprintf(stderr, "\r%lld",
						counter);
			}
			counter++;
			/* Print each match */
			AlignedReadConvertPrintOutputFormat(&a,
					&rg,
					fpOut,
					fpOutGZ,
					outputID,
					readGroupString,
					-1,
					NULL,
					outputType,
					1,
                                        0,
					outputSubType);
			AlignedReadFree(&a);
		}
		fprintf(stderr, "\r%lld\n",
				counter);
		/* Close the input file */
		if(TextInput == inputType) {
			fclose(fpIn);
		}
		else {
			gzclose(fpInGZ);
		}
		/* Close the output file */
		if(TextOutput == outputSubType) {
			fclose(fpOut);
		}
		else {
			gzclose(fpOutGZ);
		}
	}
	if(SAM == outputType) {
		RGBinaryDelete(&rg);
	}
	free(readGroupFileName);
	free(readGroup);
	free(readGroupString);

	fprintf(stderr, "Terminating successfully!\n");
	return 0;
}
Пример #13
0
gint dvtmcf1_r1(class dvtmcf1_r_data *data)
{
    time_t vremn;
    time(&vremn);
    char strsql[1024];
    iceb_u_str repl;
    iceb_clock sss(data->window);





    short ostkg=0;

    iceb_poldan("Отчет в килограммах",strsql,"matnast.alx",data->window);
    if(iceb_u_SRAV(strsql,"Вкл",1) == 0)
        ostkg=1;

    sprintf(strsql,"select * from Kart");
    SQLCURSOR cur,curtmp;
    SQLCURSOR cur1;
    SQL_str row,rowtmp;
    SQL_str row1;

    int kolstr;

    if((kolstr=cur.make_cursor(&bd,strsql)) < 0)
        iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window);

    if(kolstr == 0)
    {
        iceb_menu_soob(gettext("Не найдено ни одной записи !"),data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    class iceb_tmptab tabtmp;
    const char *imatmptab= {"dvtmcf1"};

    char zaprostmp[512];
    memset(zaprostmp,'\0',sizeof(zaprostmp));

    sprintf(zaprostmp,"CREATE TEMPORARY TABLE %s (\
sh char(24) not null,\
skl int not null,\
kgm int not null,\
naim char(112) not null,\
km int not null,\
nk int not null,\
ei char(24) not null,\
cena double(15,6) not null,\
nds float(2) not null,\
mnds smallint not null,\
fas float(2) not null)",imatmptab);


    if(tabtmp.create_tab(imatmptab,zaprostmp,data->window) != 0)
    {
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }
    /*********
    char imaftmp[32];
    FILE *ff1;

    sprintf(imaftmp,"dv%d.tmp",getpid());
    if((ff1 = fopen(imaftmp,"w")) == NULL)
     {
      iceb_er_op_fil(imaftmp,"",errno,data->window);
      sss.clear_data();
      gtk_widget_destroy(data->window);
      return(FALSE);
     }
    **************/
    short dn,mn,gn;
    short dk,mk,gk;

    iceb_rsdatp(&dn,&mn,&gn,data->rk->datan.ravno(),&dk,&mk,&gk,data->rk->datak.ravno(),data->window);

    sprintf(strsql,"%s\n%s %d.%d.%d %s %d.%d.%d\n",
            gettext("Сортируем записи"),
            gettext("Период с"),
            dn,mn,gn,
            gettext("по"),
            dk,mk,gk);

    iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

    int kgrm=0;
//int kolstr2=0;
    float kolstr1=0.;
    class iceb_u_str naim("");

    while(cur.read_cursor(&row) != 0)
    {
        iceb_pbar(data->bar,kolstr,++kolstr1);

        if(iceb_u_proverka(data->rk->sklad.ravno(),row[0],0,0) != 0)
            continue;

        if(iceb_u_proverka(data->rk->shet.ravno(),row[5],0,0) != 0)
            continue;

        kgrm=0;
        naim.new_plus("");
        /*Читаем код группы материалла*/
        sprintf(strsql,"select kodgr,naimat from Material where kodm=%s",row[2]);
        if(sql_readkey(&bd,strsql,&row1,&cur1) != 1)
        {
            printf("%s %s !\n",gettext("Не найден код материалла"),row[2]);
            continue;
        }
        else
        {
            kgrm=atoi(row1[0]);
            naim.new_plus(row1[1]);
        }

        if(iceb_u_proverka(data->rk->grupa.ravno(),row1[0],0,0) != 0)
            continue;

        if(provndsw(data->rk->nds.ravno(),row) != 0)
            continue;

        if(iceb_u_proverka(data->rk->kodmat.ravno(),row[2],0,0) != 0)
            continue;

//  kolstr2++;
        /************
          fprintf(ff1,"%s|%s|%d|%s|%s|%s|%s|%.10g|%.5g|%s|%s|\n",
          row[5],row[0],kgrm,naim.ravno(),row[2],row[1],row[4],atof(row[6]),atof(row[9]),
          row[3],row[10]);
        *************/
        sprintf(strsql,"insert into %s values ('%s',%s,%d,'%s',%s,%s,'%s',%.10g,%.5g,%s,%s)",
                imatmptab,
                row[5],row[0],kgrm,naim.ravno_filtr(),row[2],row[1],row[4],atof(row[6]),atof(row[9]),
                row[3],row[10]);
        iceb_sql_zapis(strsql,1,0,data->window);

    }

//fclose(ff1);


    if(data->rk->metka_sort == 0) //Сортировать счет-склад-наименование материалла.
    {
//  sprintf(strsql,"sort -o %s -t\\| -k1,2 -k2,3n -k4,5 %s",imaftmp,imaftmp);
//  sprintf(strsql,"sort -o %s -t\\| +0 -1 +1n -2 +3 -4 %s",imaftmp,imaftmp);
        sprintf(strsql,"select * from %s order by sh asc,skl asc,naim asc",imatmptab);
    }
    if(data->rk->metka_sort == 1) //Сортировать счет-склад-группа-наименование материалла.
    {
//  sprintf(strsql,"sort -o %s -t\\| -k1,2 -k2,3n -k3,4n -k4,5 %s",imaftmp,imaftmp);
//  sprintf(strsql,"sort -o %s -t\\| +0 -1 +1n -2 +2n -3 +3 -4 %s",imaftmp,imaftmp);
        sprintf(strsql,"select * from %s order by sh asc,skl asc,kgm asc,naim asc",imatmptab);
    }
//system(strsql); //Запуск сортировки
    int kolstrtmp=0;
    if((kolstrtmp=curtmp.make_cursor(&bd,strsql)) < 0)
    {
        iceb_msql_error(&bd,gettext("Ошибка создания курсора !"),strsql,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    sprintf(strsql,"%s.\n",gettext("Делаем отчет"));
    iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);
    /**************
    if((ff1 = fopen(imaftmp,"r")) == NULL)
     {
      iceb_er_op_fil(imaftmp,"",errno,data->window);
      gtk_widget_destroy(data->window);
      return(FALSE);
     }
    *************/
    FILE *ff;
    char imaf[32];

    sprintf(imaf,"zag%d.lst",getpid());
    data->rk->imaf.plus(imaf);

    repl.new_plus(gettext("Оборотная ведомость движния товарно-материальных ценностей"));
    repl.plus(" (");
    repl.plus(gettext("формат"));
    repl.plus(" A3)");

    data->rk->naimf.plus(repl.ravno());

    if((ff = fopen(imaf,"w")) == NULL)
    {
        iceb_er_op_fil(imaf,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }
    FILE *ffuz;
    char imafuz[32];

    sprintf(imafuz,"zaguz%d.lst",getpid());
    data->rk->imaf.plus(imafuz);

    repl.new_plus(gettext("Оборотная ведомость движния товарно-материальных ценностей"));
    repl.plus(" (");
    repl.plus(gettext("формат"));
    repl.plus(" A4)");

    data->rk->naimf.plus(repl.ravno());

    if((ffuz = fopen(imafuz,"w")) == NULL)
    {
        iceb_er_op_fil(imafuz,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }

    /***************
    if(tipras == 1)
     {
      sprintf(imafkl2,"zagg%d.lst",getpid());

      if((ffkl2 = fopen(imafkl2,"w")) == NULL)
       ERROR1(gettext("Ошибка открытия файла"),errno,imafkl2);
      startfil(ffkl2);
     }
    else
     {
    *****************/
    char imafitog[32];
    sprintf(imafitog,"zai%d.lst",getpid());
    data->rk->imaf.plus(imafitog);

    data->rk->naimf.plus(gettext("Свод движения материальных ценностей"));
    FILE *ffitog;
    if((ffitog = fopen(imafitog,"w")) == NULL)
    {
        iceb_er_op_fil(imafitog,"",errno,data->window);
        sss.clear_data();
        gtk_widget_destroy(data->window);
        return(FALSE);
    }


    iceb_u_zagolov(gettext("Свод движения материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ffitog);


    iceb_u_zagolov(gettext("Оборотная ведомость движния товарно-материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ff);
    iceb_u_zagolov(gettext("Оборотная ведомость движния товарно-материальных ценностей"),dn,mn,gn,dk,mk,gk,organ,ffuz);


    int kst=4;

    if(data->rk->shet.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Счёт"),data->rk->shet.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Счёт"),data->rk->shet.ravno());
        kst++;
    }
    if(data->rk->sklad.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Склад"),data->rk->sklad.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Склад"),data->rk->sklad.ravno());
        kst++;
    }
    if(data->rk->grupa.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Група"),data->rk->grupa.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Група"),data->rk->grupa.ravno());
        kst++;
    }

    if(data->rk->kodmat.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("Код материалла"),data->rk->kodmat.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("Код материалла"),data->rk->kodmat.ravno());
        kst++;
    }
    if(data->rk->nds.getdlinna() > 1)
    {
        fprintf(ff,"%s:%s\n",gettext("НДС"),data->rk->nds.ravno());
        fprintf(ffuz,"%s:%s\n",gettext("НДС"),data->rk->nds.ravno());
        kst++;
    }
    char shbm[32];
    char naiskl[112];

    memset(shbm,'\0',sizeof(shbm));
    memset(naiskl,'\0',sizeof(naiskl));
    int skl=0;
    int sli=1;
    double itg1=0.,itg2=0.,itg3=0.,itg4=0.,itg5=0.,itg6=0.,itg7=0.,itg8=0.;
    double k1=0.,s1=0.,k2=0.,s2=0.,k3=0.,s3=0.,k4=0.,s4=0.;
    double kk1=0.,ss1=0.,kk2=0.,ss2=0.,kk3=0.,ss3=0.,kk4=0.,ss4=0.;
    double kg0=0.,kg1=0.,kg2=0.,kg3=0.;
    double kgs0=0.,kgs1=0.,kgs2=0.,kgs3=0.;
    int kgrmzp=0;
    char str[512];
    memset(str,'\0',sizeof(str));
    memset(str,'.',233);
    int mvsh=0;
    kolstr1=0;
//char str1[1000];
    class ostatok ost;
    char shb[20];
    int skl1;
    int kodm;
    int nk;
    char ei[32];
    char		mnds='\0';
    double cena,nds;
    char naimshet[512];
    char nomn[112];

//while(fgets(str1,sizeof(str1),ff1) != NULL)
// {
    while(curtmp.read_cursor(&rowtmp) != 0)
    {
        iceb_pbar(data->bar,kolstrtmp,++kolstr1);

        /********
          iceb_u_pole(str1,shb,1,'|');
          iceb_u_pole(str1,strsql,2,'|');
          skl1=atoi(strsql);
          iceb_u_pole(str1,strsql,3,'|');
          kgrm=atoi(strsql);

          iceb_u_pole(str1,naim,4,'|');
          iceb_u_pole(str1,strsql,5,'|');
          kodm=atoi(strsql);
          iceb_u_pole(str1,strsql,6,'|');
          nk=atoi(strsql);
        **************/
        strncpy(shb,rowtmp[0],sizeof(shb)-1);
        skl1=atoi(rowtmp[1]);
        kgrm=atoi(rowtmp[2]);
        naim.new_plus(rowtmp[3]);
        kodm=atoi(rowtmp[4]);
        nk=atoi(rowtmp[5]);

        /*Остаток по карточкам*/
        ostkarw(dn,mn,gn,dk,mk,gk,skl1,nk,&ost);

        if(ost.ostm[0] == 0. && ost.ostm[1] == 0. && ost.ostm[3] == 0. && fabs(ost.ostmc[3]) < 0.009)
            continue;
        /************
          iceb_u_pole(str1,ei,7,'|');
          iceb_u_pole(str1,strsql,8,'|');
          cena=atof(strsql);
          iceb_u_pole(str1,strsql,9,'|');
          nds=atof(strsql);

          iceb_u_pole(str1,strsql,10,'|');
        ***********/
        strncpy(ei,rowtmp[6],sizeof(ei)-1);
        cena=atof(rowtmp[7]);
        nds=atof(rowtmp[8]);
        strncpy(strsql,rowtmp[9],sizeof(strsql)-1);

        if(atoi(strsql) == 0)
            mnds=' ';
        if(atoi(strsql) == 1)
            mnds='+';

        if(kgrmzp != kgrm)
        {
            if(kgrmzp != 0)
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        kst+=2;
                    }
            }
            itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
            kgrmzp=kgrm;
        }

        if(iceb_u_SRAV(shb,shbm,1) != 0)
        {
            if(shbm[0] != '\0')
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
                        kst+=2;
                    }
                itskl(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((kk1+kk2+kk3+kk4) - (kg0+kg1+kg2+kg3)) > 0.0001 &&
                        kg0+kg1+kg2+kg3 > 0.0001)
                {
                    itkg(shbm,skl,kg0,kg1,kg2,kg3,1,ffuz,ff);
                    kst+=2;
                    kg0=kg1=kg2=kg3=0.;
                }
                itsh(shbm,k1,k2,k3,k4,s1,s2,s3,s4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((k1+k2+k3+k4) - (kgs0+kgs1+kgs2+kgs3)) > 0.0001 &&
                        kgs0+kgs1+kgs2+kgs3 > 0.0001)
                {
                    itkg(shbm,skl,kgs0,kgs1,kgs2,kgs3,0,ffuz,ff);
                    kst+=2;
                    kgs0=kgs1=kgs2=kgs3=0.;
                }
                skl=0;
                /****************
                      if(tipras == 1)
                       {
                	itskl1(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,str,ff,ffkl2);
                	skl=0;
                	itsh1(shbm,k1,k2,k3,k4,s1,s2,s3,s4,str,ff,ffkl2);
                	kst+=4;
                       }
                *******************/
            }
            k1=s1=k2=s2=k3=s3=k4=s4=0.;

            /*Читаем наименование счета*/
            memset(naimshet,'\0',sizeof(naimshet));
            sprintf(strsql,"select nais from Plansh where ns='%s'",shb);
            if(sql_readkey(&bd,strsql,&row,&cur1) != 1)
            {
                printf("Не найден счет %s в плане счетов !\n",shb);
                fprintf(ff,"%s %s !\n",gettext("Не найден счет"),shb);
            }
            else
                strncpy(naimshet,row[0],sizeof(naimshet)-1);

            sprintf(strsql,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

            if(kst > kol_strok_na_liste - 10)
            {
                fprintf(ff,"\f");
                fprintf(ffuz,"\f");
//      if(ffkl2 != NULL)
//         fprintf(ffkl2,"\f");
                kst=0;
                sli++;
            }


            fprintf(ff,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            fprintf(ffuz,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            if(ffitog != NULL)
                fprintf(ffitog,"\n%s %s \"%s\"\n",gettext("Счет"),shb,naimshet);
            kst+=2;
//    if(tipras == 0)
            gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);
//    else
//     gsapp2(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,str,ff,ffkl2);

            mvsh=1;

            strcpy(shbm,shb);
        }

        if(skl != skl1)
        {
            if(skl != 0)
            {
                if(data->rk->metka_sort == 1)
                    if(itg1 != 0. || itg2 != 0. || itg3 != 0. || itg4 != 0.)
                    {
                        itgrup(kgrmzp,itg1,itg2,itg3,itg4,itg5,itg6,itg7,itg8,ffuz,0,ff);
                        itg1=itg2=itg3=itg4=itg5=itg6=itg7=itg8=0.;
                        kst+=2;
                    }

                itskl(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,ffuz,ff,ffitog,data);
                kst+=2;
                if(ostkg == 1 && fabs((kk1+kk2+kk3+kk4) - (kg0+kg1+kg2+kg3)) > 0.0001 &&
                        kg0+kg1+kg2+kg3 > 0.0001)
                {
                    itkg(shbm,skl,kg0,kg1,kg2,kg3,1,ffuz,ff);
                    kst+=2;
                    kg0=kg1=kg2=kg3=0.;
                }

//      if(tipras == 1)
//       {
//	itskl1(skl,kk1,kk2,kk3,kk4,ss1,ss2,ss3,ss4,str,ff,ffkl2);
//        kst+=2;
//       }
            }
            kk1=ss1=kk2=ss2=kk3=ss3=kk4=ss4=0.;

            /*Читаем наименование склада*/
            memset(naiskl,'\0',sizeof(naiskl));
            sprintf(strsql,"select naik from Sklad where kod='%d'",skl1);
            if(sql_readkey(&bd,strsql,&row,&cur1) != 1)
            {
                printf("Не найден склад %d в списке складов\n",skl1);
                fprintf(ff,"%s %d !\n",gettext("Не найден склад"),skl1);
            }
            strncpy(naiskl,row[0],sizeof(naiskl));

            sprintf(strsql,"%s: %d %s\n",gettext("Склад"),skl1,naiskl);
            iceb_printw(iceb_u_toutf(strsql),data->buffer,data->view);

            if(kst != 0)
                if(kst > kol_strok_na_liste - 10)
                {
                    fprintf(ff,"\f");
                    fprintf(ffuz,"\f");
//      if(ffkl2 != NULL)
//         fprintf(ffkl2,"\f");
                    kst=0;
                    sli++;
                }
            mvsh=1;
            skl=skl1;

        }
        if(mvsh == 1)
        {
//    if(tipras == 0)
//     {
            shdtmcf1(dn,mn,gn,dk,mk,gk,sli,ff,skl,naiskl,ffuz);
            kst+=6;
//     }
            /***************
                if(tipras == 1)
                 {
                  shdtmcf1k(dn,mn,gn,sli,ff,skl,naiskl,ffkl2);
                  kst+=6;
                 }
            ***************/
            mvsh=0;
        }


        /*Остаток по карточкам*/
//  ostkar(dn,mn,gn,dk,mk,gk,skl1,nk,ostg,ostm,ostgc,ostmc);

//  sprintf(nomn,"%d.%s.%d.%d",skl1,shb,kgrm,nk);
        sprintf(nomn,"%s.%d.%d",shb,kgrm,nk);


//  if(tipras == 0)
//   {
        gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);

        fprintf(ff,"\
%4d %-*.*s %-*s %-*s %c%2.2g %14.10g %15.10g %15.2f %15.10g %15.2f %15.10g %15.2f \
%15.10g %15.2f\n",
                kodm,
                iceb_u_kolbait(40,naim.ravno()),iceb_u_kolbait(40,naim.ravno()),naim.ravno(),
                iceb_u_kolbait(13,nomn),nomn,
                iceb_u_kolbait(10,ei),ei,
                mnds,nds,cena,
                ost.ostm[0],ost.ostmc[0],ost.ostm[1],ost.ostmc[1],ost.ostm[2],ost.ostmc[2],ost.ostm[3],ost.ostmc[3]);

        fprintf(ffuz,"\
%4d %-*.*s %-*s %-*s %c%2.2g %7s %8.8g %8.2f %8.8g %8.2f %8.8g %8.2f \
%8.8g %8.2f\n",
                kodm,
                iceb_u_kolbait(23,naim.ravno()),iceb_u_kolbait(23,naim.ravno()),naim.ravno(),
                iceb_u_kolbait(13,nomn),nomn,
                iceb_u_kolbait(3,ei),ei,
                mnds,nds,iceb_prcn(cena),
                ost.ostm[0],ost.ostmc[0],ost.ostm[1],ost.ostmc[1],ost.ostm[2],ost.ostmc[2],ost.ostm[3],ost.ostmc[3]);


        if(ostkg == 1)
        {
            double ost1=0.,ost2=0.,ost3=0.,ost4=0.;
            double fas=0.;
//       iceb_u_pole(str1,strsql,11,'|');
//       fas=atof(strsql);
            fas=atof(rowtmp[10]);
            if(fas > 0.0000001)
            {
                ost1=ost.ostm[0]*fas;
                ost2=ost.ostm[1]*fas;
                ost3=ost.ostm[2]*fas;
                ost4=ost.ostm[3]*fas;
                kg0+=ost1;
                kg1+=ost2;
                kg2+=ost3;
                kg3+=ost4;
                kgs0+=ost1;
                kgs1+=ost2;
                kgs2+=ost3;
                kgs3+=ost4;

                gsapp(dn,mn,gn,dk,mk,gk,&sli,&kst,skl1,naiskl,ffuz,ff);

                fprintf(ff,"\
%4s %-40.40s %-13s %-10s %3s %14s %15.10g %15s %15.10g %15s %15.10g %15s \
%15.10g %15s\n"," "," "," "," "," "," ",
                        ost1," ",ost2," ",ost3," ",ost4," ");

                fprintf(ffuz,"\
%4s %-23.23s %-13s %-3s %3s %7s %8.8g %8s %8.8g %8s %8.8g %8s \
%8.8g %8s\n"," "," "," "," "," "," ",
                        ost1," ",ost2," ",ost3," ",ost4," ");

            }
            else if(iceb_u_SRAV(ei,"Кг",0) == 0 || iceb_u_SRAV(ei,"кг",0) == 0 ||
Пример #14
0
static int
vhost_bdev_scsi_inquiry_command(struct vhost_block_dev *bdev,
				struct vhost_scsi_task *task)
{
	int hlen = 0;
	uint32_t alloc_len = 0;
	uint16_t len = 0;
	uint16_t *temp16;
	int pc;
	int pd;
	int evpd;
	int i;
	uint8_t *buf;
	struct scsi_cdb_inquiry *inq;

	inq = (struct scsi_cdb_inquiry *)task->req->cdb;

	assert(task->iovs_cnt == 1);

	/* At least 36Bytes for inquiry command */
	if (task->data_len < 0x24)
		goto inq_error;

	pd = SPC_PERIPHERAL_DEVICE_TYPE_DISK;
	pc = inq->page_code;
	evpd = inq->evpd & 0x1;

	if (!evpd && pc)
		goto inq_error;

	if (evpd) {
		struct scsi_vpd_page *vpage = (struct scsi_vpd_page *)
					      task->iovs[0].iov_base;

		/* PERIPHERAL QUALIFIER(7-5) PERIPHERAL DEVICE TYPE(4-0) */
		vpage->peripheral = pd;
		/* PAGE CODE */
		vpage->page_code = pc;

		switch (pc) {
		case SPC_VPD_SUPPORTED_VPD_PAGES:
			hlen = 4;
			vpage->params[0] = SPC_VPD_SUPPORTED_VPD_PAGES;
			vpage->params[1] = SPC_VPD_UNIT_SERIAL_NUMBER;
			vpage->params[2] = SPC_VPD_DEVICE_IDENTIFICATION;
			len = 3;
			/* PAGE LENGTH */
			vpage->alloc_len = rte_cpu_to_be_16(len);
			break;
		case SPC_VPD_UNIT_SERIAL_NUMBER:
			hlen = 4;
			strncpy((char *)vpage->params, bdev->name, 32);
			vpage->alloc_len = rte_cpu_to_be_16(32);
			break;
		case SPC_VPD_DEVICE_IDENTIFICATION:
			buf = vpage->params;
			struct scsi_desig_desc *desig;

			hlen = 4;
			/* NAA designator */
			desig = (struct scsi_desig_desc *)buf;
			desig->code_set = SPC_VPD_CODE_SET_BINARY;
			desig->protocol_id = SPC_PROTOCOL_IDENTIFIER_ISCSI;
			desig->type = SPC_VPD_IDENTIFIER_TYPE_NAA;
			desig->association = SPC_VPD_ASSOCIATION_LOGICAL_UNIT;
			desig->reserved0 = 0;
			desig->piv = 1;
			desig->reserved1 = 0;
			desig->len = 8;
			vhost_bdev_scsi_set_naa_ieee_extended(bdev->name,
							      desig->desig);
			len = sizeof(struct scsi_desig_desc) + 8;

			buf += sizeof(struct scsi_desig_desc) + desig->len;

			/* T10 Vendor ID designator */
			desig = (struct scsi_desig_desc *)buf;
			desig->code_set = SPC_VPD_CODE_SET_ASCII;
			desig->protocol_id = SPC_PROTOCOL_IDENTIFIER_ISCSI;
			desig->type = SPC_VPD_IDENTIFIER_TYPE_T10_VENDOR_ID;
			desig->association = SPC_VPD_ASSOCIATION_LOGICAL_UNIT;
			desig->reserved0 = 0;
			desig->piv = 1;
			desig->reserved1 = 0;
			desig->len = 8 + 16 + 32;
			strncpy((char *)desig->desig, "INTEL", 8);
			vhost_strcpy_pad((char *)&desig->desig[8],
					 bdev->product_name, 16, ' ');
			strncpy((char *)&desig->desig[24], bdev->name, 32);
			len += sizeof(struct scsi_desig_desc) + 8 + 16 + 32;

			buf += sizeof(struct scsi_desig_desc) + desig->len;

			/* SCSI Device Name designator */
			desig = (struct scsi_desig_desc *)buf;
			desig->code_set = SPC_VPD_CODE_SET_UTF8;
			desig->protocol_id = SPC_PROTOCOL_IDENTIFIER_ISCSI;
			desig->type = SPC_VPD_IDENTIFIER_TYPE_SCSI_NAME;
			desig->association = SPC_VPD_ASSOCIATION_TARGET_DEVICE;
			desig->reserved0 = 0;
			desig->piv = 1;
			desig->reserved1 = 0;
			desig->len = snprintf((char *)desig->desig,
					      255, "%s", bdev->name);
			len += sizeof(struct scsi_desig_desc) + desig->len;

			buf += sizeof(struct scsi_desig_desc) + desig->len;
			vpage->alloc_len = rte_cpu_to_be_16(len);
			break;
		default:
			goto inq_error;
		}

	} else {
		struct scsi_cdb_inquiry_data *inqdata =
			(struct scsi_cdb_inquiry_data *)task->iovs[0].iov_base;
		/* Standard INQUIRY data */
		/* PERIPHERAL QUALIFIER(7-5) PERIPHERAL DEVICE TYPE(4-0) */
		inqdata->peripheral = pd;

		/* RMB(7) */
		inqdata->rmb = 0;

		/* VERSION */
		/* See SPC3/SBC2/MMC4/SAM2 for more details */
		inqdata->version = SPC_VERSION_SPC3;

		/* NORMACA(5) HISUP(4) RESPONSE DATA FORMAT(3-0) */
		/* format 2 */ /* hierarchical support */
		inqdata->response = 2 | 1 << 4;

		hlen = 5;

		/* SCCS(7) ACC(6) TPGS(5-4) 3PC(3) PROTECT(0) */
		/* Not support TPGS */
		inqdata->flags = 0;

		/* MULTIP */
		inqdata->flags2 = 0x10;

		/* WBUS16(5) SYNC(4) LINKED(3) CMDQUE(1) VS(0) */
		/* CMDQUE */
		inqdata->flags3 = 0x2;

		/* T10 VENDOR IDENTIFICATION */
		strncpy((char *)inqdata->t10_vendor_id, "INTEL", 8);

		/* PRODUCT IDENTIFICATION */
		snprintf((char *)inqdata->product_id,
				RTE_DIM(inqdata->product_id), "%s",
				bdev->product_name);

		/* PRODUCT REVISION LEVEL */
		strncpy((char *)inqdata->product_rev, "0001", 4);

		/* Standard inquiry data ends here. Only populate
		 * remaining fields if alloc_len indicates enough
		 * space to hold it.
		 */
		len = INQ_OFFSET(product_rev) - 5;

		if (alloc_len >= INQ_OFFSET(vendor)) {
			/* Vendor specific */
			memset(inqdata->vendor, 0x20, 20);
			len += sizeof(inqdata->vendor);
		}

		if (alloc_len >= INQ_OFFSET(ius)) {
			/* CLOCKING(3-2) QAS(1) IUS(0) */
			inqdata->ius = 0;
			len += sizeof(inqdata->ius);
		}

		if (alloc_len >= INQ_OFFSET(reserved)) {
			/* Reserved */
			inqdata->reserved = 0;
			len += sizeof(inqdata->reserved);
		}

		/* VERSION DESCRIPTOR 1-8 */
		if (alloc_len >= INQ_OFFSET(reserved) + 2) {
			temp16 = (uint16_t *)&inqdata->desc[0];
			*temp16 = rte_cpu_to_be_16(0x0960);
			len += 2;
		}

		if (alloc_len >= INQ_OFFSET(reserved) + 4) {
			/* SPC-3 (no version claimed) */
			temp16 = (uint16_t *)&inqdata->desc[2];
			*temp16 = rte_cpu_to_be_16(0x0300);
			len += 2;
		}

		if (alloc_len >= INQ_OFFSET(reserved) + 6) {
			/* SBC-2 (no version claimed) */
			temp16 = (uint16_t *)&inqdata->desc[4];
			*temp16 = rte_cpu_to_be_16(0x0320);
			len += 2;
		}

		if (alloc_len >= INQ_OFFSET(reserved) + 8) {
			/* SAM-2 (no version claimed) */
			temp16 = (uint16_t *)&inqdata->desc[6];
			*temp16 = rte_cpu_to_be_16(0x0040);
			len += 2;
		}

		if (alloc_len > INQ_OFFSET(reserved) + 8) {
			i = alloc_len - (INQ_OFFSET(reserved) + 8);
			if (i > 30)
				i = 30;
			memset(&inqdata->desc[8], 0, i);
			len += i;
		}

		/* ADDITIONAL LENGTH */
		inqdata->add_len = len;
	}

	/* STATUS GOOD */
	scsi_task_set_status(task, SCSI_STATUS_GOOD, 0, 0, 0);
	return hlen + len;

inq_error:
	scsi_task_set_status(task, SCSI_STATUS_CHECK_CONDITION,
				     SCSI_SENSE_ILLEGAL_REQUEST,
				     SCSI_ASC_INVALID_FIELD_IN_CDB,
				     SCSI_ASCQ_CAUSE_NOT_REPORTABLE);
	return 0;
}
Пример #15
0
int encrypt_vec_to_file( int vsizelocal, const char * input_file_name, const char * output_file_name, const char * key_file_name)
{
	int input_size = 0, i, temp;
	mpz_t *vec1;
	char* temp_str = NULL;
	FILE *input_file, *output_file;


	vsize = vsizelocal;
	input_file = fopen(input_file_name, "r");
	output_file = fopen(output_file_name, "w");

	strncpy(g_key_file_name, key_file_name, sizeof(g_key_file_name));

	printf("Number of vector dimensions = %d\n", vsizelocal);
	//printf("p_vec2:%p, ENOMEM:%d\n", p_vec2, (errno == ENOMEM)?1:0);



	//initialize vectors and big number variables
	//Dynamically creating the array
	vec1 = (mpz_t *)malloc(vsizelocal*sizeof(mpz_t));

	//We have to write encrypted values to file
	//to hold each value in string before we need
	//a large string to copy the big number
	//Although the key size is 4096 bits,
	//we will allocate the chars capable of storing
	//8192 bit values. No. of chars required = 
	//log(2^{8192}) base 10 = keysize*log 2 = 8192 * log 2 = 2466.03<2500
	temp_str = (char *)malloc(BIG_NUM_SZ);

	//initialize vectors and big number variables
	for (i = 0; i < vsizelocal; i++)
		mpz_init(*(vec1+i));

	//variables are set to 0

	init();

	for (i = 0; i < vsizelocal; i++)
	{
		mpz_init(*(vec1+i));
	}

	//variables are set to 0

	//init();



	//check if files are opened properly
	if (input_file == NULL) {
		printf("\n%s", "Error: open input_file!");
		return -2;
	}

	if (output_file == NULL) {
		printf("\n%s", "Error: open output_file!");
		return -3;
	}

	//fill in the first vector
	for( fscanf(input_file,"%d", &temp); temp != EOF && input_size < vsizelocal; 
			fscanf(input_file, "%d", &temp) ){

		//temp = (int) temp2;
		//printf("doc1:: temp2: %" PRId64 ", temp:%d\n", temp2, temp);
		printf("doc1::Wt:%d\n", temp);

		encrypt(*(vec1+input_size), temp);
		//gmp_printf("No. of chars:%d, BIGNO:%s\n", gmp_sprintf(temp_str, "%Zd", *(vec1+input_size)), temp_str);
		//TODO: Optimization area use fprintf directly using %Zd instead of temp_str. No memory needed.
		gmp_sprintf(temp_str, "%Zd", *(vec1+input_size));
		//decrypt(vec1[input_size]);
		//gmp_printf("%d: %Zd\n", input_size, *(vec1+input_size));
		fprintf(output_file, "%s", temp_str);
		fflush(output_file);
		sync();
		input_size ++;
		if ( vsizelocal!=1 && input_size < vsizelocal )
		{
			fprintf(output_file, "\n");
		}
	} 




	fclose(input_file);  
	fflush(output_file);
	fclose(output_file);

	//release space used by big number variables
	for (i = 0; i < vsizelocal; i++)
		mpz_clear(*(vec1+i));


	clear();
	free(vec1);
	free(temp_str);

	return 0;

}
Пример #16
0
void WebTask::SetURL( char *url )
{
	// サーバーのURLを設定
	//
	strncpy( req_url, url, 1024 );
}
Пример #17
0
/**
 * ilo2_ribcl_open: open (initiate) instance of the iLO2 RIBCL plug-in
 * @handler_config: Pointer to openhpi config file.
 *
 * This function opens an instance of the iLO2 RIBCL plugin.
 * Detailed description:
 * 	- Reads iLO2 IP address and hostname from the configfile hash
 * 	- Reads iLO2 user name and password from the configfile hash.
 * 	- Intializes plugin internal data structures. Allocates memory
 * 	  for RIBCL send/receive buffers.
 * 	- Initilaizes iLO2 RIBCL SSL module to communicate with iLO2.
 * 	- Error handling: Frees allocated memory (if any) before returning.
 *
 * Return values:
 * 	Plugin handle - normal operation.
 * 	NULL - on error.
 **/
void *ilo2_ribcl_open(GHashTable *handler_config,
                      unsigned int hid,
                      oh_evt_queue *eventq)
{
    struct oh_handler_state *oh_handler = NULL;
    ilo2_ribcl_handler_t *ilo2_ribcl_handler = NULL;
    char *ilo2_hostname = NULL;
    char *ilo2_port_str = NULL;
    char *ilo2_user_name = NULL;
    char *ilo2_password = NULL;
    char *entity_root = NULL;
    int host_len = 0;
    int port_len = 0;
    int temp_len = 0;

#ifdef ILO2_RIBCL_SIMULATE_iLO2_RESPONSE
    char *d_responsefile;
    size_t fnamesize;
#endif /* #ifdef ILO2_RIBCL_SIMULATE_iLO2_RESPONSE */

    /* check input parameters */
    if (!handler_config) {
        err("ilo2_ribcl Open:No config file provided.");
        return(NULL);
    } else if (!hid) {
        err("ilo2 ribcl Open:Bad handler id passed.");
        return NULL;
    } else if (!eventq) {
        err("ilo2 ribcl Open:No event queue was passed.");
        return NULL;
    }

    /* set up entity root in g_epbase */
    entity_root = (char *)g_hash_table_lookup(handler_config,
                  "entity_root");
    if(!entity_root) {
        err("ilo2 ribcl Open:entity root is not present");
        return(NULL);
    }
    oh_encode_entitypath(entity_root, &g_epbase);

    /* read hostname, port string user_name, and password from the
       config file */
    ilo2_hostname = (char *)g_hash_table_lookup(handler_config,
                    "ilo2_ribcl_hostname");
    if(!ilo2_hostname) {
        err("ilo2 ribcl Open:ilo2_ribcl_hostname is not specified in the config file");
        return(NULL);
    }
    host_len = strlen(ilo2_hostname);
    if((host_len < ILO2_HOST_NAME_MIN_LEN) ||
            (host_len > ILO2_HOST_NAME_MAX_LEN)) {
        err("ilo2 ribcl Open: Invalid iLO2 IP address");
        return(NULL);
    }

    ilo2_port_str = (char *)g_hash_table_lookup(handler_config,
                    "ilo2_ribcl_portstr");
    if(!ilo2_port_str) {
        err("ilo2 ribcl Open:ilo2_ribcl_port_str is not specified in the config file");
        return(NULL);
    } else if((port_len = strlen(ilo2_port_str)) < ILO2_MIN_PORT_STR_LEN) {
        err("ilo2 ribcl Open:Invalid iLO2 port");
        return(NULL);
    }

    ilo2_user_name = (char *)g_hash_table_lookup(handler_config,
                     "ilo2_ribcl_username");
    if(!ilo2_user_name) {
        err("ilo2 ribcl Open:ilo2_ribcl_username is not specified in the config file");
        return(NULL);
    }
    temp_len = strlen(ilo2_user_name);
    if(temp_len > ILO2_RIBCL_USER_NAME_MAX_LEN) {
        err("ilo2 ribcl Open:Invalid ilo2_ribcl_username - too long");
        return(NULL);
    } else if(temp_len < ILO2_RIBCL_USER_NAME_MIN_LEN) {
        err("ilo2 ribcl Open:Invalid ilo2_ribcl_username - too short");
        return(NULL);
    }

    ilo2_password = (char *)g_hash_table_lookup(handler_config,
                    "ilo2_ribcl_password");
    if(!ilo2_password) {
        err("ilo2 ribcl Open:ilo2_ribcl_password is not specified in the config file");
        return(NULL);
    }
    temp_len = strlen(ilo2_password);
    if(temp_len > ILO2_RIBCL_PASSWORD_MAX_LEN) {
        err("ilo2 ribcl Open:Invalid ilo2_ribcl_password - too long");
        return(NULL);
    } else if(temp_len < ILO2_RIBCL_PASSWORD_MIN_LEN) {
        err("ilo2 ribcl Open:Invalid ilo2_ribcl_password - too short");
        return(NULL);
    }

    /* allocate main handler and initialize it */
    oh_handler = malloc(sizeof(*oh_handler));
    if(!oh_handler) {
        err("ilo2 ribcl Open:unable to allocate main handler");
        return(NULL);
    }
    memset(oh_handler, '\0', sizeof(*oh_handler));

    /* assign config to handler_config and initialize rptcache */
    oh_handler->config = handler_config;

    oh_handler->rptcache = (RPTable *)g_malloc0(sizeof(RPTable));
    if(!oh_handler->rptcache) {
        err("ilo2 ribcl Open:unable to allocate RPT cache");
        free(oh_handler);
        return(NULL);
    }

    oh_handler->hid = hid;
    oh_handler->eventq = eventq;

    /* allocate memory for ilo2 ribcl private handler */
    ilo2_ribcl_handler = malloc(sizeof(*ilo2_ribcl_handler));
    if(!ilo2_ribcl_handler) {
        err("ilo2 ribcl Open:unable to allocate main handler");
        free(oh_handler->rptcache);
        free(oh_handler);
        return(NULL);
    }
    memset(ilo2_ribcl_handler, '\0', sizeof(*ilo2_ribcl_handler));
    oh_handler->data = ilo2_ribcl_handler;

    /* Save configuration in the handler */
    ilo2_ribcl_handler->entity_root = entity_root;

    /* build complete hostname with port string appended */
    /* add one extra byte to account for : in the middle of hostname:port
       string example: 10.100.1.1:443 */
    ilo2_ribcl_handler->ilo2_hostport = g_malloc(host_len+port_len+2);
    if(ilo2_ribcl_handler->ilo2_hostport == NULL) {
        err("ilo2 ribcl Open:unable to allocate memory");
        free(ilo2_ribcl_handler);
        free(oh_handler->rptcache);
        free(oh_handler);
        return(NULL);
    }
    snprintf(ilo2_ribcl_handler->ilo2_hostport,
             (host_len+port_len+2), "%s:%s",
             ilo2_hostname, ilo2_port_str);

    ilo2_ribcl_handler->user_name = ilo2_user_name;
    ilo2_ribcl_handler->password = ilo2_password;

    /* Build the customized RIBCL command strings containing the
     * login and password for this ilo2 host */

    if (ir_xml_build_cmdbufs( ilo2_ribcl_handler) != RIBCL_SUCCESS) {
        err("ilo2_ribcl_open(): ir_xml_build_cmdbufs failed to build buffers.");
        free(ilo2_ribcl_handler->ilo2_hostport);
        free(ilo2_ribcl_handler);
        free(oh_handler->rptcache);
        free(oh_handler);
        return(NULL);
    }

#ifdef ILO2_RIBCL_SIMULATE_iLO2_RESPONSE

    /* Check if a iLO2 response file should be used for discovery testing.
     * We will use the contents of this file as the command response,
     * rather than communucating with an actual iLO2. */

    d_responsefile = (char *)g_hash_table_lookup(handler_config,
                     "discovery_responsefile");
    if(  d_responsefile) {

        fnamesize = strlen( d_responsefile) + 1;
        ilo2_ribcl_handler->discovery_responsefile = malloc( fnamesize);

        if( ilo2_ribcl_handler->discovery_responsefile == NULL) {
            err("ilo2_ribcl_open(): allocation for discovery_responsefile failed.");
        } else {
            strncpy( ilo2_ribcl_handler->discovery_responsefile,
                     d_responsefile, fnamesize);
        }
    }

#endif /* ILO2_RIBCL_SIMULATE_iLO2_RESPONSE */

    /* initialize SSL */
    ilo2_ribcl_ssl_init();
    ilo2_ribcl_handler->ssl_ctx = ilo2_ribcl_ssl_ctx_init();
    if(ilo2_ribcl_handler->ssl_ctx == NULL) {
        err("ilo2_ribcl_open(): failed to initialize ssl connection to %s",
            ilo2_ribcl_handler->ilo2_hostport);
        free(ilo2_ribcl_handler->ilo2_hostport);
        free(ilo2_ribcl_handler);
        free(oh_handler->rptcache);
        free(oh_handler);
        return(NULL);
    }

    /* Initialize sensor data */
    ilo2_ribcl_init_sensor_data( ilo2_ribcl_handler);

    return((void *)oh_handler);
}
Пример #18
0
void
msg_set_progname (const char * pn)
{
  strncpy (progname, pn, PROGNAME_MAXLEN);
  progname [PROGNAME_MAXLEN - 1] = 0;
}
Пример #19
0
/* Use all available means to detect file language
 */
const char *ohcount_detect_language(SourceFile *sourcefile) {
  const char *language = NULL;
  char *p, *pe;
  int length;

  // Attempt to detect using Emacs mode line (/^-\*-\s*mode[\s:]*\w/i).
  char line[81] = { '\0' }, buf[81];
  p = ohcount_sourcefile_get_contents(sourcefile);
  pe = p;
  char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
  while (pe < eof) {
    // Get the contents of the first line.
    while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
    length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
    strncpy(line, p, length);
    line[length] = '\0';
    if (*line == '#' && *(line + 1) == '!') {
      // First line was sh-bang; loop to get contents of second line.
      while (*pe == '\r' || *pe == '\n') pe++;
      p = pe;
    } else break;
  }
  p = strstr(line, "-*-");
  if (p) {
    p += 3;
    while (*p == ' ' || *p == '\t') p++;
    // detect "mode" (any capitalization)
    if (strncasecmp(p, "mode", 4) == 0) {
      p += 4;
      while (*p == ' ' || *p == '\t' || *p == ':') p++;
    }
    pe = p;
    while (!isspace(*pe) && *pe != ';' && pe != strstr(pe, "-*-")) pe++;
    length = (pe - p <= sizeof(buf)) ? pe - p : sizeof(buf);
    strncpy(buf, p, length);
    buf[length] = '\0';

		// Special case for "c" or "C" emacs mode header: always means C, not C++
		if (strcasecmp(buf, "c") == 0) {
				return LANG_C;
		}

    // First try it with the language name.
    struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
    if (rl) language = rl->name;
    if(!language) {
      // Then try it with the extension table.
      struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
      if (re) language = re->value;
    }
    if (!language) {
      // Try the lower-case version of this modeline.
      for (pe = buf; pe < buf+length; pe++) *pe = tolower(*pe);
      // First try it with the language name.
      rl = ohcount_hash_language_from_name(buf, length);
      if (rl) language = rl->name;
    }
    if (!language) {
      // Then try it with the extension table.
      struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
      if (re) language = re->value;
    }
  }

  // Attempt to detect based on file extension.
  if(!language) {
      length = strlen(sourcefile->ext);
      struct ExtensionMap *re = ohcount_hash_language_from_ext(sourcefile->ext,
                                                               length);
      if (re) language = re->value;
    if (!language) {
      // Try the lower-case version of this extension.
      char lowerext[length + 1];
      strncpy(lowerext, sourcefile->ext, length);
      lowerext[length] = '\0';
      for (p = lowerext; p < lowerext + length; p++) *p = tolower(*p);
      struct ExtensionMap *re = ohcount_hash_language_from_ext(lowerext, length);
      if (re) language = re->value;
    }
  }

  // Attempt to detect based on filename.
  if(!language) {
    length = strlen(sourcefile->filename);
    struct FilenameMap *rf =
      ohcount_hash_language_from_filename(sourcefile->filename, length);
    if (rf) language = rf->value;
  }

  // Attempt to detect based on Unix 'file' command.
  if(!language) {
    language = detect_language_magic(sourcefile);
  }

  if (language) {
    if (ISAMBIGUOUS(language)) {
      // Call the appropriate function for disambiguation.
      length = strlen(DISAMBIGUATEWHAT(language));
      struct DisambiguateFuncsMap *rd =
        ohcount_hash_disambiguate_func_from_id(DISAMBIGUATEWHAT(language),
                                               length);
      if (rd) language = rd->value(sourcefile);
    } else language = ISBINARY(language) ? NULL : language;
  }
  return language;
}
Пример #20
0
static char *
call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
{
	size_t n;
	char *p, *q;
	PyOS_sighandler_t old_inthandler;
#ifdef SAVE_LOCALE
	char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
	if (!saved_locale)
		Py_FatalError("not enough memory to save locale");
	setlocale(LC_CTYPE, "");
#endif

	old_inthandler = PyOS_setsig(SIGINT, onintr);
	if (setjmp(jbuf)) {
#ifdef HAVE_SIGRELSE
		/* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
		sigrelse(SIGINT);
#endif
		PyOS_setsig(SIGINT, old_inthandler);
		return NULL;
	}
	if (event_hook) 
	  rl_event_hook = (Function *)on_event_hook;
	else
	  rl_event_hook = PyOS_InputHook;

	if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
		rl_instream = sys_stdin;
		rl_outstream = sys_stdout;
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
		rl_prep_terminal (1);
#endif
	}

	p = readline(prompt);
	PyOS_setsig(SIGINT, old_inthandler);

	/* We must return a buffer allocated with PyMem_Malloc. */
	if (p == NULL) {
		p = PyMem_Malloc(1);
		if (p != NULL)
			*p = '\0';
		return p;
	}
	n = strlen(p);
	if (n > 0) {
		char *line;
		HISTORY_STATE *state = history_get_history_state();
		if (state->length > 0)
			line = history_get(state->length)->line;
		else
			line = "";
		if (strcmp(p, line))
			add_history(p);
		/* the history docs don't say so, but the address of state
		   changes each time history_get_history_state is called
		   which makes me think it's freshly malloc'd memory...
		   on the other hand, the address of the last line stays the
		   same as long as history isn't extended, so it appears to
		   be malloc'd but managed by the history package... */
		free(state);
	}
	/* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
	   release the original. */
	q = p;
	p = PyMem_Malloc(n+2);
	if (p != NULL) {
		strncpy(p, q, n);
		p[n] = '\n';
		p[n+1] = '\0';
	}
	free(q);
#ifdef SAVE_LOCALE
	setlocale(LC_CTYPE, saved_locale); /* Restore locale */
	free(saved_locale);
#endif
	return p;
}
Пример #21
0
const char *disambiguate_m(SourceFile *sourcefile) {
  char *p, *pe;
  int length;

  // Attempt to detect based on a weighted heuristic of file contents.
  int matlab_score = 0;
  int objective_c_score = 0;
  int limbo_score = 0;
  int octave_syntax_detected = 0;

  int i, has_h_headers = 0, has_c_files = 0;
  char **filenames = sourcefile->filenames;
  if (filenames) {
    for (i = 0; filenames[i] != NULL; i++) {
      p = filenames[i];
      pe = p + strlen(p);
      if (pe - p >= 4) {
        if (*(pe - 4) == '.' && *(pe - 3) == 'c' &&
            ((*(pe - 2) == 'p' && *(pe - 1) == 'p') ||
             (*(pe - 2) == '+' && *(pe - 1) == '+') ||
             (*(pe - 2) == 'x' && *(pe - 1) == 'x'))) {
          has_c_files = 1;
          break; // short circuit
        }
      } else if (pe - p >= 3) {
        if (*(pe - 3) == '.' && *(pe - 2) == 'c' && *(pe - 1) == 'c') {
          has_c_files = 1;
          break; // short circuit
        }
      } else if (pe - p >= 2) {
        if (*(pe - 2) == '.') {
          if (*(pe - 1) == 'h')
            has_h_headers = 1;
          else if (*(pe - 1) == 'c' || *(pe - 1) == 'C') {
            has_c_files = 1;
            break; // short circuit
          }
        }
      }
    }
  }
  if (has_h_headers && !has_c_files)
    objective_c_score += 5;

  char line[81], buf[81];
  p = ohcount_sourcefile_get_contents(sourcefile);
  pe = p;
  char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
  while (pe < eof) {
    // Get a line at a time.
    while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
    length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
    strncpy(line, p, length);
    line[length] = '\0';
    char *eol = line + strlen(line);
    char *line_end = pe;

    // Look for tell-tale lines.
    p = line;
    while (*p == ' ' || *p == '\t') p++;
    if (*p == '%') { // Matlab comment
      matlab_score++;
		} else if (*p == '#' && strncmp(p, "#import", 7) == 0) { // Objective C
			objective_c_score++;
    } else if (*p == '#') { // Limbo or Octave comment
      while (*p == '#') p++;
      if (*p == ' ' || *p == '\t') {
        limbo_score++;
        matlab_score++;
        octave_syntax_detected = 1;
      }
    } else if (*p == '/' && *(p + 1) == '/' || *(p + 1) == '*') {
      objective_c_score++; // Objective C comment
    } else if (*p == '+' || *p == '-') { // Objective C method signature
      objective_c_score++;
    } else if (*p == '@' || *p == '#') { // Objective C method signature
      if (strncmp(p, "@implementation", 15) == 0 ||
          strncmp(p, "@interface", 10) == 0)
        objective_c_score++;
    } else if (strncmp(p, "function", 8) == 0) { // Matlab or Octave function
      p += 8;
      while (*p == ' ' || *p == '\t') p++;
      if (*p == '(')
        matlab_score++;
    } else if (strncmp(p, "include", 7) == 0) { // Limbo include
      // /^include[ \t]+"[^"]+\.m";/
      p += 7;
      if (*p == ' ' || *p == '\t') {
        while (*p == ' ' || *p == '\t') p++;
        if (*p == '"') {
          while (*p != '"' && p < eol) p++;
          if (*p == '"' && *(p - 2) == '.' && *(p - 1) == 'm')
            limbo_score++;
        }
      }
    }

    // Look for Octave keywords.
    p = line;
    while (p < eol) {
      if (islower(*p) && p != line && !isalnum(*(p - 1))) {
        pe = p;
        while (islower(*pe) || *pe == '_') pe++;
        if (!isalnum(*pe)) {
          length = pe - p;
          strncpy(buf, p, length);
          buf[length] = '\0';
          if (strcmp(buf, "end_try_catch") == 0 ||
              strcmp(buf, "end_unwind_protect") == 0 ||
              strcmp(buf, "endfunction") == 0 ||
              strcmp(buf, "endwhile") == 0)
            octave_syntax_detected = 1;
        }
        p = pe + 1;
      } else p++;
    }

    // Look for Limbo declarations
    p = line;
    while (p < eol) {
      if (*p == ':' && (*(p + 1) == ' ' || *(p + 1) == '\t')) {
        // /:[ \t]+(module|adt|fn ?\(|con[ \t])/
        p += 2;
        if (strncmp(p, "module", 6) == 0 && !isalnum(*(p + 6)) ||
            strncmp(p, "adt", 3) == 0 && !isalnum(*(p + 3)) ||
            strncmp(p, "fn", 2) == 0 &&
              (*(p + 2) == ' ' && *(p + 3) == '(' || *(p + 2) == '(') ||
            strncmp(p, "con", 3) == 0 &&
              (*(p + 3) == ' ' || *(p + 3) == '\t'))
          limbo_score++;
      } else p++;
    }

    // Next line.
    pe = line_end;
    while (*pe == '\r' || *pe == '\n') pe++;
    p = pe;
  }

  if (limbo_score > objective_c_score && limbo_score > matlab_score)
    return LANG_LIMBO;
  else if (objective_c_score > matlab_score)
    return LANG_OBJECTIVE_C;
  else
    return octave_syntax_detected ? LANG_OCTAVE : LANG_MATLAB;
}
Пример #22
0
/*
 * Get the information to configure the network, configure it and
 * make sure both the gateway and the name server are up.
 */
int
config_network(void)
{
	char *textbuf;
	int  octet0;
	int  dhcp_config;
	int  nfs_root = 0;
 	int  slip = 0;
 	int  pid, status;
 	char **ap, *slcmd[10], *in_buf;
 	char buffer[STRSIZE];
 	struct statvfs sb;
	struct net_desc net_devs[MAX_NETS];
	menu_ent net_menu[5];
	int menu_no;
	int num_devs;
	int selected_net;
	int i;
#ifdef INET6
	int v6config = 1, rv;
#endif

	FILE *f;
	time_t now;

	if (network_up)
		return (1);

	num_devs = get_ifconfig_info(net_devs);

	if (num_devs < 1) {
		/* No network interfaces found! */
		msg_display(MSG_nonet);
		process_menu(MENU_ok, NULL);
		return (-1);
	}

	for (i = 0; i < num_devs; i++) {
		net_menu[i].opt_name = net_devs[i].if_dev;
		net_menu[i].opt_menu = OPT_NOMENU;
		net_menu[i].opt_flags = OPT_EXIT;
		net_menu[i].opt_action = set_menu_select;
	}
again:
	selected_net = -1;
	menu_no = new_menu(MSG_netdevs,
		net_menu, num_devs, -1, 4, 0, 0,
		MC_SCROLL,
		NULL, NULL, NULL, NULL, NULL);
	msg_display(MSG_asknetdev, "");
	process_menu(menu_no, &selected_net);
	free_menu(menu_no);
	
	if (selected_net == -1)
	    return 0;

	network_up = 1;
	dhcp_config = 0;

	strncpy(net_dev, net_devs[selected_net].if_dev, STRSIZE);

	if (!handle_license(net_dev))
		goto done;

	slip = net_dev[0] == 's' && net_dev[1] == 'l' &&
	    isdigit((unsigned char)net_dev[2]);

	/* If root is on NFS do not reconfigure the interface. */
	if (statvfs("/", &sb) == 0 && strcmp(sb.f_fstypename, "nfs") == 0) {
		nfs_root = 1;
		get_ifinterface_info();
		get_if6interface_info();
		get_host_info();
	} else if (!slip) {
		/* Preload any defaults we can find */
		get_ifinterface_info();
		get_if6interface_info();
		get_host_info();

		/* domain and host */
		msg_display(MSG_netinfo);

		/* ethernet medium */
		for (;;) {
			msg_prompt_add(MSG_net_media, net_media, net_media,
					sizeof net_media);

			/*
			 * ifconfig does not allow media specifiers on
			 * IFM_MANUAL interfaces.  Our UI gives no way
			 * to set an option back
			 * to null-string if it gets accidentally set.
			 * Check for plausible alternatives.
			 */
			if (strcmp(net_media, "<default>") == 0 ||
			    strcmp(net_media, "default") == 0 ||
			    strcmp(net_media, "<manual>") == 0 ||
			    strcmp(net_media, "manual") == 0 ||
			    strcmp(net_media, "<none>") == 0 ||
			    strcmp(net_media, "none") == 0 ||
			    strcmp(net_media, " ") == 0) {
				*net_media = '\0';
			}

			if (*net_media == '\0')
				break;
			/*
			 * We must set the media type here - to give dhcp
			 * a chance
			 */
			if (run_program(0, "/sbin/ifconfig %s media %s",
				    net_dev, net_media) == 0)
				break;
			/* Failed to set - output the supported values */
			if (collect(T_OUTPUT, &textbuf, "/sbin/ifconfig -m %s |"
				    "while IFS=; read line;"
				    " do [ \"$line\" = \"${line#*media}\" ] || "
				    "echo $line;"
				    " done", net_dev ) > 0)
				msg_display(textbuf);
			free(textbuf);
		}

		net_dhcpconf = 0;
		/* try a dhcp configuration */
		dhcp_config = config_dhcp(net_dev);
		if (dhcp_config) {
			char *nline;

			/* Get newly configured data off interface. */
			get_ifinterface_info();
			get_if6interface_info();
			get_host_info();

			net_dhcpconf |= DHCPCONF_IPADDR;

			/*
			 * Extract default route from output of
			 * 'route -n show'
			 */
			if (collect(T_OUTPUT, &textbuf,
			    "/sbin/route -n show | "
			    "while read dest gateway flags;"
			    " do [ \"$dest\" = default ] && {"
			    " echo \"$gateway\"; break; };"
			    " done" ) > 0)
				strlcpy(net_defroute, textbuf,
				    sizeof net_defroute);
			free(textbuf);
			if ((nline = strchr(net_defroute, '\n')))
				*nline = '\0';

			/* pull nameserver info out of /etc/resolv.conf */
			if (collect(T_OUTPUT, &textbuf,
			    "cat /etc/resolv.conf 2>/dev/null |"
			    " while read keyword address rest;"
			    " do [ \"$keyword\" = nameserver ] &&"
			    " { echo \"$address\"; break; };"
			    " done" ) > 0)
				strlcpy(net_namesvr, textbuf,
				    sizeof net_namesvr);
			free(textbuf);
			if ((nline = strchr(net_namesvr, '\n')))
				*nline = '\0';
			if (net_namesvr[0] != '\0')
				net_dhcpconf |= DHCPCONF_NAMESVR;

			/* pull domain info out of /etc/resolv.conf */
			if (collect(T_OUTPUT, &textbuf,
			    "cat /etc/resolv.conf 2>/dev/null |"
			    " while read keyword domain rest;"
			    " do [ \"$keyword\" = domain ] &&"
			    " { echo \"$domain\"; break; };"
			    " done" ) > 0)
				strlcpy(net_domain, textbuf,
				    sizeof net_domain);
			free(textbuf);
			if (net_domain[0] == '\0') {
				/* pull domain info out of /etc/resolv.conf */
				if (collect(T_OUTPUT, &textbuf,
				    "cat /etc/resolv.conf 2>/dev/null |"
				    " while read keyword search rest;"
				    " do [ \"$keyword\" = search ] &&"
				    " { echo \"$search\"; break; };"
				    " done" ) > 0)
					strlcpy(net_domain, textbuf,
					    sizeof net_domain);
				free(textbuf);
			}
			if ((nline = strchr(net_domain, '\n')))
				*nline = '\0';
			if (net_domain[0] != '\0')
				net_dhcpconf |= DHCPCONF_DOMAIN;

			if (gethostname(net_host, sizeof(net_host)) == 0 &&
			    net_host[0] != 0)
				net_dhcpconf |= DHCPCONF_HOST;
		}
	}

	if (!(net_dhcpconf & DHCPCONF_HOST))
		msg_prompt_add(MSG_net_host, net_host, net_host,
		    sizeof net_host);

	if (!(net_dhcpconf & DHCPCONF_DOMAIN))
		msg_prompt_add(MSG_net_domain, net_domain, net_domain,
		    sizeof net_domain);

	if (!dhcp_config) {
		/* Manually configure IPv4 */
		if (!nfs_root)
			msg_prompt_add(MSG_net_ip, net_ip, net_ip,
			    sizeof net_ip);
		if (slip)
			msg_prompt_add(MSG_net_srv_ip, net_srv_ip, net_srv_ip,
			    sizeof net_srv_ip);
		else if (!nfs_root) {
			/* We don't want netmasks for SLIP */
			octet0 = atoi(net_ip);
			if (!net_mask[0]) {
				if (0 <= octet0 && octet0 <= 127)
					strlcpy(net_mask, "0xff000000",
				    	sizeof(net_mask));
				else if (128 <= octet0 && octet0 <= 191)
					strlcpy(net_mask, "0xffff0000",
				    	sizeof(net_mask));
				else if (192 <= octet0 && octet0 <= 223)
					strlcpy(net_mask, "0xffffff00",
				    	sizeof(net_mask));
			}
			msg_prompt_add(MSG_net_mask, net_mask, net_mask,
			    sizeof net_mask);
		}
		msg_prompt_add(MSG_net_defroute, net_defroute, net_defroute,
		    sizeof net_defroute);
	}

	if (!(net_dhcpconf & DHCPCONF_NAMESVR)) {
#ifdef INET6
		if (v6config) {
			rv = 0;
			process_menu(MENU_namesrv6, &rv);
			if (!rv)
				msg_prompt_add(MSG_net_namesrv, net_namesvr,
				    net_namesvr, sizeof net_namesvr);
		} else
#endif
		msg_prompt_add(MSG_net_namesrv, net_namesvr, net_namesvr,
		    sizeof net_namesvr);
	}

	/* confirm the setting */
	if (slip)
		msg_display(MSG_netok_slip, net_domain, net_host,
		    *net_namesvr == '\0' ? "<none>" : net_namesvr,
		    net_dev,
		    *net_media == '\0' ? "<default>" : net_media,
		    *net_ip == '\0' ? "<none>" : net_ip,
		    *net_srv_ip == '\0' ? "<none>" : net_srv_ip,
		    *net_mask == '\0' ? "<none>" : net_mask,
		    *net_defroute == '\0' ? "<none>" : net_defroute);
	else
		msg_display(MSG_netok, net_domain, net_host,
		    *net_namesvr == '\0' ? "<none>" : net_namesvr,
		    net_dev,
		    *net_media == '\0' ? "<default>" : net_media,
		    *net_ip == '\0' ? "<none>" : net_ip,
		    *net_mask == '\0' ? "<none>" : net_mask,
		    *net_defroute == '\0' ? "<none>" : net_defroute);
#ifdef INET6
	msg_display_add(MSG_netokv6,
		     !is_v6kernel() ? "<not supported>" : net_ip6);
#endif
done:
	if (!ask_yesno(MSG_netok_ok))
		goto again;

	run_program(0, "/sbin/ifconfig lo0 127.0.0.1");

	/* dhcpcd will have configured it all for us */
	if (dhcp_config) {
		fflush(NULL);
		network_up = 1;
		return network_up;
	}

	/*
	 * we may want to perform checks against inconsistent configuration,
	 * like IPv4 DNS server without IPv4 configuration.
	 */

	/* Create /etc/resolv.conf if a nameserver was given */
	if (net_namesvr[0] != '\0') {
		f = fopen("/etc/resolv.conf", "w");
		if (f == NULL) {
			if (logfp)
				(void)fprintf(logfp,
				    "%s", msg_string(MSG_resolv));
			(void)fprintf(stderr, "%s", msg_string(MSG_resolv));
			exit(1);
		}
		scripting_fprintf(NULL, "cat <<EOF >/etc/resolv.conf\n");
		time(&now);
		scripting_fprintf(f, ";\n; BIND data file\n; %s %s;\n",
		    "Created by NetBSD sysinst on", safectime(&now));
		if (net_domain[0] != '\0')
			scripting_fprintf(f, "search %s\n", net_domain);
		if (net_namesvr[0] != '\0')
			scripting_fprintf(f, "nameserver %s\n", net_namesvr);
		scripting_fprintf(NULL, "EOF\n");
		fflush(NULL);
		fclose(f);
	}

	if (net_ip[0] != '\0') {
		if (slip) {
			/* XXX: needs 'ifconfig sl0 create' much earlier */
			/* Set SLIP interface UP */
			run_program(0, "/sbin/ifconfig %s inet %s %s up",
			    net_dev, net_ip, net_srv_ip);
			strcpy(sl_flags, "-s 115200 -l /dev/tty00");
			msg_prompt_win(MSG_slattach, -1, 12, 70, 0,
				sl_flags, sl_flags, 255);

			/* XXX: wtf isn't run_program() used here? */
			pid = fork();
			if (pid == 0) {
				strcpy(buffer, "/sbin/slattach ");
				strcat(buffer, sl_flags);
				in_buf = buffer;

				for (ap = slcmd; (*ap = strsep(&in_buf, " ")) != NULL;)
				if (**ap != '\0')
					++ap;

				execvp(slcmd[0], slcmd);
			} else
				wait4(pid, &status, WNOHANG, 0);
		} else if (!nfs_root) {
			if (net_mask[0] != '\0') {
				run_program(0, "/sbin/ifconfig %s inet %s netmask %s",
				    net_dev, net_ip, net_mask);
			} else {
				run_program(0, "/sbin/ifconfig %s inet %s",
			    	net_dev, net_ip);
			}
		}
	}

	/* Set host name */
	if (net_host[0] != '\0')
	  	sethostname(net_host, strlen(net_host));

	/* Set a default route if one was given */
	if (!nfs_root && net_defroute[0] != '\0') {
		run_program(RUN_DISPLAY | RUN_PROGRESS,
				"/sbin/route -n flush -inet");
		run_program(RUN_DISPLAY | RUN_PROGRESS,
				"/sbin/route -n add default %s", net_defroute);
	}

	/*
	 * wait a couple of seconds for the interface to go live.
	 */
	if (!nfs_root) {
		msg_display_add(MSG_wait_network);
		sleep(5);
	}

	/*
	 * ping should be verbose, so users can see the cause
	 * of a network failure.
	 */
	if (net_defroute[0] != '\0' && network_up)
		network_up = !run_program(RUN_DISPLAY | RUN_PROGRESS,
		    "/sbin/ping -v -c 5 -w 5 -o -n %s", net_defroute);
	if (net_namesvr[0] != '\0' && network_up) {
#ifdef INET6
		if (strchr(net_namesvr, ':'))
			network_up = !run_program(RUN_DISPLAY | RUN_PROGRESS,
			    "/sbin/ping6 -v -c 3 -n %s", net_namesvr);
		else
#endif
			network_up = !run_program(RUN_DISPLAY | RUN_PROGRESS,
			    "/sbin/ping -v -c 5 -w 5 -o -n %s", net_namesvr);
	}
	fflush(NULL);

	return network_up;
}
Пример #23
0
int medo_contact_update(char *src_data) {

	char	tmp_data[11][MAX_DATA_LEN];
	char    *data;
	char    *p_data = src_data;
	int     i = 0;
	int     resp = 0;
    MEDO_CONTACT	medo_contact;


	memset(&tmp_data[0][0], NULL, 11*MAX_DATA_LEN);
	memset(&medo_contact, NULL, sizeof(medo_contact));

	while((data = strchr(p_data, ',')) != NULL)
	{
		data = strchr(p_data, ',');
		if( i < 10 && (data - p_data) < MAX_DATA_LEN)
		{
			strncpy(tmp_data[i], p_data, data - p_data);
			p_data = data + 1;
			i ++;
		}
		else
		{
			i = 99;
			break;
		}
	}

	if( i == 10 )
	{
		if(strlen(p_data) < MAX_DATA_LEN)
		{
			strcpy(tmp_data[i], p_data);
		}
		else
		{
			return 2;
		}
	}else{
		return 2;
	}

#if(0)
	if(i == 10 && strlen(tmp_data[0]) <= MEDO_CONTACT_MECONTACTID_LEN &&
					strlen(tmp_data[1]) <= MEDO_CONTACT_MEMAINTENANCEAREA_LEN &&
					strlen(tmp_data[2]) <= MEDO_CONTACT_MECENTERNAME_LEN &&
					strlen(tmp_data[3]) <= MEDO_CONTACT_MEBASENAME_LEN &&
					strlen(tmp_data[4]) <= MEDO_CONTACT_MEDIVISION_LEN &&
					strlen(tmp_data[5]) <= MEDO_CONTACT_MEPERSONDAY_LEN &&
					strlen(tmp_data[6]) <= MEDO_CONTACT_MECONTACTDAY_LEN &&
					strlen(tmp_data[7]) <= MEDO_CONTACT_NIGHTSERVICEFLAG_LEN &&
					strlen(tmp_data[8]) <= MEDO_CONTACT_MECONTACTNIGHT_LEN &&
					strlen(tmp_data[9]) <= MEDO_CONTACT_FAXNUMBERDAY_LEN &&
					strlen(tmp_data[10]) <= MEDO_CONTACT_PORTABLETELEPHONE_LEN )
#endif
	if(i == 10) 
	{
		strncpy(medo_contact.MeContactid, &tmp_data[0][0], MEDO_CONTACT_MECONTACTID_LEN);
		strncpy(medo_contact.MeMaintenanceArea, &tmp_data[1][0], MEDO_CONTACT_MEMAINTENANCEAREA_LEN);
		strncpy(medo_contact.MeCenterName, &tmp_data[2][0], MEDO_CONTACT_MECENTERNAME_LEN);
		strncpy(medo_contact.MeBaseName, &tmp_data[3][0], MEDO_CONTACT_MEBASENAME_LEN);
		strncpy(medo_contact.MeDivision, &tmp_data[4][0], MEDO_CONTACT_MEDIVISION_LEN);
		strncpy(medo_contact.MePersonDay, &tmp_data[5][0], MEDO_CONTACT_MEPERSONDAY_LEN);
		strncpy(medo_contact.MeContactDay, &tmp_data[6][0], MEDO_CONTACT_MECONTACTDAY_LEN);
		strncpy(medo_contact.NightServiceFlag, &tmp_data[7][0], MEDO_CONTACT_NIGHTSERVICEFLAG_LEN);
		strncpy(medo_contact.MeContactNight, &tmp_data[8][0], MEDO_CONTACT_MECONTACTNIGHT_LEN);
		strncpy(medo_contact.FaxNumberDay, &tmp_data[9][0], MEDO_CONTACT_FAXNUMBERDAY_LEN);
		strncpy(medo_contact.PortableTelephone, &tmp_data[10][0], MEDO_CONTACT_PORTABLETELEPHONE_LEN);
#if(0)  /*  前バージョンの名残り    今は使わない    */
#endif

#ifdef DEBUG
printf("############ NETEXPERTから受け取りデータ分割 ############\n");
printf("tmp_data[0]=%s\n",tmp_data[0]);
printf("tmp_data[1]=%s\n",tmp_data[1]);
printf("tmp_data[2]=%s\n",tmp_data[2]);
printf("tmp_data[3]=%s\n",tmp_data[3]);
printf("tmp_data[4]=%s\n",tmp_data[4]);
printf("tmp_data[5]=%s\n",tmp_data[5]);
printf("tmp_data[6]=%s\n",tmp_data[6]);
printf("tmp_data[7]=%s\n",tmp_data[7]);
printf("tmp_data[8]=%s\n",tmp_data[8]);
printf("tmp_data[9]=%s\n",tmp_data[9]);
printf("tmp_data[10]=%s\n",tmp_data[10]);
fflush( stdout );
#if(0)  /*  前バージョンの名残り    今は使わない    */
#endif
printf("############ PROC受け取りデータ分割 #####################\n");
printf("medo_contact.MeContactid=%s\n",medo_contact.MeContactid);
printf("medo_contact.MeMaintenanceArea=%s\n",medo_contact.MeMaintenanceArea);
printf("medo_contact.MeCenterName=%s\n",medo_contact.MeCenterName);
printf("medo_contact.MeBaseName=%s\n",medo_contact.MeBaseName);
printf("medo_contact.MeDivision=%s\n",medo_contact.MeDivision);
printf("medo_contact.MePersonDay=%s\n",medo_contact.MePersonDay);
printf("medo_contact.MeContactDay=%s\n",medo_contact.MeContactDay);
printf("medo_contact.NightServiceFlag=%s\n",medo_contact.NightServiceFlag);
printf("medo_contact.MeContactNight=%s\n",medo_contact.MeContactNight);
printf("medo_contact.FaxNumberDay=%s\n",medo_contact.FaxNumberDay);
printf("medo_contact.PortableTelephone=%s\n",medo_contact.PortableTelephone);
fflush( stdout );
printf("############ END OF 分割データ  #########################\n");
fflush( stdout );
#if(0)  /*  前バージョンの名残り    今は使わない    */
#endif
#endif

		resp = Proc_MEDO_CONTACT_Update(&medo_contact);
	}
	else
	{
		resp = -1;
	} 

    return resp;

} /* medo_contact_update */
Пример #24
0
const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory)
{
  int status;
  char *p, *r;
  size_t l;
  unsigned long flags = 0;

/* Arrange 32-bit pointer to (copied) string storage, if needed. */
#if __INITIAL_POINTER_SIZE == 64
# pragma pointer_size save
# pragma pointer_size 32
        char *ctx_filespec_32p;
# pragma pointer_size restore
        char ctx_filespec_32[ NAMX_MAXRSS+ 1];
#endif /* __INITIAL_POINTER_SIZE == 64 */

#ifdef NAML$C_MAXRSS
  flags |= LIB$M_FIL_LONG_NAMES;
#endif

  if (ctx == NULL || directory == NULL)
    {
      errno = EINVAL;
      return 0;
    }

  errno = 0;
  if (*ctx == NULL)
    {
      size_t filespeclen = strlen(directory);
      char *filespec = NULL;

      /* MUST be a VMS directory specification!  Let's estimate if it is. */
      if (directory[filespeclen-1] != ']'
	  && directory[filespeclen-1] != '>'
	  && directory[filespeclen-1] != ':')
	{
	  errno = EINVAL;
	  return 0;
	}

      filespeclen += 4;		/* "*.*;" */

      if (filespeclen > NAMX_MAXRSS)
	{
	  errno = ENAMETOOLONG;
	  return 0;
	}

      *ctx = (LP_DIR_CTX *)malloc(sizeof(LP_DIR_CTX));
      if (*ctx == NULL)
	{
	  errno = ENOMEM;
	  return 0;
	}
      memset(*ctx, '\0', sizeof(LP_DIR_CTX));

      strcpy((*ctx)->filespec,directory);
      strcat((*ctx)->filespec,"*.*;");

/* Arrange 32-bit pointer to (copied) string storage, if needed. */
#if __INITIAL_POINTER_SIZE == 64
# define CTX_FILESPEC ctx_filespec_32p
        /* Copy the file name to storage with a 32-bit pointer. */
        ctx_filespec_32p = ctx_filespec_32;
        strcpy( ctx_filespec_32p, (*ctx)->filespec);
#else /* __INITIAL_POINTER_SIZE == 64 */
# define CTX_FILESPEC (*ctx)->filespec
#endif /* __INITIAL_POINTER_SIZE == 64 [else] */

      (*ctx)->filespec_dsc.dsc$w_length = filespeclen;
      (*ctx)->filespec_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
      (*ctx)->filespec_dsc.dsc$b_class = DSC$K_CLASS_S;
      (*ctx)->filespec_dsc.dsc$a_pointer = CTX_FILESPEC;
    }

  (*ctx)->result_dsc.dsc$w_length = 0;
  (*ctx)->result_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
  (*ctx)->result_dsc.dsc$b_class = DSC$K_CLASS_D;
  (*ctx)->result_dsc.dsc$a_pointer = 0;

  status = lib$find_file(&(*ctx)->filespec_dsc, &(*ctx)->result_dsc,
			 &(*ctx)->VMS_context, 0, 0, 0, &flags);

  if (status == RMS$_NMF)
    {
      errno = 0;
      vaxc$errno = status;
      return NULL;
    }

  if(!$VMS_STATUS_SUCCESS(status))
    {
      errno = EVMSERR;
      vaxc$errno = status;
      return NULL;
    }

  /* Quick, cheap and dirty way to discard any device and directory,
     since we only want file names */
  l = (*ctx)->result_dsc.dsc$w_length;
  p = (*ctx)->result_dsc.dsc$a_pointer;
  r = p;
  for (; *p; p++)
    {
      if (*p == '^' && p[1] != '\0') /* Take care of ODS-5 escapes */
	{
	  p++;
	}
      else if (*p == ':' || *p == '>' || *p == ']')
	{
	  l -= p + 1 - r;
	  r = p + 1;
	}
      else if (*p == ';')
	{
	  l = p - r;
	  break;
	}
    }

  strncpy((*ctx)->result, r, l);
  (*ctx)->result[l] = '\0';
  str$free1_dx(&(*ctx)->result_dsc);

  return (*ctx)->result;
}
Пример #25
0
Файл: log.c Проект: Chr1stoph/i3
/*
 * Logs the given message to stdout (if print is true) while prefixing the
 * current time to it. Additionally, the message will be saved in the i3 SHM
 * log if enabled.
 * This is to be called by *LOG() which includes filename/linenumber/function.
 *
 */
static void vlog(const bool print, const char *fmt, va_list args) {
    /* Precisely one page to not consume too much memory but to hold enough
     * data to be useful. */
    static char message[4096];
    static struct tm result;
    static time_t t;
    static struct tm *tmp;
    static size_t len;

    /* Get current time */
    t = time(NULL);
    /* Convert time to local time (determined by the locale) */
    tmp = localtime_r(&t, &result);
    /* Generate time prefix */
    len = strftime(message, sizeof(message), "%x %X - ", tmp);

    /*
     * logbuffer  print
     * ----------------
     *  true      true   format message, save, print
     *  true      false  format message, save
     *  false     true   print message only
     *  false     false  INVALID, never called
     */
    if (!logbuffer) {
#ifdef DEBUG_TIMING
        struct timeval tv;
        gettimeofday(&tv, NULL);
        printf("%s%d.%d - ", message, tv.tv_sec, tv.tv_usec);
#else
        printf("%s", message);
#endif
        vprintf(fmt, args);
    } else {
        len += vsnprintf(message + len, sizeof(message) - len, fmt, args);
        if (len >= sizeof(message)) {
            fprintf(stderr, "BUG: single log message > 4k\n");

            /* vsnprintf returns the number of bytes that *would have been written*,
             * not the actual amount written. Thus, limit len to sizeof(message) to avoid
             * memory corruption and outputting garbage later.  */
            len = sizeof(message);

            /* Punch in a newline so the next log message is not dangling at
             * the end of the truncated message. */
            message[len - 2] = '\n';
        }

        /* If there is no space for the current message in the ringbuffer, we
         * need to wrap and write to the beginning again. */
        if (len >= (size_t)(logbuffer_size - (logwalk - logbuffer))) {
            loglastwrap = logwalk;
            logwalk = logbuffer + sizeof(i3_shmlog_header);
            store_log_markers();
            header->wrap_count++;
        }

        /* Copy the buffer, move the write pointer to the byte after our
         * current message. */
        strncpy(logwalk, message, len);
        logwalk += len;

        store_log_markers();

        /* Wake up all (i3-dump-log) processes waiting for condvar. */
        pthread_cond_broadcast(&(header->condvar));

        if (print)
            fwrite(message, len, 1, stdout);
    }
}
Пример #26
0
/*
 * This function reads the encrypted query sent by client, computes the intermediate cosine tfidf product and cosine co-ordination factor,
 * randomizes these two values and writes them along with respective randomizing values into the output_file_name.
 * */
int read_encrypt_vec_from_file_comp_inter_sec_prod( int vsizelocal, const char * input_encr_tfidf_file_name, const char * input_encr_bin_file_name, const char * input_tfidf_vec_file_name, const char * input_bin_vec_file_name, const char * output_file_name, const char * key_file_name)
{
	int input_size = 0, i, temp, *p_tfidf_vec, *p_bin_vec;
	mpz_t *vec1;	//holds input encrypted tfidf q values
	mpz_t *vec2;	//holds input encrypted binary q values
	mpz_t cosine_result;
	mpz_t co_ord_factor;
	mpz_t random_no;
	FILE *input_encr_tfidf_file, *input_tfidf_vec_file, *input_bin_vec_file, *output_file, *input_encr_bin_file;


	vsize = vsizelocal;
	input_encr_tfidf_file = fopen(input_encr_tfidf_file_name, "r");
	input_encr_bin_file = fopen(input_encr_bin_file_name, "r");
	input_tfidf_vec_file = fopen(input_tfidf_vec_file_name, "r");
	input_bin_vec_file = fopen(input_bin_vec_file_name, "r");
	output_file = fopen(output_file_name, "w");

	strncpy(g_key_file_name, key_file_name, sizeof(g_key_file_name));

	printf("Number of vector dimensions = %d\n", vsizelocal);
	//printf("p_tfidf_vec:%p, ENOMEM:%d\n", p_tfidf_vec, (errno == ENOMEM)?1:0);



	//initialize vectors and big number variables
	//Dynamically creating the array
	vec1 = (mpz_t *)malloc(vsizelocal*sizeof(mpz_t));
	vec2 = (mpz_t *)malloc(vsizelocal*sizeof(mpz_t));
	p_tfidf_vec = (int*)malloc(vsize*sizeof(int));
	p_bin_vec = (int*)malloc(vsize*sizeof(int));
	printf("p_tfidf_vec:%p, ENOMEM:%d\n", p_tfidf_vec, (errno == ENOMEM)?1:0);

	//initialize vectors and big number variables
	for (i = 0; i < vsizelocal; i++)
		mpz_init(*(vec1+i));
	for (i = 0; i < vsizelocal; i++)
		mpz_init(*(vec2+i));

	//variables are set to 0
	mpz_init(cosine_result);
	mpz_init(co_ord_factor);
	mpz_init(random_no);

	init();

	//variables are set to 0

	//init();



	//check if files are opened properly
	if (input_encr_tfidf_file == NULL) {
		printf("\n%s", "Error: open input_encr_tfidf_file!");
		return -2;
	}

	if (input_encr_bin_file == NULL) {
		printf("\n%s", "Error: open input_encr_bin_file!");
		return -2;
	}

	if (input_tfidf_vec_file == NULL) {
		printf("\n%s", "Error: open input_tfidf_vec_file!");
		return -3;
	}

	if (input_bin_vec_file == NULL) {
		printf("\n%s", "Error: open input_bin_vec_file!");
		return -4;
	}

	if (output_file == NULL) {
		printf("\n%s", "Error: open output_file!");
		exit(1);
	}


	//fill in the first vector
	input_size = 0;
	while ( (input_size < vsizelocal) )
	{
		if ( input_size == vsizelocal - 1 )
		{
			gmp_fscanf(input_encr_tfidf_file,"%Zd", (vec1+input_size));
		}
		else
		{
			gmp_fscanf(input_encr_tfidf_file,"%Zd\n", (vec1+input_size));
		}
		gmp_printf("%d>> READ %Zd\n", input_size+1, *(vec1+input_size));

		input_size++;
	}
	if ( !( input_size == vsizelocal ) )
	{
		fprintf(stderr, "%s:%d::ERROR! TFIDF: Nothing to read OR parsing error! input_size:%d, vsizelocal:%d\n", 
				__func__, __LINE__, input_size, vsizelocal);
		return -4;
	}

	input_size = 0;
	while ( (input_size < vsizelocal) )
	{
		if ( input_size == vsizelocal - 1 )
		{
			gmp_fscanf(input_encr_bin_file,"%Zd", (vec2+input_size));
		}
		else
		{
			gmp_fscanf(input_encr_bin_file,"%Zd\n", (vec2+input_size));
		}
		gmp_printf("%d>> READ %Zd\n", input_size+1, *(vec2+input_size));

		input_size++;
	}
	if ( !( input_size == vsizelocal ) )
	{
		fprintf(stderr, "%s:%d::ERROR! Binary: Nothing to read OR parsing error! input_size:%d, vsizelocal:%d\n", 
				__func__, __LINE__, input_size, vsizelocal);
		return -4;
	}


	printf("\n");
	input_size = 0;

	//fill in the second vector
	for( fscanf(input_tfidf_vec_file,"%d", &temp); temp != EOF && input_size < vsize; 
			fscanf(input_tfidf_vec_file, "%d", &temp) ){

		printf("Non encrypted TFIDF Input::Wt.:%d\n", temp);
		*(p_tfidf_vec + input_size) = temp;
		input_size ++;
	} 

	input_size = 0;
	for( fscanf(input_bin_vec_file,"%d", &temp); temp != EOF && input_size < vsize; 
			fscanf(input_bin_vec_file, "%d", &temp) ){

		printf("Non encrypted Binary Input::Wt.:%d\n", temp);
		*(p_bin_vec + input_size) = temp;
		input_size ++;
	} 

	encrypt(cosine_result, 0);
	//compute encrypted the vec1 * p_tfidf_vec (dot product)
	for (i = 0; i < input_size; i++) {
		//compute m1 * m2
		mpz_powm_ui(big_temp, *(vec1+i), *(p_tfidf_vec+i), n_square);
		//compute m1 + m2
		mpz_mul(cosine_result, cosine_result, big_temp);
		mpz_mod(cosine_result, cosine_result, n_square);
	}

	encrypt(co_ord_factor, 0);
	//compute encrypted the vec2 * co_ord_factor (dot product)
	for (i = 0; i < input_size; i++) {
		//compute m1 * m2
		mpz_powm_ui(big_temp, *(vec2+i), *(p_bin_vec+i), n_square);
		//compute m1 + m2
		mpz_mul(co_ord_factor, co_ord_factor, big_temp);
		mpz_mod(co_ord_factor, co_ord_factor, n_square);
	}


	/*
	 * Donot decrypt here as we would not be having the CORRESPONDING private key
	 * */
	//decrypt the encrypted dot product
	//decrypt(cosine_result);

	//TODO: Remove this debug decryption. - START
	mpz_t dot_prod;
	mpz_init(dot_prod);
	mpz_set(dot_prod, cosine_result);
	decrypt(dot_prod);
	gmp_fprintf(stderr, "\n%s:%d:: Query*%s TFIDF cosine product: %Zd\n", __func__, __LINE__, input_encr_tfidf_file_name, dot_prod);

	mpz_set(dot_prod, co_ord_factor);
	decrypt(dot_prod);
	gmp_fprintf(stderr, "%s:%d:: Query*%s CO-ORD. cosine product: %Zd\n\n", __func__, __LINE__, input_encr_bin_file_name, dot_prod);
	fflush(stderr);

	mpz_clear(dot_prod);
	//TODO: Remove this debug decryption. - END

	//decrypt the encrypted co ordination factor
	//decrypt(co_ord_factor);

	/*
	 * Generate two random numbers of the modulo n_square and the add these two
	 * to the two results - cosine product and co_ord_factor. 
	 * Write these two random values one after the other
	 * and then the randomized values after them in the output file
	 * given for performing the secure multiplication
	 * protocol. All should be seperated by a newline except maybe the last one
	 * written to the file. FORMAT - output file
	 * ===START===
	 * r_1
	 * randomized cosine tfidf product
	 * r_2
	 * randomized cosine co-ord. product
	 *  ===END===
	 * */

	//Generate random number, say r_1
	get_random_r_given_modulo(random_no, n_square);
	//Write r_1 to outputfile
	mpz_out_str(output_file, 10, random_no);
	fprintf(output_file, "\n");
	//Calculate randomized cosine tfidf product, MULTIPLYING to add
	mpz_mul(cosine_result, cosine_result, random_no);
	//Compute modulus
	mpz_mod(cosine_result, cosine_result, n_square);
	//Write randomized cosine tfidf product to output file
	mpz_out_str(output_file, 10, cosine_result);
	fprintf(output_file, "\n");

	//Generate random number, say r_2
	get_random_r_given_modulo(random_no, n_square);
	//Write r_2 to outputfile
	mpz_out_str(output_file, 10, random_no);
	fprintf(output_file, "\n");
	//Calculate randomized cosine tfidf product, MULTIPLYING to add
	mpz_mul(co_ord_factor, co_ord_factor, random_no);
	//Compute modulus
	mpz_mod(co_ord_factor, co_ord_factor, n_square);
	//Write randomized cosine co_ord product to output file
	mpz_out_str(output_file, 10, co_ord_factor);

	gmp_printf("\nThus similarity of %s and %s score = %Zd written in %s\n", input_encr_tfidf_file_name, input_tfidf_vec_file_name, cosine_result, output_file_name);
#if 0
	//print the cosine_result
	if (mpz_out_str(output_file, 10, cosine_result) == 0)
		printf("ERROR: Not able to write the cosine_result!\n");

	fprintf(output_file, "\n");
#endif
	gmp_printf("\nThus co-ord. factor of %s and %s score = %Zd written in %s\n", input_encr_bin_file_name, input_bin_vec_file_name, co_ord_factor, output_file_name);
#if 0
	//print the co_ord_factor
	if (mpz_out_str(output_file, 10, co_ord_factor) == 0)
		printf("ERROR: Not able to write the co_ord_factor!\n");
#endif


	fclose(input_encr_tfidf_file);  
	fclose(input_encr_bin_file);  
	//fflush(input_tfidf_vec_file);
	fclose(input_tfidf_vec_file);
	//fflush(input_bin_vec_file);
	fclose(input_bin_vec_file);
	fflush(output_file);
	fclose(output_file);

	//release space used by big number variables
	for (i = 0; i < vsizelocal; i++)
		mpz_clear(*(vec1+i));
	for (i = 0; i < vsizelocal; i++)
		mpz_clear(*(vec2+i));


	mpz_clear(cosine_result);
	mpz_clear(co_ord_factor);
	mpz_clear(random_no);
	clear();
	free(vec1);
	free(vec2);
	free(p_tfidf_vec);
	free(p_bin_vec);

	return 0;
}
Пример #27
0
int main(int argc, char *argv[])
{
	int fd, i;
	int ret;
	char packet[MAX_PACKET_SIZE], tmp[MAX_PACKET_SIZE];
	char reply[MAX_PACKET_SIZE];

	if (argc < 2)
		print_usage(argv[0]);

	fd = open(OSR_USB_FX2_DEV, O_RDWR);

	if (-1 == fd)
	{
		fprintf(stderr, "Failed to open %s\n", OSR_USB_FX2_DEV);
		return 1;
	}


	/* Save two characters for packet number and one for NULL */
	memset(tmp, 0, MAX_PACKET_SIZE);
	strncpy(tmp, argv[1], MAX_PACKET_SIZE - 3);

	for (i = 0; i < TOTAL_PACKETS; i++)
	{
		sprintf(packet, "%s %i", tmp, i);

		ret = write(fd, packet, MAX_PACKET_SIZE);
		if (ret < 0)
		{
			fprintf(stderr,
				"Failed to write to device after %d packets\n",
				i);
			close(fd);
			return 1;
		}

		printf("Send: %s\n", packet);

		sleep(1);
	}

	for (i = 0; i < TOTAL_PACKETS; i++)
	{
		memset(reply, 0, MAX_PACKET_SIZE);
		ret = read(fd, reply, MAX_PACKET_SIZE);
		if (ret < 0)
		{
			fprintf(stderr, "Failed to read from device\n");
			close(fd);
			return 1;
		}

		printf("Reply: %s\n", reply);
		sleep(1);
	}

	/* Clean up */
	close(fd);

	return 0;
}
Пример #28
0
/*
 * Implementing second part of secure MP protocol. This function reads the input file containing the two encrypted products seperated by a newline, decrypts them, multiplies them and again encrypts their 
 * product and writes to the output file. If the other party has n documents in its collection, this should be called n times by the native Jav API i.e. this acts per remotely-based collection document.
 * */
int read_decrypt_mul_encrypt_write_encrypted_rand_prod( const char * input_interm_prods_file_name, const char * output_encrypt_rand_prod_file_name, const char * key_file_name)
{
	mpz_t tfidf_prod1;	//holds input randomized, encrypted tfidf vector products
	mpz_t coord_prod2;	//holds input randomized, encrypted binary vector products
	mpz_t out_enc_ran_prod;	//holds the encrypted product of tfidf_prod1, coord_prod2

	FILE *input_interm_prods_file=NULL, *output_encrypt_rand_prod_file=NULL;


	input_interm_prods_file = fopen(input_interm_prods_file_name, "r");
	output_encrypt_rand_prod_file = fopen(output_encrypt_rand_prod_file_name, "w");

	strncpy(g_key_file_name, key_file_name, sizeof(g_key_file_name));

	//Initialize
	mpz_init(tfidf_prod1);
	mpz_init(coord_prod2);

	mpz_init(out_enc_ran_prod);

	init();

	//variables are set to 0

	//init();



	//check if files are opened properly
	if (input_interm_prods_file == NULL) {
		printf("\n%s", "Error: open %s!", input_interm_prods_file_name);
		return -2;
	}

	if (output_encrypt_rand_prod_file == NULL) {
		printf("\n%s", "Error: open %s!", output_encrypt_rand_prod_file_name);
		return -2;
	}

	//Read the product values
	//File structure can be found in the Java function in which it is written i.e. 
	//<Class_name>:<function_name> :: DocSimSecApp:acceptIntermValues()
	gmp_fscanf(input_interm_prods_file, "%Zd", tfidf_prod1);
	gmp_fscanf(input_interm_prods_file, "%Zd\n", coord_prod2);

	gmp_fprintf(stderr, "TFIDF Product read = %Zd\n\n", tfidf_prod1);
	gmp_fprintf(stderr, "Co-ord Product read = %Zd\n\n", coord_prod2);

	//Decrypt both
	decrypt(tfidf_prod1);
	decrypt(coord_prod2);

	gmp_fprintf(stderr, "After decrypting, TFIDF Product read = %Zd\n\n", tfidf_prod1);
	gmp_fprintf(stderr, "After decrypting, Co-ord Product read = %Zd\n\n", coord_prod2);


	//Multiply both
	mpz_mul(out_enc_ran_prod, tfidf_prod1, coord_prod2);
	mpz_mod(out_enc_ran_prod, out_enc_ran_prod, n);
	
	gmp_fprintf(stderr, "Unencrypted Product = %Zd\n\n", out_enc_ran_prod);

	//note obtained product is not encrypted, hence, encrypting it
	encrypt_big_num(out_enc_ran_prod, out_enc_ran_prod);
	gmp_fprintf(stderr, "Encrypted Product = %Zd\n\n", out_enc_ran_prod);
	gmp_fprintf(output_encrypt_rand_prod_file, "%Zd", out_enc_ran_prod);

	fflush(output_encrypt_rand_prod_file);
	fclose(input_interm_prods_file);
	fclose(output_encrypt_rand_prod_file);


	mpz_clear(tfidf_prod1);
	mpz_clear(coord_prod2);
	mpz_clear(out_enc_ran_prod);
	clear();

	return 0;
}
Пример #29
0
//-------- Begin of function ButtonCustom::set_help_code -------//
//
void ButtonCustom::set_help_code(const char* helpCode)
{
	strncpy( help_code, helpCode, HELP_CODE_LEN );

	help_code[HELP_CODE_LEN] = NULL;
}
Пример #30
0
int authenticate_gss_server_step(gss_server_state *state, const char *challenge)
{
    OM_uint32 maj_stat;
    OM_uint32 min_stat;
    gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
    gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
    int ret = AUTH_GSS_CONTINUE;
    
    // Always clear out the old response
    if (state->response != NULL)
    {
        free(state->response);
        state->response = NULL;
    }
    
    // If there is a challenge (data from the server) we need to give it to GSS
    if (challenge && *challenge)
    {
        size_t len;
        input_token.value = base64_decode(challenge, &len);
        input_token.length = len;
    }
    else
    {
        PyErr_SetString(KrbException_class, "No challenge parameter in request from client");
        ret = AUTH_GSS_ERROR;
        goto end;
    }
    
    Py_BEGIN_ALLOW_THREADS
    maj_stat = gss_accept_sec_context(&min_stat,
                                      &state->context,
                                      state->server_creds,
                                      &input_token,
                                      GSS_C_NO_CHANNEL_BINDINGS,
                                      &state->client_name,
                                      NULL,
                                      &output_token,
                                      NULL,
                                      NULL,
                                      &state->client_creds);
    Py_END_ALLOW_THREADS
    
    if (GSS_ERROR(maj_stat))
    {
        set_gss_error(maj_stat, min_stat);
        ret = AUTH_GSS_ERROR;
        goto end;
    }
    
    // Grab the server response to send back to the client
    if (output_token.length)
    {
        state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);;
        maj_stat = gss_release_buffer(&min_stat, &output_token);
    }
    
    // Get the user name
    maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL);
    if (GSS_ERROR(maj_stat))
    {
        set_gss_error(maj_stat, min_stat);
        ret = AUTH_GSS_ERROR;
        goto end;
    }
    state->username = (char *)malloc(output_token.length + 1);
    strncpy(state->username, (char*) output_token.value, output_token.length);
    state->username[output_token.length] = 0;
    
    // Get the target name if no server creds were supplied
    if (state->server_creds == GSS_C_NO_CREDENTIAL)
    {
        gss_name_t target_name = GSS_C_NO_NAME;
        maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL);
        if (GSS_ERROR(maj_stat))
        {
            set_gss_error(maj_stat, min_stat);
            ret = AUTH_GSS_ERROR;
            goto end;
        }
        maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL);
        if (GSS_ERROR(maj_stat))
        {
            set_gss_error(maj_stat, min_stat);
            ret = AUTH_GSS_ERROR;
            goto end;
        }
        state->targetname = (char *)malloc(output_token.length + 1);
        strncpy(state->targetname, (char*) output_token.value, output_token.length);
        state->targetname[output_token.length] = 0;
    }

    ret = AUTH_GSS_COMPLETE;
    
end:
    if (output_token.length)
        gss_release_buffer(&min_stat, &output_token);
    if (input_token.value)
        free(input_token.value);
    return ret;
}