Example #1
0
int main(int argc, char** argv)
{
  if ( argc == 2 )
  {
      if( (std::string(argv[1]) == "--help" ||
           std::string(argv[1]) == "-h" ) )
      {
          printHelp();
          return 0;
      }
  }
  if (argc != 5)
  {
      printHelp();
      return -1;
  }

  std::string urdf_file_name         = argv[1];
  std::string base_link_name         = argv[2];
  std::string end_effector_link_name = argv[3];
  std::string ikin_ini_file_name     = argv[4];

  KDL::Tree kdl_tree;
  KDL::Chain kdl_chain;
  iCub::iKin::iKinLimb ikin_limb;
  std::vector<std::string> joint_names;
  KDL::JntArray min,max;

  //
  // URDF --> KDL::Tree
  //
  bool root_inertia_workaround = true;
  if( !treeFromUrdfFile(urdf_file_name,kdl_tree,root_inertia_workaround) )
  {
      cerr << "urdf2dh: Could not parse urdf robot model" << endl;
      std::cerr << "urdf2dh: Please open an issue at https://github.com/robotology-playground/idyntree/issues " << std::endl;

      return EXIT_FAILURE;
  }

  //
  // URDF --> position ranges
  //
  if( !jointPosLimitsFromUrdfFile(urdf_file_name,joint_names,min,max) )
  {
      cerr << "Could not parse urdf robot model limits" << endl;
      return EXIT_FAILURE;
  }

  if( joint_names.size() != min.rows() ||
      joint_names.size() != max.rows() ||
      joint_names.size() == 0)
  {
      cerr << "Inconsistent joint limits got from urdf (nr of joints extracted: " << joint_names.size() << " ) " << endl;
      return EXIT_FAILURE;
  }

  //
  // KDL::Tree --> KDL::CoDyCo::UndirectedTree
  // (for extracting arbitrary chains,
  //    using KDL::Tree you can just get chains where the base of the chain
  //    is proximal to the tree base with respect to the end effector.
  //
  KDL::CoDyCo::UndirectedTree undirected_tree(kdl_tree);

  KDL::Tree kdl_rotated_tree = undirected_tree.getTree(base_link_name);

  bool result = kdl_rotated_tree.getChain(base_link_name,end_effector_link_name,kdl_chain);
  if( !result )
  {
      cerr << "urdf2dh: Impossible to find " << base_link_name << " or "
           << end_effector_link_name << " in the URDF."  << endl;
      return EXIT_FAILURE;
  }

  //
  // Copy the limits extracted from the URDF to the chain
  //
  int nj = kdl_chain.getNrOfJoints();
  KDL::JntArray chain_min(nj), chain_max(nj);

  size_t seg_i, jnt_i;
  for(seg_i=0,jnt_i=0; seg_i < kdl_chain.getNrOfSegments(); seg_i++)
  {
      const Segment & seg = kdl_chain.getSegment(seg_i);
      if( seg.getJoint().getType() != KDL::Joint::None )
      {
          std::string jnt_name = seg.getJoint().getName();
         // std::cerr << "searching for joint " << jnt_name << std::endl;
          int tree_jnt = 0;
          for(tree_jnt = 0; tree_jnt < joint_names.size(); tree_jnt++ )
          {
              //std::cerr << "joint_names[ " << tree_jnt << "] is " << joint_names[tree_jnt] << std::endl;
              if( joint_names[tree_jnt] == jnt_name )
              {
                  chain_min(jnt_i) = min(tree_jnt);
                  chain_max(jnt_i) = max(tree_jnt);
                  jnt_i++;
                  break;
              }
          }
          if( tree_jnt == joint_names.size() )
          {
              std::cerr << "urdf2dh failure in converting limits from tree to chain, unable to find joint " << jnt_name << std::endl;
              return EXIT_FAILURE;
          }
      }
  }

  if( jnt_i != nj )
  {
      std::cerr << "urdf2dh failure in converting limits from tree to chain" << std::endl;
      return EXIT_FAILURE;
  }

  //
  // Convert the chain and the limits to an iKin chain (i.e. DH parameters)
  //
  result = iKinLimbFromKDLChain(kdl_chain,ikin_limb,chain_min,chain_max);
  if( !result )
  {
      cerr << "urdf2dh: Could not export KDL::Tree to iKinChain" << endl;
      return EXIT_FAILURE;
  }

  bool result_corrupted = false;
  if( !checkChainsAreEqual(kdl_chain,ikin_limb) )
  {
      cerr << "urdf2dh error: KDL::Chain and iKinChain results does not match" << endl;
      std::cerr << "urdf2dh: Please open an issue at https://github.com/robotology-playground/idyntree/issues " << std::endl;
      return false;
  }

  yarp::os::Property prop;
  result = ikin_limb.toLinksProperties(prop);
  if( !result )
  {
      cerr << "urdf2dh: Could not export Link Properties from ikin_limb" << endl;
      return EXIT_FAILURE;
  } else {
      std::cout << "urdf2dh: Conversion to iKin DH chain completed correctly" << std::endl;
  }

  std::string ikin_prop = prop.toString();
  yarp::os::Bottle prop_bot;
  prop_bot.fromString(prop.toString());

  //Write the properties to file
   std::ofstream ofs (ikin_ini_file_name.c_str(), std::ofstream::out);

   ofs << prop_bot.findGroup("type").toString() << std::endl;
   ofs << prop_bot.findGroup("numLinks").toString() << std::endl;
   ofs << prop_bot.findGroup("H0").toString() << std::endl;
   for( int link = 0; link < ikin_limb.getN(); link++ )
   {
        std::string link_name = "link_" + int2string(link);
        ofs << prop_bot.findGroup(link_name).toString() << std::endl;

   }
   ofs << prop_bot.findGroup("HN").toString() << std::endl;


   ofs.close();

   if( result_corrupted )
   {
       return EXIT_FAILURE;
   }
   else
   {
     return EXIT_SUCCESS;
   }
}
Example #2
0
int parseCmdLine(int argc, char *argv[]) {
	int j, more;

	if (argc < 3) {
		printHelp();
		return 0;
	}

	for (j = 1; j < argc; j++) {
		more = ((j + 1) < argc);
		if (!strcmp(argv[j], "--remove")) {
			estgbconf.isRemove = 1;
		} else if (!strcmp(argv[j], "--force-remove")) {
			estgbconf.isRemove = 2;
		} else if (!strcmp(argv[j], "--escape-seq")) {
			estgbconf.needUnescape = 1;
		} else if (!strcmp(argv[j], "--singleton")) {
			estgbconf.isSingleton = 1;
		} else if (!strcmp(argv[j], "--daemon")) {
			estgbconf.isDaemonize = 1;
		} else if (!strcmp(argv[j], "--mediagroup")) {
			estgbconf.isPicsMediagroup = 1;
		} else if (!strcmp(argv[j], "--repeat-send") && more) {
			estgbconf.isScan = atoi(argv[++j]);
		} else if (!strcmp(argv[j], "--time-sleep") && more) {
			estgbconf.timeRescan = atoi(argv[++j]);
		} else if (!strcmp(argv[j], "--animation")) {
			estgbconf.isAnimation = 1;
		} else if (!strcmp(argv[j], "--wildcard")) {
			estgbconf.isWildcard = 1;
		} else if (!strcmp(argv[j], "--weakconfig")) {
			estgbconf.isWeakConfig = 1;
		} else if (!strcmp(argv[j], "--sendpic") && more) {
			estgbconf.imgfile = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--sendvideo") && more) {
			estgbconf.videofile = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--sendtext") && more) {
			estgbconf.text = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--senddoc") && more) {
			estgbconf.docfile = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--sendaudio") && more) {
			estgbconf.audiofile = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--fileconfigs")) {
			estgbconf.useFileConfig = 1;
		} else if (!strcmp(argv[j], "--token") && more) {
			estgbconf.token = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--userid") && more) {
			estgbconf.user_id = atoll(argv[++j]);
		} else if (!strcmp(argv[j], "--path") && more) {
			estgbconf.path = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--comment") && more) {
			estgbconf.comment = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--proxy") && more) {
			estgbconf.proxy_addr = strdup(argv[++j]);
		} else if (!strcmp(argv[j], "--proxyauth") && more) {
			estgbconf.proxy_auth = strdup(argv[++j]);
		}

		else if (!strcmp(argv[j], "--help")) {
			printHelp();
			return 0;
		} else {
			printHelp();
			printConfig();
			printf("Unknown or not enough arguments for option '%s'.\n\n",
					argv[j]);
			return 0;
		}
	}
	return 1;
}
imagePathPars ImagePathInit(int argc, char *argv[],int * verbose)
{
	imagePathPars par = {argc,0,
		(char **)malloc(sizeof(char *) * argc),
		(char **)malloc(sizeof(char *) * argc),
		(char **)malloc(sizeof(char *) * argc),
		(char **)malloc(sizeof(char *) * argc),
		(char **)malloc(sizeof(char *) * argc)};
	if (argc == 1)
	{
		printHelp();
	}
	else
	{
		//指针没学好的结果....
		//*par.imagePath = (char *)malloc(sizeof(char *) * argc);
		//*par.imageInputPath = (char *)malloc(sizeof(char *) * argc);
		//*par.imageOutputPath = (char *)malloc(sizeof(char *) * argc);
		//*par.imageInputName = (char *)malloc(sizeof(char *) * argc);
		//*par.imageOutputName = (char *)malloc(sizeof(char *) * argc);
		char inputPath[255] = "\0";
		char inputName[255] = "\0";
		char outputPath[255] = "\0";
		char outputName[255] = "\0";
		char exName[255] = "\0";
		int j = 0;
		int posSplit = -1;
		int posDot = -1;

		for (int i = 1; i < argc; i++)
		{
			if(strcmp("--version",argv[i]) == 0)
			{
				//输出版本信息
				if (i != 1) exit(0);
				printVersion();
				par.imageNum = -1;
				break;
			}
			else if(strcmp("-h",argv[i]) == 0 || strcmp("--help",argv[i]) == 0)
			{
				//输出help
				if (i != 1) exit(0);
				printHelp();
				par.imageNum = -1;
				break;
			}
			else if (strcmp("-v",argv[i]) == 0 || strcmp("--verbose",argv[i]) == 0)
			{
				//屏幕输出
				*verbose = true;
			}
			else
			{
				//添加路径
				par.imagePath[par.imageNum] = argv[i];
				//从path中获取最后一个路径分隔符和.并将内容copy到inputPath中
				j = 0;
				posSplit = -1;
				posDot = -1;
				while(par.imagePath[par.imageNum][j])
				{
					inputPath[j] = par.imagePath[par.imageNum][j];
					//Windows系统分隔符多一个":"
#ifdef WIN32
					if (inputPath[j] == '\\' || inputPath[j] == '/' || inputPath[j] == ':')
#else
					if (inputPath[j] == '\\' || inputPath[j] == '/')
#endif
					{
						posSplit = j;
					}
					else if (inputPath[j] == '.')
					{
						posDot = j;
					}
					j++;
				}
				inputPath[j] = '\0';
				if(posSplit != -1)
				{
					//设置inputName
					strcpy(inputName,&(inputPath[posSplit + 1]));
					par.imageInputName[par.imageNum] = (char *)malloc(strlen(inputName) + 1);
					strcpy(par.imageInputName[par.imageNum],inputName);
					//设置inputPath
					inputPath[posSplit + 1] = '\0';
					par.imageInputPath[par.imageNum] = (char *)malloc(posSplit + strlen(inputName) + 2);
					strcpy(par.imageInputPath[par.imageNum],inputPath);
					strcat(par.imageInputPath[par.imageNum],inputName);
					//设置outputPath
					par.imageOutputPath[par.imageNum] = (char *)malloc(posSplit + strlen("_output") + 2);
					strcpy(outputPath,inputPath);
					strcpy(par.imageOutputPath[par.imageNum],outputPath);
				}
				else
				{
					//设置inputName
					strcpy(inputName,inputPath);
					par.imageInputName[par.imageNum] = (char *)malloc(strlen(inputName) + 1);
					strcpy(par.imageInputName[par.imageNum],inputName);
					//设置inputPath
					inputPath[0] = '\0';
					par.imageInputPath[par.imageNum] = (char *)malloc(strlen(inputName) + 1);
					strcpy(par.imageInputPath[par.imageNum],inputName);
					//设置outputPath
					par.imageOutputPath[par.imageNum] = (char *)malloc(strlen(inputName) + strlen("_output") + 1);
					strcpy(outputPath,inputPath);
					strcpy(par.imageOutputPath[par.imageNum],outputPath);
				}

				//设置outputName为balabala_output.扩展名,没有扩展名则balabala_output
				par.imageOutputName[par.imageNum] = (char *)malloc(strlen(inputName) + strlen("_output") + 1);
				posDot -= posSplit; //修正dot的位置
				if(posDot > 0)	//有扩展名
				{
					//提取扩展名
					strcpy(exName,&inputName[posDot]);
					strcpy(outputName,inputName);
					outputName[posDot == 0 ? posDot : posDot - 1] = '\0';
					strcat(outputName,"_output.");
					strcat(outputName,exName);
				}
				else	//无扩展名
				{
					strcpy(outputName,inputName);
					strcat(outputName,"_output");
				}
				strcpy(par.imageOutputName[par.imageNum],outputName);
				strcat(par.imageOutputPath[par.imageNum],outputName);
				//           \bin\a.bmp   split = 4  dot = 6    dot - split > 0
				par.imageNum++;
			}
		}
	}
	return par;
}
Example #4
0
int main(int argc, char** argv) {

    // Argument parsing

    if ((argc == 1) ||
        ((argc >= 2) && (std::string("--help") == argv[1]))) {
        printHelp();
        return 0;
    }

    if ((argc == 2) && (std::string("--version") == argv[1])) {
        printVersion();
        return 0;
    }

    std::string src = "";
    std::string dst = "";

    // Figure out source and dest filenames
    if (argc >= 4) {
        if (std::string("-o") != argv[1]) {
            printf("Invalid command line to GLSLCheck.  Expected '-o' or"
                " filename as 1st argument, found: '%s'\n", argv[1]);
            return -1;
        }
        dst = argv[2];
        src = argv[3];
    } else {
        src = argv[1];
    }

    if (! fileExists(src)) {
        printf("GLSLCheck error : input file '%s' not found\n", src.c_str());
        return -4;
    }

    if (endsWith(dst, "/") || endsWith(dst, "\\")) {
        if (! fileExists(dst.substr(0, dst.size() - 1))) {
            printf("GLSLCheck error : output directory '%s' not found\n", dst.c_str());
            return -5;
        }

        // Add the filename part of src to dst, since dst is a directory
        dst = dst + filenameBaseExt(src);
    }


    Mode mode;
    if (endsWith(toLower(src), ".vert")) {
        mode = VERTEX;
    } else if (endsWith(toLower(src), ".frag")) {
        mode = FRAGMENT;
    } else {
        printf("Invalid filename; source file must end with .vert or .frag\n");
        return -2;
    }

    // We must create a GL context before loading extensions.
    GWindowSettings settings;
    settings.visible = false;
    settings.width = 200;
    settings.height = 200;

    GWindow* window;
    #ifdef G3D_WIN32
        window = new Win32Window(settings);
    #else
        window = new SDLWindow(settings);
    #endif
    GLCaps::loadExtensions();

    if (! VertexAndPixelShader::fullySupported()) {
        printf("GLSL not supported by your graphics card and driver.\n");
        return -3;
    }

    int result = check(mode, src);

    if ((result == 0) && (dst != "")) {
        copyFile(src, dst);
    }

    delete window;
    return result;
}
Example #5
0
	/**
	* Given an argument count and list, parses the arguments
	* and sets the global options as desired
	*
	* @param argc
	*		The number of arguments
	* @param argv
	*		The list of cmd line arguments
	* @param paths
	*		A vector of strings to be filled with lint paths
	*/
	void parseArgs(int argc, char* argv[], vector<string> &paths) {
		// Set default values
		Options.RECURSIVE	= false;
		Options.CMODE		= false;
		Options.JSON		= false;
		Options.VERBOSE		= false;
		Options.LEVEL		= Lint::ADVICE;
		bool HELP			= false;

		bool l1 = false;
		bool l2 = false;
		bool l3 = false;

		enum ArgType {
			BOOL, INT
		};
		struct Arg {
			ArgType type;
			const void *ptr;
		};

		// Map values to their cmd line flags
		Arg argHelp			= { ArgType::BOOL, &HELP };
		Arg argRecursive	= { ArgType::BOOL, &Options.RECURSIVE };
		Arg argCMode		= { ArgType::BOOL, &Options.CMODE };
		Arg argJSON			= { ArgType::BOOL, &Options.JSON };
		Arg argVerbose		= { ArgType::BOOL, &Options.VERBOSE };

		Arg argLevel		= { ArgType::INT,  &Options.LEVEL };
		Arg argL1 = { ArgType::BOOL, &l1 };
		Arg argL2 = { ArgType::BOOL, &l2 };
		Arg argL3 = { ArgType::BOOL, &l3 };

		static const unordered_map<string, Arg &> params = {
			{ "-h", argHelp },
			{ "--help", argHelp },

			{ "-r", argRecursive },
			{ "--recursive", argRecursive },

			{ "-c", argCMode },
			{ "--cmode", argCMode },

			{ "-j", argJSON },
			{ "--json", argJSON },

			{ "-l", argLevel },
			{ "--level", argLevel },
			{ "-l1", argL1 },
			{ "-l2", argL2 },
			{ "-l3", argL3 },

			{ "-v", argVerbose },
			{ "--verbose", argVerbose }
		};

		// Loop over the given argument list
		for (int i = 1; i < argc; ++i) {
			
			// If the current argument is in the map
			// then set its value to true
			auto it = params.find(string(argv[i]));
			if (it != params.end()) {
				
				if (it->second.type == ArgType::BOOL) {
					bool *arg = (bool*)it->second.ptr;
					*arg = true;
				}
				else if (it->second.type == ArgType::INT) {
					int *arg = (int*) it->second.ptr;

					++i;
					if (i >= argc) {
						printf("Missing (int) value for parameter: %s\n\n", 
							it->first.c_str());
						printHelp();
					}

					int val = atoi(argv[i]) - 1;
					*arg = val;
					continue;
				}
			}
			else {
				// Push another path onto the lint list
				string p = argv[i];
				if (p.back() == '/' || p.back() == '\\') {
					p.erase(p.end()-1, p.end());
				}
				paths.push_back(move(p));
			}
		}

		if (l1) {
			Options.LEVEL = Lint::ERROR;
		}
		else if (l2) {
			Options.LEVEL = Lint::WARNING;
		}
		else if (l3) {
			Options.LEVEL = Lint::ADVICE;
		}

		// Make sure level was given a correct value
		Options.LEVEL = ((Options.LEVEL > Lint::ADVICE) ? 
			Lint::ADVICE : 
			((Options.LEVEL < Lint::ERROR) ? 
				Lint::ERROR : 
				Options.LEVEL));

		if (paths.size() == 0) {
			paths.push_back(".");
		}

		if (HELP) {
			printHelp();
		}
	};
Example #6
0
int main(int argc, char* argv[])
{
	QApplication app(argc, argv);
	app.setOrganizationName("Graphem");
	app.setApplicationName("Graphem");

	QCA::Initializer crypto_init;
	InputWidget *input = new InputWidget();

	WindowMode mode = CONFIG;
	int tries = 0; //ignored if mode != ASK

	for(int i = 1; i < argc; i++) {
		if(argv[i] == QString("--help")) {
			printHelp(argv[0]);
			return 0;
		} else if(argv[i] == QString("--ask")) {
			mode = ASK;
		} else if(argv[i] == QString("--lock")) {
			mode = LOCK;
		} else if(argv[i] == QString("--tries")) {
			if(i+1 >= argc)
				break; //parameter not found

			tries = QString(argv[i+1]).toInt();
			i++;
		} else if(argv[i] == QString("-v") or argv[i] == QString("--verbose")) {
			input->auth()->setVerbose(true);

		}

#ifndef NO_DEBUG
		else if(argv[i] == QString("--print-data")) {
			QObject::connect(input, SIGNAL(dataReady()),
				input, SLOT(printData()));
		} else if(argv[i] == QString("--print-pattern")) {
			input->auth()->setPrintPattern(true);
		}
#endif

		else {
			std::cerr << "Unknown command line option '" << argv[i] << "'\n";
			printHelp(argv[0]);
			return 1;
		}
	}

	if(mode == CONFIG) { //show main window
		MainWindow *main = new MainWindow(input);
		//main->setWindowIcon(QIcon("icon.png"));
		main->setWindowTitle(GRAPHEM_VERSION);
		main->show();
	} else {
		if(!input->hashLoaded()) {
			std::cerr << "Couldn't load key pattern! Please start Graphem without any arguments to create one.\n";
			return 1;
		}

		QObject::connect(input->auth(), SIGNAL(passed()),
			input, SLOT(quit()));

		//input->setWindowIcon(QIcon("icon.png"));

		if(mode == ASK) {
			input->setWindowTitle(QObject::tr("%1 - Press ESC to cancel").arg(GRAPHEM_VERSION));
			new QShortcut(QKeySequence("Esc"), input, SLOT(exit()));
			input->auth()->setTries(tries);
			input->showMaximized();
		} else { //mode == LOCK
			input->setWindowTitle(GRAPHEM_VERSION);
			input->setGrab(true);

			//for full screen, we strip WM decorations and resize the window manually
			input->setWindowFlags(Qt::X11BypassWindowManagerHint);
			input->setVisible(true);
			QDesktopWidget dw;
			input->setGeometry(dw.screenGeometry());
		}
	}

	return app.exec();
}
Example #7
0
struct config parseArguments(double argc, char** argv) {
	struct config c;
	c.exposure = -1;
	c.pixel = 96;
	c.frames = 1;
	c.filename = std::string("default.fit");
	c.aoi[0] = -1;
	c.bmp = false;
	c.jpg = false;
	c.sex = false;
	c.error = false;
	c.blocks = 1;
	c.degrees = 0.0;
	char o;
	static struct option opts[] = {
		{"exposure", required_argument, 0, 'e'},
		{"frames", required_argument, 0, 'n'},
		{"pixelclock", required_argument, 0, 'p'},
		{"file", required_argument, 0, 'f'},
		{"aoi", required_argument, 0, 'a'},
		{"bmp", no_argument, 0, 'b'},
		{"jpg", no_argument, 0, 'j'},
		{"sex", no_argument, 0, 's'},
		{"help", no_argument, 0, 'h'},
		{"blocks",required_argument, 0, 'm'},
		{"degrees",required_argument, 0, 'd'},
		{0, 0, 0, 0}
	};
	int i = 0;
	o = getopt_long (argc, argv, "e:n:p:f:a:m:d:bjsh", opts, &i);
	while (o != -1) {
		std::string aoi;
		int pos;
		switch (o) {
		case 0:
			std::cout << "Option "<< opts[i].name;
			if (optarg) {
				std::cout << " with argument " << optarg << std::endl;
			} else {
				std::cout << " without argument." << std::endl;
			}
			break;
		case 'e':
			std::cout << "Known Option " << o << " with argument " << optarg << std::endl;
			c.exposure = std::stoi(optarg);
			break;
		case 'n':
			std::cout << "Known Option " << o << " with argument " << optarg << std::endl;
			c.frames = std::stoi(optarg);
			break;
		case 'm':
			std::cout << "Known Option " << o << " with argument " << optarg << std::endl;
			c.blocks = std::stoi(optarg);
			break;
		case 'd':
			std::cout << "Known Option " << o << " with argument " << optarg << std::endl;
			c.degrees = std::stoi(optarg);
			std::cout << "Known Option " << o << " with argument " << c.degrees << std::endl;
			break;
		case 'p':
			std::cout << "Known Option " << o << " with argument " << optarg << std::endl;
			c.pixel = std::stoi(optarg);
			break;
		case 'f':
			std::cout << "Known Option " << o << " with argument " << optarg << std::endl;
			c.filename = optarg;
			break;
		case 'a':
			std::cout << "Known Option " << o << " with argument " << optarg << std::endl;
			aoi = std::string(optarg);
			if(std::count(aoi.begin(), aoi.end(), ',') != 3) {
				std::cout << "Error!" << std::endl;
				c.error = true;
			} else {
				for (int i = 0; i < 4; i++) {
					pos = aoi.find(',');
					if (pos != aoi.npos) {
						c.aoi[i] = std::stoi(aoi.substr(0, pos));
						aoi = aoi.substr(pos+1, aoi.size()-pos);
					} else {
						c.aoi[i] = std::stoi(aoi);
					}
				}
			}
			break;
		case 'b':
			c.bmp = true;
			break;
		case 'j':
			c.jpg = true;
			break;
		case 's':
			c.sex = true;
			break;
		case 'h':
			printHelp(argv[0]);
			c.error = true;
			break;
		default:
			std::cout << "Unknown option " << o;
			if (optarg) {
				std::cout << " with argument " << optarg << std::endl;
			} else {
				std::cout << " without argument." << std::endl;
			}
			printHelp(argv[0]);
			c.error = true;
		}
		o = getopt_long (argc, argv, "e:n:p:f:a:m:d:bjsh", opts, &i);
	}
	return c;
}
Example #8
0
static void showError(const char * pgm_msg) {
	Serial.pgm_print(PSTR("Error "));
	Serial.pgm_println(pgm_msg);
	Serial.println();
	printHelp();
}
Example #9
0
int main( int argc, char **argv )
{
    QCoreApplication app(argc, argv);

    PolyArchiveExtractor qsaExtractor( QStringList() << "qsa",
				       "qsauncompress \1 \2" );
    PolyArchiveExtractor tarExtractor( QStringList() << "tar",
				       "tar -C \2 -xf \1" );
    PolyArchiveExtractor tazExtractor( QStringList() << "taz",
				       "tar -C \2 -Zxf \1" );
    PolyArchiveExtractor tbz2Extractor( QStringList() << "tbz" << "tbz2",
					"tar -C \2 -jxf \1" );
    PolyArchiveExtractor tgzExtractor( QStringList() << "tgz",
				       "tar -C \2 -zxf \1" );
    PolyArchiveExtractor zipExtractor( QStringList() << "zip",
				       "unzip \1 -d \2" );

    PolyUncompressor bz2Uncompressor( QStringList() << "bz" << "bz2",
				      "bunzip2 -c \1 > \2" );
    PolyUncompressor gzAndZUncompressor( QStringList() << "gz" << "z" << "Z",
					 "gunzip -c \1 > \2" );
    PolyUncompressor zipUncompressor( QStringList() << "zip",
				      "unzip -c \1 > \2" );

    CCodeParser cParser;
    CppCodeParser cppParser;

    Tree *cppTree = treeForLanguage( cppParser.language() );

    QsCodeParser qsParser( cppTree );
    QsaKernelParser qsaKernelParser( cppTree );
    JambiApiParser jambiParser(cppTree);

    PlainCodeMarker plainMarker;
    CppCodeMarker cppMarker;
    JavaCodeMarker javaMarker;
    QsCodeMarker qsMarker;

    ApiGenerator apiGenerator;
    HtmlGenerator htmlGenerator;
    JavadocGenerator javadocGenerator;
    LoutGenerator loutGenerator;
    ManGenerator manGenerator;
    SgmlGenerator smglGenerator;
    WebXMLGenerator webxmlGenerator;

    QStringList qdocFiles;
    QString opt;
    int i = 1;

    while ( i < argc ) {
	opt = argv[i++];

	if ( opt == "-help" ) {
	    printHelp();
	    return EXIT_SUCCESS;
	} else if ( opt == "-version" ) {
	    printVersion();
	    return EXIT_SUCCESS;
	} else if ( opt == "--" ) {
	    while ( i < argc )
		qdocFiles.append( argv[i++] );
        } else if ( opt.startsWith("-D") ) {
            QString define = opt.mid(2);
            defines += define;
        } else if (opt == "-slow") {
            slow = true;
	} else {
	    qdocFiles.append( opt );
	}
    }

    if ( qdocFiles.isEmpty() ) {
	printHelp();
	return EXIT_FAILURE;
    }

    foreach (QString qf, qdocFiles)
	processQdocconfFile( qf );

    qDeleteAll(trees);
    return EXIT_SUCCESS;
}
Example #10
0
int main(int argc, char** argv )
{
	int fd;						/* file descriptor */
	char comm[20];					/* point to command string */
	bzero(comm, sizeof(comm));
	char rbuf[RCVBUF_SIZE];		/* receive buffer */
	__tod_t texp;				/* to receive the expended time */
	int r;
	char* port = "/dev/ttyUSB0";
        speed_t speed = B9600;


	switch ( argc )
	{
	    case 2:
		if (!strcmp(argv[1], "--help") || !strcmp (argv[1], "-h") )
		    printManual();
		else
		    printHelp();
		exit(-1);
	    case 3:
		contstr(argv[1], argv[2], comm );
		break;
    	    case 4:
		contstr( argv[1], argv[2], comm );
    		speed = consspeed( argv[3] );
    		break;
    	    case 5:
		contstr( argv[1], argv[2], comm );
		speed = consspeed( argv[3] );
    		port = argv[4];
    		break;
    	    default:
		printHelp();
		exit  ( -1 );
    	    
        } 
	fd = sio_open( port, speed, DATA_BITS_8, NO_PARITY,
				  ONE_STOP_BIT);
	if (fd == ERR_PORT_OPEN) {
		printf("open port failed!\n");
		return (-1);
	}


        comm[strlen(comm)] = '\r';
        printf("send command: %s\n", comm  );
	
	sio_set_noncan(fd);
	sio_set_timer(fd, 0, 10);	/* set timeout for 1 sec */

	r = i7k_send_readt(fd, comm, rbuf, RCVBUF_SIZE, &texp);
	//char* cmd = "$01P\r";
	//r = i7k_send_readt(fd, cmd, rbuf, RCVBUF_SIZE, &texp);
	
	char buff[16];
	memcpy (buff, rbuf+1, 15);

	switch (r) {
	case 0:
		printf("time-out!\ntime expended: %llu us\n", texp);
		break;
	case -1:
		printf("error!\ntime expended: %llu us\n", texp);
		break;
	default:
		printf("ret: %s\ntime expended: %llu us\n", buff, texp);
		break;
	}
	sio_close(fd);

	return (0);
}
Example #11
0
void RepRapPCBTest::loop() {
	pcb.update();
	reader.update();
	btn.update();
	led.update();

	if (reader.available()) {
		char *line = reader.readln();
		Serial.println(line);
		switch (line++[0]) {
		case 'i':
			stop();
			repRapMode = InitializeAllMotors;
			modeState= 0;
		case 'a':
			doAxis(pgmAxisNameX, line, pcb.axisX);
			doAxis(pgmAxisNameY, line, pcb.axisY);
			doAxis(pgmAxisNameZ, line, pcb.axisZ);
			break;
		case 'x':
			doAxis(pgmAxisNameX, line, pcb.axisX);
			break;
		case 'y':
			doAxis(pgmAxisNameY, line, pcb.axisY);
			break;
		case 'z':
			doAxis(pgmAxisNameZ, line, pcb.axisZ);
			break;
		case 'h':
			printHelp();
			break;
		case 's':
			stop();
			break;
		default:
			showError(PSTR("invalid command"));
			break;
		}
	}

	switch (repRapMode) {
	case AlterDelayBetweenSteps:
		doAlterDelayBetweenSteps();
		break;
	case GotoStep:
		doGotoStep();
		break;
	case DetermineAvailableSteps:
		doDetermineAvailableSteps();
		break;
	case MoveForthAndBackAtSpeed:
		doMoveForthAndBackAtSpeed();
		break;
	case InitializeAllMotors:
		doInitializeAllMotors();
		break;
	case StepTicking:
		doStepTicking();
		if (btn.isClicked()) {
			modeState = !modeState;
			btn.reset();
		}
		break;
	case Idle:
	default:
		break;
	}

	if (btn.isLongClicked()) {
		stop();
		printHelp();
	} else if (btn.isClicked()) {
		stop();
	}
}
Example #12
0
    int Tool::main( int argc , char ** argv, char ** envp ) {
        static StaticObserver staticObserver;

        setGlobalAuthorizationManager(new AuthorizationManager(new AuthzManagerExternalStateMock()));

        mongo::runGlobalInitializersOrDie(argc, argv, envp);

        // hide password from ps output
        for (int i=0; i < (argc-1); ++i) {
            if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--password")) {
                char* arg = argv[i+1];
                while (*arg) {
                    *arg++ = 'x';
                }
            }
        }

        if (!toolGlobalParams.useDirectClient) {
            if (toolGlobalParams.noconnection) {
                // do nothing
            }
            else {
                string errmsg;

                ConnectionString cs = ConnectionString::parse(toolGlobalParams.connectionString,
                                                              errmsg);
                if ( ! cs.isValid() ) {
                    toolError() << "invalid hostname [" << toolGlobalParams.connectionString << "] "
                              << errmsg << std::endl;
                    ::_exit(-1);
                }

                _conn = cs.connect( errmsg );
                if ( ! _conn ) {
                    toolError() << "couldn't connect to [" << toolGlobalParams.connectionString
                              << "] " << errmsg << std::endl;
                    ::_exit(-1);
                }

                toolInfoOutput() << "connected to: " << toolGlobalParams.connectionString
                                 << std::endl;
            }

        }
        else {
            verify( lastError.get( true ) );

            Client::initThread("tools");
            _conn = new DBDirectClient();
            storageGlobalParams.dbpath = toolGlobalParams.dbpath;
            try {
                acquirePathLock();
            }
            catch ( DBException& ) {
                toolError() << std::endl << "If you are running a mongod on the same "
                             "path you should connect to that instead of direct data "
                              "file access" << std::endl << std::endl;
                dbexit( EXIT_FS );
                ::_exit(EXIT_FAILURE);
            }

            FileAllocator::get()->start();

            dur::startup();
        }

        int ret = -1;
        try {
            if (!toolGlobalParams.useDirectClient && !toolGlobalParams.noconnection)
                auth();
            ret = run();
        }
        catch ( DBException& e ) {
            toolError() << "assertion: " << e.toString() << std::endl;
            ret = -1;
        }
        catch(const boost::filesystem::filesystem_error &fse) {
            /*
              https://jira.mongodb.org/browse/SERVER-2904

              Simple tools that don't access the database, such as
              bsondump, aren't throwing DBExceptions, but are throwing
              boost exceptions.

              The currently available set of error codes don't seem to match
              boost documentation.  boost::filesystem::not_found_error
              (from http://www.boost.org/doc/libs/1_31_0/libs/filesystem/doc/exception.htm)
              doesn't seem to exist in our headers.  Also, fse.code() isn't
              boost::system::errc::no_such_file_or_directory when this
              happens, as you would expect.  And, determined from
              experimentation that the command-line argument gets turned into
              "\\?" instead of "/?" !!!
             */
#if defined(_WIN32)
            if (/*(fse.code() == boost::system::errc::no_such_file_or_directory) &&*/
                (fse.path1() == "\\?"))
                printHelp(cerr);
            else
#endif // _WIN32
                toolError() << "error: " << fse.what() << std::endl;

            ret = -1;
        }

        if ( currentClient.get() )
            currentClient.get()->shutdown();

        if (toolGlobalParams.useDirectClient)
            dbexit( EXIT_CLEAN );

        fflush(stdout);
        fflush(stderr);
        ::_exit(ret);
    }
Example #13
0
int main(int argc, char *argv[]) {
  std::string command,
              ucMode,
              volMode,
              inodeMapFile,
              diskMapFile;
  uint64_t    maxUcBlockSize;

  po::options_description desc("Allowed Options");
  po::positional_options_description posOpts;
  posOpts.add("command", 1);
  posOpts.add("ev-files", -1);
  desc.add_options()
    ("help", "produce help message")
    ("command", po::value< std::string >(&command), "command to perform [info|dumpimg|dumpfs|dumpfiles]")
    ("overview-file", po::value< std::string >(), "output disk overview information")
    ("unallocated", po::value< std::string >(&ucMode)->default_value("none"), "how to handle unallocated [none|fragment|block]")
    ("max-unallocated-block-size", po::value< uint64_t >(&maxUcBlockSize)->default_value(std::numeric_limits<uint64_t>::max()), "Maximum size of an unallocated entry, in blocks")
    ("ev-files", po::value< std::vector< std::string > >(), "evidence files")
    ("inode-map-file", po::value<std::string>(&inodeMapFile)->default_value(""), "optional file to output containing directory entry to inode map")
    ("disk-map-file", po::value<std::string>(&diskMapFile)->default_value(""), "optional file to output containing disk data to inode map");

  po::variables_map vm;
  try {
    po::store(po::command_line_parser(argc, argv).options(desc).positional(posOpts).run(), vm);
    po::notify(vm);

    std::shared_ptr<LbtTskAuto> walker;

    std::vector< std::string > imgSegs;
    if (vm.count("ev-files")) {
      imgSegs = vm["ev-files"].as< std::vector< std::string > >();
    }
    if (vm.count("help")) {
      printHelp(desc);
    }
    else if (vm.count("command") && vm.count("ev-files") && (walker = createVisitor(command, std::cout, imgSegs))) {
      std_binary_io();

      boost::scoped_array< const char* >  segments(new const char*[imgSegs.size()]);
      for (unsigned int i = 0; i < imgSegs.size(); ++i) {
        segments[i] = imgSegs[i].c_str();
      }
      if (0 == walker->openImageUtf8(imgSegs.size(), segments.get(), TSK_IMG_TYPE_DETECT, 0)) {
        if (vm.count("overview-file")) {
          std::ofstream file(vm["overview-file"].as<std::string>().c_str(), std::ios::out);
          file << *(walker->getImage(imgSegs));
          file.close();
        }

        walker->setVolFilterFlags((TSK_VS_PART_FLAG_ENUM)(TSK_VS_PART_FLAG_ALLOC | TSK_VS_PART_FLAG_UNALLOC | TSK_VS_PART_FLAG_META));
        walker->setFileFilterFlags((TSK_FS_DIR_WALK_FLAG_ENUM)(TSK_FS_DIR_WALK_FLAG_RECURSE | TSK_FS_DIR_WALK_FLAG_UNALLOC | TSK_FS_DIR_WALK_FLAG_ALLOC));
        if (ucMode == "fragment") {
          walker->setUnallocatedMode(LbtTskAuto::FRAGMENT);
          walker->setMaxUnallocatedBlockSize(maxUcBlockSize);
        }
        else if (ucMode == "block") {
          walker->setUnallocatedMode(LbtTskAuto::BLOCK);
        }
        else {
          walker->setUnallocatedMode(LbtTskAuto::NONE);
        }
        if (0 == walker->start()) {
          walker->startUnallocated();
          walker->finishWalk();
          std::vector<std::future<void>> futs;
          if (vm.count("disk-map-file") && command == "dumpfs") {
            futs.emplace_back(std::async(outputDiskMap, diskMapFile, walker));
          }
          if (vm.count("inode-map-file") && command == "dumpfs") {
            futs.emplace_back(std::async(outputInodeMap, inodeMapFile, walker));
          }
          for (auto& fut: futs) {
            fut.get();
          }
          return 0;
        }
        else {
          std::cout.flush();
          std::cerr << "Had an error parsing filesystem" << std::endl;
          for (auto& err: walker->getErrorList()) {
            std::cerr << err.msg1 << " " << err.msg2 << std::endl;
          }
        }
      }
      else {
        std::cerr << "Had an error opening the evidence file" << std::endl;
        for (unsigned int i = 0; i < imgSegs.size(); ++i) {
          std::cerr << " ** seg[" << i << "] = " << imgSegs[i] << std::endl;
        }
        return 1;
      }
    }
    else {
      std::cerr << "Error: did not understand arguments\n\n";
      printHelp(desc);
      return 1;
    }
  }
  catch (std::exception& err) {
    std::cerr << "Error: " << err.what() << "\n\n";
    printHelp(desc);
    return 1;
  }
  return 0;
}
Example #14
0
int main(int argc,char** argv){
	
	//Seed the timer.
	srand(time(0));
	//printf("Begin GPU PBF..\n");

	//Does the user need help?
	if(wasArgSpecified("--help",argv,argc)!=0){
		printHelp();
		return 0;
	}
	
	//Initialize with default configuration.
	BloomOptions_t bloomOptions_t;
	setDefault(&bloomOptions_t);	
	//Parse the user's configuration.
	getConfiguration(&bloomOptions_t,argv,argc);
	bloomOptions_t.prob = calculateProb(bloomOptions_t.freq,bloomOptions_t.numKeys);
	bloomOptions_t.size = calculateSize(bloomOptions_t.numHashes,bloomOptions_t.numKeys,bloomOptions_t.prob);

	//showDetails(&bloomOptions_t);

	//Create the bloom filter being used, and initialize it with all 0's.
	char* bloom = (char*)malloc(sizeof(char)*bloomOptions_t.size);
	memset(bloom,0,bloomOptions_t.size);

	//Allocate the GPU bloom filter.
	char* dev_bloom = allocateAndCopyChar(bloom,bloomOptions_t.size); 
	if(dev_bloom==0){
		printf("Could not allocate the bloom filter \n");
		return -1;	
	}

	//Read input keys and insert to PBF
	char* fileName = (char*)malloc(sizeof(char)*50);
	sprintf(fileName,"./data/total_keys.txt");
	WordAttributes* allKeys = loadFileByName(fileName);
	int total_keys = allKeys->numWords;	
	int randOffset = rand()%2432+10;			
	insertWordsPBF(dev_bloom,bloomOptions_t.size,allKeys->currentWords,allKeys->positions,allKeys->numWords,allKeys->numBytes,bloomOptions_t.numHashes,bloomOptions_t.device,bloomOptions_t.prob,randOffset);
	freeWordAttributes(allKeys);
			
	//Query PBF
	sprintf(fileName,"./data/distinct_keys.txt");
	WordAttributes* distinctKeys = loadFileByName(fileName);
	int distinct_keys = distinctKeys->numWords;
	//printf("distinct keys = %d, total keys = %d\n",distinct_keys,total_keys);
	int* results = (int*)calloc(sizeof(int)*distinct_keys,sizeof(int));
	queryWordsPBF(dev_bloom,bloomOptions_t.size,distinctKeys->currentWords,distinctKeys->positions,distinctKeys->numWords,
distinctKeys->numBytes,bloomOptions_t.numHashes,bloomOptions_t.device,results);
	freeWordAttributes(distinctKeys);

	//Read the actual frequency of keys
	int* actual = (int*)calloc(sizeof(int)*distinct_keys,sizeof(int));
	FILE* actualFreqFile = fopen("./data/freq.txt","r");
	if(!actualFreqFile){
		printf("Can not open actual frequency file!\n");
		return -1;
	}
	for(int i = 0; i < distinct_keys; i++){
		char* temp = (char*)malloc(sizeof(char)*15);
		if(fgets(temp,15,actualFreqFile)!=NULL){
			int len = strlen(temp);
			temp[len-1]='\0'; 		
			actual[i]=atoi(temp);
			//printf("%d: actual = %d\n",i,actual[i]);
		}
		free(temp);
	}
	
	//Copy the bloom filter to main memory.
	//copyCharsToHost(bloom,dev_bloom,bloomOptions_t.size);

	//Write the result to output file
	//data format: index, number of 1s, calculated frequency, actual frequency, relative error
	if(bloomOptions_t.pbfOutput){
		FILE* outputFile = fopen(bloomOptions_t.pbfOutput,"w");
		writeStats(outputFile,actual,results,distinct_keys, bloomOptions_t.numHashes,bloomOptions_t.prob,total_keys,bloomOptions_t.size);
		fclose(outputFile);
	}
	
	free(fileName);
	free(actual);
	free(results);
	freeChars(dev_bloom);	
	free(bloom);
	//printf("\n");
	return 0;
}
Example #15
0
static int parseCommandLine(int argc, const char **argv, Params *params)
{
	memset(params, 0, sizeof(Params));

	if (argc < 2 || argv[1][0] != '-')
		return printHelp("Invalid command");

	int        index = 1;
	const char *arg  = argv[index];

	if (!strcmp(arg, "-l"))
	{
		if (argc != 2)
			return printHelp("No arguments are allowed after '-l'\n");
		params->command = 'l';
		return 0;
	}

	if (!strcmp(arg, "-r"))
	{
		if (argc < 3)
			return printHelp("No reader number are specified after '-r'\n");
		params->readerNr = atoi(argv[2]);

		index += 2;
		arg    = argv[index];
	}

	if (!strcmp(arg, "-s"))
	{
		if (argc - index != 2)
			return printHelp("Only 1 argument allowed after '-s'\n");
		params->command = 's';
		params->timeout = atoi(argv[index + 1]);
		return 0;
	}

	if (!strcmp(arg, "-a"))
	{
		if (argc - index < 2)
			return printHelp("No arguments specified after '-a'\n");
		params->command   = 'a';
		params->apduCount = argc - index - 1;
		params->apdus     = argv + (index + 1);
	}
	else if (!strcmp(arg, "-t"))
	{
		if (argc - index > 2)
			return printHelp("Only 1 argument allowed after '-t'\n");
		params->command = 't';
		if (argc - index == 2)
			params->chipnr = argv[index + 1];
	}
	else if (!strcmp(arg, "-f"))
	{
		if (argc - index > 1)
			return printHelp("No arguments are allowed after '-f'\n");
		params->command = 'f';
	}
	else if (!strcmp(arg, "-x"))
	{
		if (argc < 3)
			return printHelp("No tests specified for '-x'\n");
		params->command = 'x';
		params->test    = atoi(argv[2]);
	}

	else
		return printHelp("Unknown command\n");

	return 0;
}
int main(int argc, char* argv[]) {
  char *device = NULL, c, *bind_mask = NULL;
  int snaplen = DEFAULT_SNAPLEN, rc, watermark = 0, rehash_rss = 0;
  packet_direction direction = rx_only_direction;
  long i;
  u_int16_t cpu_percentage = 0, poll_duration = 0;
  u_int32_t version;
  u_int32_t flags = 0;

  startTime.tv_sec = 0;
  thiszone = gmt2local(0);
  numCPU = sysconf( _SC_NPROCESSORS_ONLN );
  memset(thread_core_affinity, -1, sizeof(thread_core_affinity));

  while((c = getopt(argc,argv,"hi:l:mvae:w:b:rp:g:")) != -1) {
    switch(c) {
    case 'h':
      printHelp();
      return(0);
      break;
    case 'a':
      wait_for_packet = 0;
      break;
    case 'e':
      switch(atoi(optarg)) {
      case rx_and_tx_direction:
      case rx_only_direction:
      case tx_only_direction:
	direction = atoi(optarg);
	break;
      }
      break;
    case 'l':
      snaplen = atoi(optarg);
      break;
    case 'i':
      device = strdup(optarg);
      break;
    case 'm':
      use_extended_pkt_header = 1;
      break;
    case 'v':
      verbose = 1;
      break;
    case 'w':
      watermark = atoi(optarg);
      break;
    case 'b':
      cpu_percentage = atoi(optarg);
      break;
    case 'r':
      rehash_rss = 1;
      break;
    case 'p':
      poll_duration = atoi(optarg);
      break;
    case 'g':
      bind_mask = strdup(optarg);
      break;
    }
  }

  if(verbose) watermark = 1;
  if(device == NULL) device = DEFAULT_DEVICE;

  printf("Capturing from %s\n", device);

  flags |= PF_RING_PROMISC; /* hardcode: promisc=1 */
#if 0
  flags |=  PF_RING_DNA_FIXED_RSS_Q_0;
#else
  flags |= PF_RING_DNA_SYMMETRIC_RSS;  /* Note that symmetric RSS is ignored by non-DNA drivers */
#endif
  if(use_extended_pkt_header) flags |= PF_RING_LONG_HEADER;

  num_channels = pfring_open_multichannel(device, snaplen, flags, ring);
  
  if(num_channels <= 0) {
    fprintf(stderr, "pfring_open_multichannel() returned %d [%s]\n", num_channels, strerror(errno));
    return(-1);
  }


  if (num_channels > MAX_NUM_THREADS)
  {
     printf("WARNING: Too many channels (%d), using %d channels\n", num_channels, MAX_NUM_THREADS);
     num_channels = MAX_NUM_THREADS;
  }
  else if (num_channels > numCPU)
  {
     printf("WARNING: More channels (%d) than available cores (%d), using %d channels\n", num_channels, numCPU, numCPU);
     num_channels = numCPU;
  }
  else 
  {
    printf("Found %d channels\n", num_channels);
  }

  if(bind_mask != NULL)
  {
     char *id = strtok(bind_mask, ":");
     int idx = 0;

     while(id != NULL) {
        thread_core_affinity[idx++] = atoi(id) % numCPU;
        if(idx >= num_channels) break;
        id = strtok(NULL, ":");
     }
  }

  pfring_version(ring[0], &version);  
  printf("Using PF_RING v.%d.%d.%d\n",
	 (version & 0xFFFF0000) >> 16,
	 (version & 0x0000FF00) >> 8,
	 version & 0x000000FF);
  
  for(i=0; i<num_channels; i++)
  {
     char buf[32];
    
     snprintf(buf, sizeof(buf), "pfcount_multichannel-thread %ld", i);
     pfring_set_application_name(ring[i], buf);

     if((rc = pfring_set_direction(ring[i], direction)) != 0)
	fprintf(stderr, "pfring_set_direction returned %d [direction=%d] (you can't capture TX with DNA)\n", rc, direction);
    
     if((rc = pfring_set_socket_mode(ring[i], recv_only_mode)) != 0)
	fprintf(stderr, "pfring_set_socket_mode returned [rc=%d]\n", rc);

     if(watermark > 0) {
        if((rc = pfring_set_poll_watermark(ring[i], watermark)) != 0)
           fprintf(stderr, "pfring_set_poll_watermark returned [rc=%d][watermark=%d]\n", rc, watermark);
     }
#if 0    
  setup_steering(ring[0], "192.168.30.207", -1);

  /* UTDF */
  setup_steering(ring[0], "224.0.1.92", 1);
  setup_steering(ring[0], "224.0.1.94", 1);
  setup_steering(ring[0], "224.0.1.96", 1);

  /* BATS */
  setup_steering(ring[0], "224.0.62.2", 2);

  /* default: should go to channel 0 */
#endif
     if(rehash_rss)
        pfring_enable_rss_rehash(ring[i]);
    
     if(poll_duration > 0)
        pfring_set_poll_duration(ring[i], poll_duration);

     pfring_enable_ring(ring[i]);

     pthread_create(&pd_thread[i], NULL, packet_consumer_thread, (void*)i);
     usleep(500);
  }

  if(cpu_percentage > 0) {
    if(cpu_percentage > 99) cpu_percentage = 99;
    pfring_config(cpu_percentage);
  }

  signal(SIGINT, sigproc);
  signal(SIGTERM, sigproc);
  signal(SIGINT, sigproc);

  if(!verbose) {
    signal(SIGALRM, my_sigalarm);
    alarm(ALARM_SLEEP);
  }

  for(i=0; i<num_channels; i++) {
    pthread_join(pd_thread[i], NULL);
    pfring_close(ring[i]);
  }

  return(0);
}
Example #17
0
int main(int argc, char** args) {
    int argchar;
	char* infn = NULL;
	char* outfn = NULL;
	unsigned int row;
	int bits;
	FILE* fid = stdin;
	FILE* fout = stdout;
	int loglvl = LOG_MSG;
	char* progname = args[0];
	int bzero = 0;
	int outformat;
	qfits_header* hdr;
	unsigned int plane;
	off_t datastart;
	anbool onepass = FALSE;
	bl* pixcache = NULL;

#if HAVE_NETPBM
	struct pam img;
	tuple * tuplerow;
#else
	void* rowbuf;
#endif
	int W, H, depth, maxval;

    while ((argchar = getopt (argc, args, OPTIONS)) != -1)
        switch (argchar) {
		case '?':
		case 'h':
			printHelp(progname);
			exit(0);
		case 'v':
			loglvl++;
			break;
		case 'q':
			loglvl--;
			break;
		case 'o':
			outfn = optarg;
			break;
		}

	log_init(loglvl);
	log_to(stderr);
	fits_use_error_system();

	if (optind == argc) {
		// ok, stdin to stdout.
	} else if (optind == argc-1) {
		infn = args[optind];
	} else if (optind == argc-2) {
		infn = args[optind];
		outfn = args[optind+1];
	} else {
		printHelp(progname);
		exit(-1);
	}

	if (infn && !streq(infn, "-")) {
		fid = fopen(infn, "rb");
		if (!fid) {
			SYSERROR("Failed to open input file %s", infn);
			exit(-1);
		}
	}
	if (outfn) {
		fout = fopen(outfn, "wb");
		if (!fid) {
			SYSERROR("Failed to open output file %s", outfn);
			exit(-1);
		}
	} else
		outfn = "stdout";

#if HAVE_NETPBM
	pm_init(args[0], 0);
	pnm_readpaminit(fid, &img, 
					// PAM_STRUCT_SIZE isn't defined until Netpbm 10.23 (July 2004)
#if defined(PAM_STRUCT_SIZE)
					PAM_STRUCT_SIZE(tuple_type)
#else
					sizeof(struct pam)
#endif
);
	W = img.width;
	H = img.height;
	depth = img.depth;
	maxval = img.maxval;

	tuplerow = pnm_allocpamrow(&img);
	bits = pm_maxvaltobits(img.maxval); 
	bits = (bits <= 8) ? 8 : 16;

#else // No NETPBM

	if (parse_pnm_header(fid, &W, &H, &depth, &maxval)) {
		ERROR("Failed to parse PNM header from file: %s\n", infn ? infn : "<stdin>");
		exit(-1);
	}
	bits = 8 * maxval_to_bytes(maxval);

	rowbuf = malloc(W * depth * (bits/8));

#endif

	logmsg("Read file %s: %i x %i pixels x %i color(s); maxval %i\n",
		   infn ? infn : "stdin", W, H, depth, maxval);
	if (bits == 8)
		outformat = BPP_8_UNSIGNED;
	else {
		outformat = BPP_16_SIGNED;
		if (maxval >= INT16_MAX)
			bzero = 0x8000;
	}
	logmsg("Using %i-bit output\n", bits);

	hdr = fits_get_header_for_image3(W, H, outformat, depth, NULL);
	if (bzero)
		fits_header_add_int(hdr, "BZERO", bzero, "Number that has been subtracted from pixel values");
	if (qfits_header_dump(hdr, fout)) {
		ERROR("Failed to write FITS header to file %s", outfn);
		exit(-1);
	}
	qfits_header_destroy(hdr);

	datastart = ftello(fid);
	// Figure out if we can seek backward in this input file...
	if ((fid == stdin) ||
		(fseeko(fid, 0, SEEK_SET) ||
		 fseeko(fid, datastart, SEEK_SET)))
		// Nope!
		onepass = TRUE;
	if (onepass && depth > 1) {
		logmsg("Reading in one pass\n");
		pixcache = bl_new(16384, bits/8);
	}

	for (plane=0; plane<depth; plane++) {
		if (plane > 0) {
			if (fseeko(fid, datastart, SEEK_SET)) {
				SYSERROR("Failed to seek back to start of image data");
				exit(-1);
			}
		}
		for (row = 0; row<H; row++) {
			unsigned int column;

#if HAVE_NETPBM
			pnm_readpamrow(&img, tuplerow);
#else
			read_pnm_row(fid, W, depth, maxval, rowbuf);
#endif

			for (column = 0; column<W; column++) {
				int rtn;
				int pixval;

#if HAVE_NETPBM
				pixval = tuplerow[column][plane];
#else
				pixval = (bits == 8 ?
						  ((uint8_t *)rowbuf)[column*depth + plane] :
						  ((uint16_t*)rowbuf)[column*depth + plane]);
#endif
				if (outformat == BPP_8_UNSIGNED)
					rtn = fits_write_data_B(fout, pixval);
				else
					rtn = fits_write_data_I(fout, pixval-bzero, TRUE);
				if (rtn) {
					ERROR("Failed to write FITS pixel");
					exit(-1);
				}
			}
			if (onepass && depth > 1) {
				for (column = 0; column<W; column++) {
					for (plane=1; plane<depth; plane++) {
						int pixval;
#if HAVE_NETPBM
						pixval = tuplerow[column][plane];
#else
						pixval = (bits == 8 ?
								  ((uint8_t *)rowbuf)[column*depth + plane] :
								  ((uint16_t*)rowbuf)[column*depth + plane]);
#endif
						if (outformat == BPP_8_UNSIGNED) {
							uint8_t pix = pixval;
							bl_append(pixcache, &pix);
						} else {
							int16_t pix = pixval - bzero;
							bl_append(pixcache, &pix);
						}
					}
				}
			}
		}
	}
	
#if HAVE_NETPBM
	pnm_freepamrow(tuplerow);
#else
	free(rowbuf);
#endif

	if (pixcache) {
		int i, j;
		int step = (depth - 1);
		logverb("Writing %zu queued pixels\n", bl_size(pixcache));
		for (plane=1; plane<depth; plane++) {
			j = (plane - 1);
			for (i=0; i<(W * H); i++) {
				int rtn;
				if (outformat == BPP_8_UNSIGNED) {
					uint8_t* pix = bl_access(pixcache, j);
					rtn = fits_write_data_B(fout, *pix);
				} else {
					int16_t* pix = bl_access(pixcache, j);
					rtn = fits_write_data_I(fout, *pix, TRUE);
				}
				if (rtn) {
					ERROR("Failed to write FITS pixel");
					exit(-1);
				}
				j += step;
			}
		}
		bl_free(pixcache);
	}

	if (fid != stdin)
		fclose(fid);

	if (fits_pad_file(fout)) {
		ERROR("Failed to pad output file \"%s\"", outfn);
		return -1;
	}

	if (fout != stdout)
		if (fclose(fout)) {
			SYSERROR("Failed to close output file %s", outfn);
			exit(-1);
		}

	return 0;
}
Example #18
0
int main(int argc, char *argv[]) {
    int argchar;

	char* infn = NULL;
	char* outfn = NULL;
	FILE* fin = NULL;
	FILE* fout = NULL;
	pl* cols;
	char* progname = argv[0];
	int nextens;
	int ext;
	int NC;
	int start, size;
    anqfits_t* anq = NULL;

	qfits_table* outtable;
	unsigned char* buffer;

	cols = pl_new(16);

    while ((argchar = getopt (argc, argv, OPTIONS)) != -1)
        switch (argchar) {
        case 'c':
			pl_append(cols, optarg);
            break;
        case 'i':
			infn = optarg;
			break;
        case 'o':
			outfn = optarg;
			break;
        case '?':
        case 'h':
			printHelp(progname);
            return 0;
        default:
            return -1;
        }

	if (!infn || !outfn || !pl_size(cols)) {
		printHelp(progname);
		exit(-1);
	}

    fin = fopen(infn, "rb");
    if (!fin) {
        ERROR("Failed to open input file %s: %s\n", infn, strerror(errno));
        exit(-1);
    }

    fout = fopen(outfn, "wb");
    if (!fout) {
        ERROR("Failed to open output file %s: %s\n", outfn, strerror(errno));
        exit(-1);
    }

	// copy the main header exactly.
    anq = anqfits_open(infn);
    if (!anq) {
        ERROR("Failed to read \"%s\"", infn);
        exit(-1);
    }
    start = anqfits_header_start(anq, 0);
    size  = anqfits_header_size (anq, 0);
    if (pipe_file_offset(fin, start, size, fout)) {
        ERROR("Failed to copy primary header.\n");
        exit(-1);
    }

	NC = pl_size(cols);
	nextens = anqfits_n_ext(anq);
	printf("Translating %i extensions.\n", nextens);
	buffer = NULL;
	for (ext=1; ext<nextens; ext++) {
		int c2, c;
		int columns[NC];
		int sizes[NC];
		int offsets[NC];
		int offset = 0;
		int off, n;
		int totalsize = 0;
		const int BLOCK=1000;
		qfits_table* table;
		qfits_header* header;
		qfits_header* tablehdr;

		if (ext%100 == 0) {
			printf("Extension %i.\n", ext);
			fflush(stdout);
		}

		if (!anqfits_is_table(anq, ext)) {
			ERROR("extention %i isn't a table.\n", ext);
			// HACK - just copy it.
			return -1;
		}
		table = anqfits_get_table(anq, ext);
		if (!table) {
			ERROR("failed to open table: file %s, extension %i.\n", infn, ext);
			return -1;
		}
        header = anqfits_get_header(anq, ext);
		if (!header) {
			ERROR("failed to read header: extension %i\n", ext);
			exit(-1);
		}

		outtable = qfits_table_new(outfn, QFITS_BINTABLE, 0, NC, table->nr);
		outtable->tab_w = 0;
		
		for (c=0; c<pl_size(cols); c++) {
			columns[c] = -1;
		}
		for (c=0; c<pl_size(cols); c++) {
			char* colname = pl_get(cols, c);
			qfits_col* col;
			c2 = fits_find_column(table, colname);
			if (c2 == -1) {
				ERROR("Extension %i: failed to find column named %s\n",
						ext, colname);
				exit(-1);
			}
			col = table->col + c2;
			columns[c] = c2;
			sizes[c] = col->atom_nb * col->atom_size;
			offsets[c] = offset;
			offset += sizes[c];

			qfits_col_fill(outtable->col + c,
						   col->atom_nb, col->atom_dec_nb,
						   col->atom_size, col->atom_type,
						   col->tlabel, col->tunit,
						   col->nullval, col->tdisp,
						   col->zero_present,
						   col->zero,
						   col->scale_present,
						   col->scale,
						   outtable->tab_w);
			outtable->tab_w += sizes[c];
		}
		totalsize = offset;

		tablehdr = qfits_table_ext_header_default(outtable);
		// add any headers from the original table that aren't part of the BINTABLE extension.
        fits_copy_non_table_headers(tablehdr, header);
		qfits_header_dump(tablehdr, fout);
		qfits_header_destroy(tablehdr);
		
		buffer = realloc(buffer, totalsize * BLOCK);

		for (off=0; off<table->nr; off+=n) {
			if (off + BLOCK > table->nr)
				n = table->nr - off;
			else
				n = BLOCK;
			for (c=0; c<pl_size(cols); c++)
				qfits_query_column_seq_to_array_no_endian_swap
					(table, columns[c], off, n, buffer + offsets[c], totalsize);
			if (fwrite(buffer, totalsize, n, fout) != n) {
				ERROR("Error writing a block of data: ext %i: %s\n", ext, strerror(errno));
				exit(-1);
			}
		}

		qfits_table_close(outtable);
		fits_pad_file(fout);
		qfits_header_destroy(header);
		qfits_table_close(table);
	}
	free(buffer);

	if (fclose(fout)) {
		ERROR("Error closing output file: %s\n", strerror(errno));
	}
	fclose(fin);

    anqfits_close(anq);

	pl_free(cols);
	return 0;
}
Example #19
0
int main(int argc, char** args) {
    int argchar;
    char* progname = args[0];
    char** inputfiles = NULL;
    int ninputfiles = 0;
    int i;
    char* outfile = NULL;
    int N;
    anbool* solved;
    int noerr = 0;

    while ((argchar = getopt (argc, args, OPTIONS)) != -1) {
        switch (argchar) {
        case 'o':
            outfile = optarg;
            break;
        case 'e':
            noerr = 1;
            break;
        case 'h':
        default:
            printHelp(progname);
            exit(-1);
        }
    }
    if (optind < argc) {
        ninputfiles = argc - optind;
        inputfiles = args + optind;
    } else {
        printHelp(progname);
        exit(-1);
    }

    N = 0;
    for (i=0; i<ninputfiles; i++) {
        int n = solvedfile_getsize(inputfiles[i]);
        if (n == -1) {
            if (!noerr) {
                fprintf(stderr, "Failed to get size of input file %s.\n", inputfiles[i]);
                exit(-1);
            }
        }
        if (n > N) N = n;
    }

    solved = calloc(N, sizeof(anbool));
    for (i=0; i<ninputfiles; i++) {
        il* slist;
        int j;
        slist = solvedfile_getall_solved(inputfiles[i], 1, N, 0);
        for (j=0; j<il_size(slist); j++)
            solved[il_get(slist, j) - 1] = TRUE;
        il_free(slist);
    }
    if (solvedfile_set_file(outfile, solved, N)) {
        fprintf(stderr, "Failed to set values in output file.\n");
        exit(-1);
    }

    free(solved);
    return 0;
}
Example #20
0
int main(int argc, char **argv)
{
    int i, next_int;
    int num_threads;
    int *int_arr;
    FILE* f;
    char *fname;
    int arr_space = 1024 * 100; //100kb by default

    int option_balanced = 0;
    int keyword_start_index = 1;

    //Check args for -h flag, print help and exit if found.
    for(i = 1; i < argc; i++) {
        if( strcmp(argv[i], "-h") == 0) {
            printf("\n");
            printHelp();
            exit(0);
        }
        if( strcmp(argv[i], "-b") == 0) {
            option_balanced = 1;
            keyword_start_index = i+1;
        }
    }

    //Debug args
    /*printf("keyword index = %d\n", keyword_start_index);
    printf("argc - keyword index = %d\n", argc - keyword_start_index);
    for(i = 0; i < argc; i++){
        printf("argv[%d] = %s\n", i, argv[i]);
    }*/

    if((argc - keyword_start_index) != 3) {
        printArgError();
        printUsage();
        exit(1);
    }

    //Set search values
    fname = argv[keyword_start_index];
    search_val = atoi(argv[keyword_start_index+1]);
    num_threads = atoi(argv[keyword_start_index+2]);

    if(num_threads < 0 || num_threads > DFS_THREAD_MAX) {
        printArgError();
        printf(PROGNAME ": error: number of threads must nonnegative"
               " and less than or equal to %d\n", DFS_THREAD_MAX);
        printUsage();
        exit(1);
    }



    //------------- Read in data file ----------------

    //Open file.
    if((f = fopen(fname, "r")) == NULL) {
        perror(PROGNAME ": error: problem opening file");
        exit(1);
    }

    //Allocate initial array for the values.
    int_arr = (int*)malloc(sizeof(int) * arr_space);
    if(int_arr == NULL) {
        perror(PROGNAME ": error: error allocating memory");
        exit(1);
    }

    //Scan to get values, growing array if needed.
    fseek(f, 0, SEEK_SET);
    for(i = 0; (fscanf(f,"%d", &next_int) != EOF); i++) {
        if(i == arr_space) {
            arr_space *= 2;
            int_arr = (int*)realloc(int_arr, sizeof(int) * arr_space);
            if(int_arr == NULL) {
                perror(PROGNAME ": error: error reallocating memory for array");
                exit(1);
            }
        }
        int_arr[i] = next_int;
    }
    fclose(f);

    if(i == 0) {
        fprintf(stderr, PROGNAME ": error: no values to process!\n");
        exit(1);
    }

    DFS_TREE_SIZE = i;


    //------------- Build Tree -------------------

    tree *t;
    if(option_balanced) {
        prog_debug(1, PROGNAME ": building balanced tree from input values\n");
        t = makeBalancedTreeFromArray(int_arr[0], int_arr, DFS_TREE_SIZE);
    } else {
        prog_debug(1, PROGNAME ": building random tree from input values\n");
        t = makeRandomTreeFromArray(int_arr[0], int_arr, DFS_TREE_SIZE);
    }


    //tree_print(t, stdout);
    //Print tree using function pointer scheme. Left as an example of
    //how to use tree_visit.
    if(DFS_DEBUG_TREE > 0) {
        treenode_func func = printNode;
        tree_visit(t, func, (void *)stdout);
    }



    //--------------- Search The Tree -----------------

    //Single DFS search using a pointer to the findVal function. For fun.
    //func = findVal;
    //tree_visit(t, func, (void *)&search_val);

    //Call the threaded search algorithm.
    if(num_threads == 0) {
        for(num_threads = 1; num_threads <= DFS_THREAD_MAX; num_threads *= 2) {
            prog_debug(1, PROGNAME ": starting search_tree_for_val...\n");
            search_tree_for_val(t, num_threads, search_val);
        }
    } else {
        prog_debug(1, PROGNAME ": starting search_tree_for_val...\n");
        search_tree_for_val(t, num_threads, search_val);
    }


    return 0;
}
Example #21
0
//-----------------------------------------------------------------------
int main(int argc, char **argv){
int i;
FILE *file=NULL, *ofile=NULL;
//char line[MAXLINE];
char counters[MAXCOUNTERS][MAXWORD];
if(argc==1) {
  char date[32]="21.05.2011";
  char oline[1000];
  //w32 clusters[NCLUST][NBO];
  printHelp(); return 8;
  file= open_rawcnts(date);
  if(file==NULL) {printf("Error: %s.rawcnts not found\n",date); return 2;};
  while(1) {
    int rc;
    rc= parseline(file,counters); if(rc==1) break; // EOF
    if(rc==2) { printf("Error: short array\n"); continue; };
    //printf("%s %s\n",counters[0],counters[1]);
    //oline[0]='\0';
    sprintf(oline, "%s %s ", counters[0], counters[1]);
    for(i= CSTARTRUNX+2;i< CSTARTRUNX+2+6;i++){   // 898..893
      //w32 number; 
      char cnumber[MAXWORD];
      //converth2i(&number,i,counters);
      //printf("n:%i \n",number);
      //sprintf(oline, "%s%i ",oline, number);
      strcpy(cnumber, counters[i]);
      sprintf(oline, "%s%s ",oline, cnumber);
      //printf("%i %s %i\n",i,counters[i],number);
    };
    oline[strlen(oline)-1]='\0'; printf("%s\n", oline); 
  };
  //getBUSYclust(clusters,counters);
} else {
#define MAXNOC 100
  int noc;   // number of counters
  int runxpos;   //  pisition in RUNX array
  w32 runi;   // atoi(runc)
  int decdata=0;   // 0: hexa   1: decimal
  int cpos[MAXNOC];
  char date[20], dati1[20],dati2[20];   // "21.05.2011 23:40:01"
  char runc[20]; char outfilepath[80];
  char oline[MAXNOC*15];
  int olines=0; int binarydata=0;
  char fmtsep[20]="%s %s ";
  if(argc < (6+1)) {printHelp(); return 8; };
  /* dati1 dati2 option run datafile.out n1 n2 ...
     1     2            3   4            5     old (before 31.5.2013)
     1     2     3      4   5            6
  */
  strcpy(dati1, argv[1]); strcpy(dati2, argv[2]);
  if(strncmp(&dati1[6],"2014",4) < 0 ) {
  } else if(strncmp(&dati1[6],"2014",4) > 0 ) {
    CSTARTRUNX= 1486;   // 896;  changed:24.5.2017
  } else {
    CSTARTRUNX= 896;    //1486;  changed:24.5.2017
    printf("Bad year, no data in 2014\n"); return 3;
  };
  strcpy(runc, argv[4]); runi=atoi(runc); strcpy(outfilepath, argv[5]);
  printf("%s %s %d %s. Counters' rel. addresses:\n", dati1, dati2, runi, outfilepath);
  runxpos=-1;
  if((argc>= 7) && (strcmp("dimall",argv[6])==0)) {
    binarydata=1;
    printf("dimall ");
  } else {
    if(strcmp(argv[3],"dec")==0) {
      decdata=1;
      printf("decimal ");
    } else if(strcmp(argv[3],"gnu")==0) {
      decdata=1;
      strcpy(fmtsep, "%s-%s ");
      printf("gnu decimal ");
    } else {
      decdata=0;
      strcpy(fmtsep, "%s %s ");
      printf("hexa ");
    }
    for(noc=0; noc<=MAXNOC; noc++) {
      if(noc>=MAXNOC) {
        printf("Error: too many counters. max:%d\n",MAXNOC); return 3;
      };
      if( noc>= (argc-6)) break;
      cpos[noc]= atoi(argv[noc+6]);
      printf("%d ", cpos[noc]);
    }; 
  };
  printf("\n");
  strcpy(date,dati1);   //1st file
  file= open_rawcnts(date);
  if(file==NULL) {printf("Error: %s.rawcnts not found\n",dati1); return 2;};
  while(1){
    int rc; 
    rc= parseline(file,counters); 
    //printf("dbg1: %s %s\n", counters[0], counters[1]);
    if(rc==2) continue;
    if(rc==1) {
      while (1) {
        if(strncmp(date,dati2,10)==0) goto ALLDONE;
        date_plus1(date);
        file= open_rawcnts(date);
        if(file!=NULL) break;
        printf("Warning: %s.rawcnts not found, trying next one...\n",date);
      };
      continue;   //parse 1st line
    };
    if(strncmp(&dati1[0], &date[0], 10)==0) {  // check lower time only in 1st file 
      if(strncmp(counters[1], &dati1[11], 8)<0) { continue; };
    };
    //printf("dbg2: %s %s\n", counters[0], counters[1]);
    if(strcmp(runc,"0")!=0) { // check run number if != 0
      if(runxpos == -1) {
        int irx;
        for(irx= CSTARTRUNX+2;irx< CSTARTRUNX+2+6;irx++){
          //printf("runx[%d]: %d ",irx, h2w32(counters[irx]));
          if(h2w32(counters[irx])==runi) {
            // run just started:
            runxpos= irx;
            break;
          };
        }; //printf("\n");
        if(runxpos==-1) continue;  // runc not found yet
      } else {
        if(h2w32(counters[runxpos])!=runi) {
          // run finished, stop reading:
          break;
        };
      }
    };
    if(strncmp(&dati2[0], &date[0], 10)==0) {  // check upper time only in last file 
      if(strncmp(counters[1], &dati2[11], 8)>0) { break; };
    };
    if(ofile==NULL) {
      ofile= fopen(outfilepath,"w");
      if(ofile==NULL) {
        printf("cant open %s\n", outfilepath);
        return(3);
      };
      if(binarydata!=1) {
        int ix;
        strcpy(oline, "# date     time    ");
        for(ix=0; ix<noc; ix++) {
          sprintf(oline,"%s %s", oline, argv[ix+6]);
        };
        fprintf(ofile, "%s\n", oline); 
      };
    };
    if(binarydata==1) {
      //printf("Bindata: ");
      for(i=2; i<NCOUNTERS+2; i++) {
        w32 cnt;
        converth2i(&cnt, i, counters);
        //if(i<7) printf("%d:%x ", i-2, cnt);
        fwrite(&cnt, 4, 1, ofile);
      };  //printf("\n");
    } else {
      //oline[0]='\0'; sprintf(oline, "%s %s ", counters[0], counters[1]);
      oline[0]='\0'; sprintf(oline, fmtsep, counters[0], counters[1]);
      for(i=0; i<noc; i++) {
        //w32 number; 
        int ix; char cnumber[MAXWORD];
        ix= cpos[i]+2 ;
        //converth2i(&number,i,counters);
        //printf("n:%i \n",number);
        //sprintf(oline, "%s%i ",oline, number);
        if(decdata!=0) {
          w32 cnumberdec;
          converth2i(&cnumberdec,ix,counters);
          sprintf(oline, "%s%u " ,oline, cnumberdec);
        } else {
          strcpy(cnumber, counters[ix]);
          sprintf(oline, "%s%s ",oline, cnumber);
        };
      }; 
      oline[strlen(oline)-1]='\0'; 
    };
    if(binarydata!=1) {
      fprintf(ofile, "%s\n", oline); 
    };
    olines++;
  };
  ALLDONE:
  printf("%s: %d lines(or blocks in case of dimall) written\n", 
    outfilepath, olines);
};
if(file!=NULL) fclose(file);
if(ofile!=NULL) fclose(ofile);
}
Example #22
0
int main(int argc, char* argv[]){
	if(argc == 3){
		opterr = 0;
		int indexptr;
		int opt;
		while((opt = getopt_long(argc, argv, "b:",longopts, &indexptr)) != -1){
			switch(opt){
				case 'b':
					bankId = optarg;
					break;
				default:
					printHelp(argv[0]);
					break;
			}
		}
		char cardNumber[16+1];
		char messageType[7+1];
		char value[13+1]; // only 13 digit needed for the richest man of the world
		char* string;
		int end = 0;
		char bankPath[20] = {0};
		char fifoPath[64] = {0};
		sprintf(bankPath,"resources/bank%.4s",bankId);
		mkdir(bankPath,0755);

		sprintf(fifoPath,"%s/localAuth.fifo",bankPath);
		mkfifo(fifoPath,DEFAULT);
		int localAuth = open(fifoPath,O_WRONLY);

		sprintf(fifoPath,"%s/input.fifo",bankPath);
		mkfifo(fifoPath,DEFAULT);
		int bank = open(fifoPath,O_RDONLY);

		sprintf(fifoPath,"%s/interRemoteDemande.fifo",bankPath);
		mkfifo(fifoPath,DEFAULT);
		int localInter = open(fifoPath,O_WRONLY);
		pthread_t remoteThread;
		pthread_create(&remoteThread,NULL,remoteResponse,NULL);
		pthread_create(&remoteThread, NULL, (void* (*) (void*))routeRemoteRequest, (void*)&bankPath);
		while(!end){
			string = litLigne(bank);
			errno = 0;
			if(string == NULL || decoupe(string,cardNumber,messageType,value) == 0){
				perror("(acquisition)message in wrong format");
				fprintf(stderr,"%s:%d: [bank %s] %s",__FILE__,__LINE__,bankId,string);
				end = 1;
				continue;
			}
			
			if(strncmp(cardNumber,bankId,4) == 0){
				ecritLigne(localAuth,string);
			}else{ // to interbancaire
				ecritLigne(localInter,string);
			}
			free(string);
		}
		
		if(pthread_join(remoteThread,NULL)){
			perror("local auth");
		}
	}else{
		printHelp(argv[0]);
	}
 return 0;
}
Example #23
0
int pdf2john(int argc, char **argv)
{
	int ret = 0;
	int c, i;
	FILE *file = NULL;
	uint8_t *userpassword = NULL;
	char *inputfile = NULL;
	unsigned char *p;
	struct custom_salt cs;
	cs.e.work_with_user = true;
	cs.e.have_userpassword = false;

	/* parse arguments */
	while (true) {
		c = getopt(argc, argv, "op:v");
		/* Detect the end of the options. */
		if (c == -1)
			break;

		switch (c) {
		case 'o':
			cs.e.work_with_user = false;
			break;
		case 'p':
			userpassword = (uint8_t *) strdup(optarg);
			cs.e.work_with_user = false;
			cs.e.have_userpassword = true;
			break;
		case 'v':
			printf("pdfcrack version %d.%d\n", VERSION_MAJOR,
			    VERSION_MINOR);
			return 0;
		default:
			printHelp(argv[0]);
			ret = 1;
		}
	}
	i = optind;
	if (i > 0) {
		if (i < argc)
			inputfile = strdup(argv[i++]);
	}

	if (!inputfile) {
		printHelp(argv[0]);
		ret = 1;
		goto cleanup;
	}

	if ((file = fopen(inputfile, "r")) == 0) {
		fprintf(stderr, "Error: file %s not found\n", inputfile);
		ret = 2;
		goto cleanup;
	}

	if (!openPDF(file, &cs.e)) {
		fprintf(stderr, "Error: Not a valid PDF\n");
		ret = 3;
		goto cleanup;
	}

	ret = getEncryptedInfo(file, &cs.e);
	if (ret) {
		if (ret == EENCNF)
			fprintf(stderr,
			    "Error: Could not extract encryption information\n");
		else if (ret == ETRANF || ret == ETRENF || ret == ETRINF)
			fprintf(stderr,
			    "Error: Encryption not detected (is the document password protected?)\n");
		ret = 4;
		goto cleanup;
	} else if (cs.e.revision < 2 || (strcmp(cs.e.s_handler, "Standard") != 0)) {
		fprintf(stderr,
		    "The specific version is not supported (%s - %d)\n",
		    cs.e.s_handler, cs.e.revision);
		ret = 5;
		goto cleanup;
	}

	if (fclose(file)) {
		fprintf(stderr, "Error: closing file %s\n", inputfile);
	}
#ifdef UNPDF_DEBUG
	printEncData(&cs.e);
#endif
	/* try to initialize the cracking-engine */

	if (!initPDFCrack(&cs)) {
		fprintf(stderr, "Wrong userpassword given, '%s'\n",
		    userpassword);
		exit(-1);
	}

	/* deep serialize "e" structure */
	printf("%s:$pdf$%s*", inputfile, cs.e.s_handler);
	p = cs.e.o_string;
	for (i = 0; i < 32; i++)
		printf("%c%c", itoa16[ARCH_INDEX(p[i] >> 4)],
		    itoa16[ARCH_INDEX(p[i] & 0x0f)]);
	printf("*");
	p = cs.e.u_string;
	for (i = 0; i < 32; i++)
		printf("%c%c",
		    itoa16[ARCH_INDEX(p[i] >> 4)],
		    itoa16[ARCH_INDEX(p[i] & 0x0f)]);
	printf("*%d*", cs.e.fileIDLen);
	p = cs.e.fileID;
	for (i = 0; i < cs.e.fileIDLen; i++)
		printf("%c%c",
		    itoa16[ARCH_INDEX(p[i] >> 4)],
		    itoa16[ARCH_INDEX(p[i] & 0x0f)]);
	printf("*%d*%d*%d*%u*%u*%d*%d*%d*%d", cs.e.encryptMetaData,
	    cs.e.work_with_user, cs.e.have_userpassword, cs.e.version_major,
	    cs.e.version_minor, cs.e.length, cs.e.permissions, cs.e.revision,
	    cs.e.version);
	if (cs.e.have_userpassword)
		printf("*%s\n", userpassword);
	else
		printf("\n");
	exit(0);

      cleanup:

	return ret;
}
int main(int argc, char* argv[]) {
	char *add  = "add";
	char *buyC = "buy";
	char *endT = "end";
	char *exit = "exit";
	char *help = "help";
	char *init = "init";
	char *numH = "num";
	char *play = "play";
	char *resign  = "resi";
	char *show = "show";
	char *stat = "stat";
	char *supply = "supp";
	char *whos = "whos";
		
	char command[MAX_STRING_LENGTH];
	char line[MAX_STRING_LENGTH];
	char cardName[MAX_STRING_LENGTH];

	//Array to hold bot presence 
	int isBot[MAX_PLAYERS] = { 0, 0, 0, 0};

	int players[MAX_PLAYERS];
	int playerNum;
	int outcome;
	int currentPlayer;
	int gameOver = FALSE;
	int gameStarted = FALSE;
	int turnNum = 0;

	int randomSeed = atoi(argv[1]);

	//Default cards, as defined in playDom
	int kCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};

	struct gameState g;
	struct gameState * game = &g;
	
	memset(game,0,sizeof(struct gameState));
		
	if(argc != 2){
		printf("Usage: player [integer random number seed]\n");
		return EXIT_SUCCESS;
	}
	
	if(randomSeed <= 0){
		printf("Usage: player [integer random number seed]\n");
		return EXIT_SUCCESS;
	}	
	
	initializeGame(2,kCards,randomSeed,game);
	printf("Please enter a command or \"help\" for commands\n");
	
	
	while(TRUE) {
		int arg0 = UNUSED;
		int arg1 = UNUSED;
		int arg2 = UNUSED;
		int arg3 = UNUSED;

		outcome = FAILURE;
		strcpy(line,"");
		strcpy(command,"");
		strcpy(cardName,"");
		
		currentPlayer = whoseTurn(game);
		
		//If you are getting a seg fault comment this if block out
		gameOver = isGameOver(game); 		
		if(gameStarted == TRUE && gameOver == TRUE){
			printScores(game);
			getWinners(players, game);
			printf("After %d turns, the winner(s) are:\n", turnNum);
			for(playerNum = 0; playerNum < game->numPlayers; playerNum++){
				if(players[playerNum] == WINNER) printf("Player %d\n", playerNum);
			}
		for(playerNum = 0; playerNum < game->numPlayers; playerNum++){
				printHand(playerNum, game);
				printPlayed(playerNum, game);
				printDiscard(playerNum, game);
				printDeck(playerNum, game);
			}
			break; //Exit out of the game/while loop
		}         
		
		if(isBot[currentPlayer] == TRUE) {
				executeBotTurn(currentPlayer, &turnNum, game);
				continue;
		}
		
		printf("$ ");
		fgets(line, MAX_STRING_LENGTH, stdin);
		sscanf(line, "%s %d %d %d %d", command, &arg0, &arg1, &arg2, &arg3);
		
		if(COMPARE(command, add) == 0) {
			outcome = addCardToHand(currentPlayer, arg0, game);
			cardNumToName(arg0, cardName);
			printf("Player %d adds %s to their hand\n\n", currentPlayer, cardName);
		} else
		if(COMPARE(command, buyC) == 0) {
			outcome = buyCard(arg0, game);
			cardNumToName(arg0, cardName);
			if(outcome == SUCCESS){
				printf("Player %d buys card %d, %s\n\n", currentPlayer, arg0, cardName);
			} else {
				printf("Player %d cannot buy card %d, %s\n\n", currentPlayer, arg0, cardName);
			}
		} else
		if(COMPARE(command, endT) == 0) {
			if(gameStarted == TRUE) {
				if(currentPlayer == (game->numPlayers -1)) turnNum++;
				endTurn(game);
				currentPlayer = whoseTurn(game);
				printf("Player %d's turn number %d\n\n", currentPlayer, turnNum);
			}

		} else			
		if(COMPARE(command, exit) == 0) {
			break;
		} else
		if(COMPARE(command, help) == 0) {
			printHelp();
		} else
		if(COMPARE(command, init) == 0) {
			int numHuman = arg0 - arg1;
			for(playerNum = numHuman; playerNum < arg0; playerNum++) {
				isBot[playerNum] = TRUE;
			}
			//selectKingdomCards(randomSeed, kCards);  //Comment this out to use the default card set defined in playDom.
			outcome = initializeGame(arg0, kCards, randomSeed, game);
			printf("\n");
			if(outcome == SUCCESS){
				gameStarted = TRUE;
				currentPlayer = whoseTurn(game);
				printf("Player %d's turn number %d\n\n", currentPlayer, turnNum);
			}

		} else
		if(COMPARE(command, numH) == 0) {
			int numCards = numHandCards(game);
			printf("There are %d cards in your hand.\n", numCards);
		} else
		if(COMPARE(command, play) == 0) {
			int card = handCard(arg0,game);
			outcome = playCard(arg0, arg1, arg2, arg3, game);
			cardNumToName(card, cardName);
			if(outcome == SUCCESS){
				printf("Player %d plays %s\n\n", currentPlayer, cardName);
			} else {
				printf("Player %d cannot play card %d\n\n", currentPlayer, arg0);
			}

		} else
		if(COMPARE(command, resign) == 0) {
			endTurn(game);
			printScores(game);
			break;
		} else
		if(COMPARE(command, show) == 0) {
			if(gameStarted == FALSE) continue;
			printHand(currentPlayer, game);
			printPlayed(currentPlayer, game);
			//printDiscard(currentPlayer, game);
			//printDeck(currentPlayer, game);
		} else
		if(COMPARE(command, stat) == 0) {
			if(gameStarted == FALSE) continue;
			printState(game);
		} else
		if(COMPARE(command, supply) == 0) {
			printSupply(game);
		} else
		if(COMPARE(command, whos) == 0) {
			int playerNum =	whoseTurn(game);
			printf("Player %d's turn\n", playerNum);
		} 
	}
	return EXIT_SUCCESS;
}
Example #25
0
int main(int argc, char *argv[])
{
    std::string inputFileName;
    std::string inputFormatName;
    std::string outputFileName;
    std::string outputFormatName;

    boost::program_options::options_description options;
    options.add_options()
        ("input-file",
            boost::program_options::value<std::string>(&inputFileName),
            "The input file.")
        ("output-file",
            boost::program_options::value<std::string>(&outputFileName),
            "The output file.")
        ("input-format,i",
            boost::program_options::value<std::string>(&inputFormatName),
            "Sets the input format.")
        ("output-format,o",
            boost::program_options::value<std::string>(&outputFormatName),
            "Sets the output format.")
        ("help,h",
            "Shows this help message");

    boost::program_options::positional_options_description positionalOptions;
    positionalOptions.add("input-file", 1).add("output-file", 1);

    boost::program_options::variables_map variables;
    boost::program_options::store(
        boost::program_options::command_line_parser(argc, argv)
            .options(options)
            .positional(positionalOptions).run(),
        variables);
    boost::program_options::notify(variables);

    if(variables.count("help")){
        printHelp(argv, options);
        return 0;
    }
    else if(inputFileName.empty()){
        printHelp(argv, options);
        std::cerr << "Error: No input file specified." << std::endl;
        return -1;
    }
    else if(outputFileName.empty()){
        printHelp(argv, options);
        std::cerr << "Error: No output file specified." << std::endl;
        return -1;
    }

    // read input
    chemkit::MoleculeFile inputFile;
    if(!inputFormatName.empty()){
        inputFile.setFormat(inputFormatName);
    }

    bool ok = false;
    if(inputFileName == "-"){
        ok = inputFile.read(std::cin);
    }
    else{
        if(inputFormatName.empty()){
            ok = inputFile.read(inputFileName);
        }
        else{
            ok = inputFile.read(inputFileName, inputFormatName);
        }
    }

    if(!ok){
        std::cerr << "Error: Failed to read input file: " << inputFile.errorString() << std::endl;
        return -1;
    }

    // write output
    if(outputFormatName.empty()){
        ok = inputFile.write(outputFileName);
    }
    else{
        if(outputFileName == "-"){
            ok = inputFile.write(std::cout, outputFormatName);
        }
        else{
            ok = inputFile.write(outputFileName, outputFormatName);
        }
    }

    if(!ok){
        std::cerr << "Error: failed to write output file: " << inputFile.errorString() << std::endl;
        return -1;
    }

    return 0;
}
Example #26
0
void parseCmdlineOpts (int argc, char **argv, struct args_info *args_info)
{

  char *string_ptr = NULL;
  char *args_ptr = NULL;

  /* Clear out the argument structure */
  memset (args_info, 0, sizeof (struct args_info));

  while (argc > 1) {

    /* If we don't have a proper argument leading with '-' */
    if (argv[1][0] != '-') {

      printHelp ();
      exit (1);

    }

    /* Deal with arguments of type '--', else deal with switches of
     * type '-'.
     */
    if (argv[1][1] == '-') {

      string_ptr = &(argv[1][2]);

      /* Find the '=' if it exists, otherwise argv_ptr is '\0' */
      for (args_ptr = string_ptr; *args_ptr != '\0'; args_ptr++) {

        if (*args_ptr == '=') {

          *args_ptr = '\0';
          args_ptr++;
          break;

        }

      }

      if (!strcmp (string_ptr, "help")) {

        args_info->help_given = 1;
        printHelp ();
        exit (0);

      }

      if (!strcmp (string_ptr, "version")) {

        args_info->version_given = 1;
        printVersion ();
        exit (0);

      }

      if (!strcmp (string_ptr, "port")) {

        if (args_info->port_given) {
          optError ("`--port' (`-p') option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --port=INT");
        }

        args_info->port_given = 1;
        GET_INT_FROM_STRING_ARG (args_ptr, args_info->port_arg,
                                 "Must specify argument: --port=INT")

      }

      if (!strcmp (string_ptr, "config")) {


        if (args_info->config_given) {
          optError ("`--config' (`-c') option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --config=STRING");
        }

        args_info->config_given = 1;
        args_info->config_arg = args_ptr;

      }

      if (!strcmp (string_ptr, "voices")) {

        if (args_info->voices_given) {
          optError ("`--voices' (`-v') option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --voices=INT");
        }

        args_info->voices_given = 1;
        GET_INT_FROM_STRING_ARG (args_ptr, args_info->voices_arg,
                                 "Must specify argument: --voices=INT")

      }

      if (!strcmp (string_ptr, "logfile")) {

        if (args_info->logfile_given) {
          optError ("`--logfile' (`-l') option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --logfile=STRING");
        }

        args_info->logfile_given = 1;
        args_info->logfile_arg = args_ptr;

      }

      if (!strcmp (string_ptr, "pidfile")) {

        if (args_info->pidfile_given) {
          optError ("`--pidfile' option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --pidfile=STRING");
        }

        args_info->pidfile_given = 1;
        args_info->pidfile_arg = args_ptr;

      }

      if (!strcmp (string_ptr, "record-file")) {

        if (args_info->record_file_given) {
          optError ("`--record-file' option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --record-file=STRING");
        }

        args_info->record_file_given = 1;
        args_info->record_file_arg = args_ptr;

      }

      if (!strcmp (string_ptr, "start-time")) {

        if (args_info->start_time_given) {
          optError ("`--start-time' option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --start_time=STRING");
        }

        args_info->start_time_given = 1;
        args_info->start_time_arg = args_ptr;

      }

      if (!strcmp (string_ptr, "end-time")) {

        if (args_info->end_time_given) {
          optError ("`--end-time' option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --end-time=STRING");
        }

        args_info->end_time_given = 1;
        args_info->end_time_arg = args_ptr;

      }

      if (!strcmp (string_ptr, "snd-device")) {

        if (args_info->snd_device_given) {
          optError ("`--snd-device' option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --snd-device=STRING");
        }

        args_info->snd_device_given = 1;
        args_info->snd_device_arg = args_ptr;

      }

      if (!strcmp (string_ptr, "snd-port")) {

        if (args_info->snd_port_given) {
          optError ("`--snd-port' option given more than once");
        }
        if (!*args_ptr) {
          optError ("Must specify argument: --snd-port=INT");
        }

        args_info->snd_port_given = 1;
        GET_INT_FROM_STRING_ARG (args_ptr, args_info->snd_port_arg,
                                 "Must specify argument: --snd-port=INT")

      }

      if (!strcmp (string_ptr, "playback-mode")) {

        if (args_info->playback_mode_given) {
          optError ("`--playback-mode' option given more than once");
        }

        args_info->playback_mode_given = 1;

      }

      if (!strcmp (string_ptr, "record-mode")) {

        if (args_info->record_mode_given) {
          optError ("`--record-mode' option given more than once");
        }

        args_info->record_mode_given = 1;

      }

      if (!strcmp (string_ptr, "nodaemon")) {

        if (args_info->nodaemon_given) {
          optError ("`--nodaemon' option given more than once");
        }

        args_info->nodaemon_given = 1;

      }

    } else {

      switch (argv[1][1]) {
Example #27
0
static inline int parseCmdLine(int argc, char *argv[],cmdLineParameters *parameters) {
    int error = EXIT_SUCCESS;
    char errorMsg[100];
    int optc;

    while (((optc = getopt_long (argc, argv, "f:o:e:hv", longopts, NULL)) != -1) && (EXIT_SUCCESS == error)) {       
       int param;
       switch (optc)
       {
       case 'f':
         param = facilityLevel(optarg);
         if (param != -1) {
            parameters->facility = param;
         } else {
           sprintf(errorMsg,"invalid facility parameter (%s)",optarg);
           printHelp(errorMsg);
           error = EINVAL;
         }
         break;
       case 'o':
         param = logLevel(optarg);
         if (param != -1) {
            parameters->stdOutLogLevel = param;
         } else {
           sprintf(errorMsg,"invalid stdout log level parameter (%s)",optarg);
           printHelp(errorMsg);
           error = EINVAL;
         }
         break;
       case 'e':
         param = logLevel(optarg);
         if (param != -1) {
            parameters->stdErrLogLevel = param;
         } else {
           sprintf(errorMsg,"invalid stdout log level parameter (%s)",optarg);
           printHelp(errorMsg);
           error = EINVAL;
         }
         break;
       case 'h':
         printHelp(NULL);
         exit(EXIT_SUCCESS);
         break;
       case 'v':
         printVersion();
         exit(EXIT_SUCCESS);
         break;
       case '?':
    	 DEBUG_VAR(optind,"%d");
         /* getopt_long already printed an error message.  */
         sprintf(errorMsg,"invalid parameter (%s) %d",optarg,optind);
         error = EINVAL;
         printHelp("");
         break;
       default: 
         sprintf(errorMsg,"invalid parameter (%s)",optarg);
         printHelp(errorMsg);
         error = EINVAL;
         break;
       } /* switch (optc) */
    } /* while (((optc = getopt_long (argc, argv, "f:o:e:hv", longopts, NULL)) != -1) && (EXIT_SUCCESS == error)) */
    DEBUG_VAR(optind,"%d");

    /*if (EXIT_SUCCESS == error) {
       error = setExternalCmdLine(argc,argv,parameters);
       if (error != EXIT_SUCCESS) {
          sprintf(errorMsg,"invalid external program parameter (%s)",optarg);
          printHelp(errorMsg);
       }
    }*/
    return error;
}
Example #28
0
static void
processCommandLine (
  OptionProcessingInformation *info,
  int *argumentCount,
  char ***argumentVector,
  const char *argumentsSummary
) {
  int lastOptInd = -1;
  int index;

  const char resetPrefix = '+';
  const char *reset = NULL;
  int resetLetter;

#ifdef ALLOW_DOS_OPTION_SYNTAX
  const char dosPrefix = '/';
  int dosSyntax = 0;
#endif /* ALLOW_DOS_OPTION_SYNTAX */

  int optHelp = 0;
  int optHelpAll = 0;
  const OptionEntry *optionEntries[0X100];
  char shortOptions[1 + (info->optionCount * 2) + 1];

#ifdef HAVE_GETOPT_LONG
  struct option longOptions[(info->optionCount * 2) + 1];

  {
    struct option *opt = longOptions;
    for (index=0; index<info->optionCount; ++index) {
      const OptionEntry *entry = &info->optionTable[index];

      if (entry->word) {
        opt->name = entry->word;
        opt->has_arg = entry->argument? required_argument: no_argument;
        opt->flag = NULL;
        opt->val = entry->letter;
        opt += 1;

        if (!entry->argument && entry->setting.flag) {
          static const char *const noPrefix = "no-";
          size_t noLength = strlen(noPrefix);
          char *name;

          if (strncasecmp(noPrefix, entry->word, noLength) == 0) {
            name = strdup(&entry->word[noLength]);
          } else {
            size_t size = noLength + strlen(entry->word) + 1;

            if ((name = malloc(size))) {
              snprintf(name, size, "%s%s", noPrefix, entry->word);
            }
          }

          if (name) {
            opt->name = name;
            opt->has_arg = no_argument;
            opt->flag = &resetLetter;
            opt->val = entry->letter;
            opt += 1;
          } else {
            logMallocError();
          }
        }
      }
    }

    memset(opt, 0, sizeof(*opt));
  }
#endif /* HAVE_GETOPT_LONG */

  for (index=0; index<0X100; index+=1) optionEntries[index] = NULL;

  {
    char *opt = shortOptions;
    *opt++ = '+';

    for (index=0; index<info->optionCount; ++index) {
      const OptionEntry *entry = &info->optionTable[index];
      optionEntries[entry->letter] = entry;

      *opt++ = entry->letter;
      if (entry->argument) *opt++ = ':';

      if (entry->argument) {
        if (entry->setting.string) *entry->setting.string = NULL;
      } else {
        if (entry->setting.flag) *entry->setting.flag = 0;
      }
    }

    *opt = 0;
  }

  if (*argumentCount > 1)
#ifdef ALLOW_DOS_OPTION_SYNTAX
    if (*(*argumentVector)[1] == dosPrefix) dosSyntax = 1;
#endif /* ALLOW_DOS_OPTION_SYNTAX */

  opterr = 0;
  optind = 1;

  while (1) {
    int option;
    char prefix = '-';

    if (optind == *argumentCount) {
      option = -1;
    } else {
      char *argument = (*argumentVector)[optind];

#ifdef ALLOW_DOS_OPTION_SYNTAX
      if (dosSyntax) {
        prefix = dosPrefix;
        optind++;

        if (*argument != dosPrefix) {
          option = -1;
        } else {
          char *name = argument + 1;
          size_t nameLength = strcspn(name, ":");
          char *value = (nameLength == strlen(name))? NULL: (name + nameLength + 1);
          const OptionEntry *entry;

          if (nameLength == 1) {
            entry = optionEntries[option = *name];
          } else {
            int count = info->optionCount;
            entry = info->optionTable;
            option = -1;

            while (count--) {
              if (entry->word) {
                size_t wordLength = strlen(entry->word);

                if ((wordLength == nameLength) &&
                    (strncasecmp(entry->word, name, wordLength) == 0)) {
                  option = entry->letter;
                  break;
                }
              }

              entry++;
            }

            if (option < 0) {
              option = 0;
              entry = NULL;
            }
          }

          optopt = option;
          optarg = NULL;

          if (!entry) {
            option = '?';
          } else if (entry->argument) {
            if (!(optarg = value)) option = ':';
          } else if (value) {
            if (!entry->setting.flag) goto dosBadFlagValue;

            if (!wordMeansTrue(value)) {
              if (wordMeansFalse(value)) {
                resetLetter = option;
                option = 0;
              } else {
              dosBadFlagValue:
                option = '?';
              }
            }
          }
        }
      } else
#endif /* ALLOW_DOS_OPTION_SYNTAX */

      if (reset) {
        prefix = resetPrefix;

        if (!(option = *reset++)) {
          reset = NULL;
          optind++;
          continue;
        }

        {
          const OptionEntry *entry = optionEntries[option];
          if (entry && !entry->argument && entry->setting.flag) {
            resetLetter = option;
            option = 0;
          } else {
            optopt = option;
            option = '?';
          }
        }
      } else {
        if (optind != lastOptInd) {
          lastOptInd = optind;
          if ((reset = (*argument == resetPrefix)? argument+1: NULL)) continue;
        }

#ifdef HAVE_GETOPT_LONG
        option = getopt_long(*argumentCount, *argumentVector, shortOptions, longOptions, NULL);
#else /* HAVE_GETOPT_LONG */
        option = getopt(*argumentCount, *argumentVector, shortOptions);
#endif /* HAVE_GETOPT_LONG */
      }
    }
    if (option == -1) break;

    /* continue on error as much as possible, as often we are typing blind
     * and won't even see the error message unless the display comes up.
     */
    switch (option) {
      default: {
        const OptionEntry *entry = optionEntries[option];

        if (entry->argument) {
          if (!*optarg) {
            info->ensuredSettings[option] = 0;
            break;
          }

          if (entry->setting.string) {
            if (entry->flags & OPT_Extend) {
              extendSetting(entry->setting.string, optarg, 0);
            } else {
              *entry->setting.string = optarg;
            }
          }
        } else {
          if (entry->setting.flag) {
            if (entry->flags & OPT_Extend) {
              *entry->setting.flag += 1;
            } else {
              *entry->setting.flag = 1;
            }
          }
        }

        info->ensuredSettings[option] = 1;
        break;
      }

      case 0: {
        const OptionEntry *entry = optionEntries[resetLetter];
        *entry->setting.flag = 0;
        info->ensuredSettings[resetLetter] = 1;
        break;
      }

      case '?':
        logMessage(LOG_ERR, "%s: %c%c", gettext("unknown option"), prefix, optopt);
        info->syntaxError = 1;
        break;

      case ':': /* An invalid option has been specified. */
        logMessage(LOG_ERR, "%s: %c%c", gettext("missing operand"), prefix, optopt);
        info->syntaxError = 1;
        break;

      case 'H':                /* help */
        optHelpAll = 1;
      case 'h':                /* help */
        optHelp = 1;
        break;
    }
  }
  *argumentVector += optind, *argumentCount -= optind;

  if (optHelp) {
    printHelp(info, stdout, 79, argumentsSummary, optHelpAll);
    info->exitImmediately = 1;
  }

#ifdef HAVE_GETOPT_LONG
  {
    struct option *opt = longOptions;

    while (opt->name) {
      if (opt->flag) free((char *)opt->name);
      opt += 1;
    }
  }
#endif /* HAVE_GETOPT_LONG */
}
Example #29
0
int main(int argc, char *argv[])
{
    std::string procName = "JoinNewGroup";
    if (argc == 1)
    {
        printHelp(procName);
        return -1;
    }

    bool bWasError = false;

    LoginParams *loginParams = new LoginParams(argc, argv);
    SampleParams *sampleParams = new SampleParams(argc, argv);

    printSampleParams(procName, loginParams, sampleParams);
    if (!checkObligatoryParams(loginParams, sampleParams))
        return -1;

    IO2GSession *session = CO2GTransport::createSession();
    int iContingencyGroupType = 1; // OCO group

    SessionStatusListener *sessionListener = new SessionStatusListener(session, true,
                                                                       loginParams->getSessionID(),
                                                                       loginParams->getPin());
    session->subscribeSessionStatus(sessionListener);

    bool bConnected = login(session, sessionListener, loginParams);

    if (bConnected)
    {
        bool bIsAccountEmpty = !sampleParams->getAccount() || strlen(sampleParams->getAccount()) == 0;
        O2G2Ptr<IO2GAccountRow> account = getAccount(session, sampleParams->getAccount());
        ResponseListener *responseListener = new ResponseListener(session);
        session->subscribeResponse(responseListener);
        if (account)
        {
            if (bIsAccountEmpty)
            {
                sampleParams->setAccount(account->getAccountID());
                std::cout << "Account: " << sampleParams->getAccount() << std::endl;
            }

            std::vector<std::string> orderIDs(2);
            orderIDs[0] = sampleParams->getPrimaryID();
            orderIDs[1] = sampleParams->getSecondaryID();

            for (size_t i=0; i < orderIDs.size(); ++i)
            {
                if (!isOrderExists(session, sampleParams->getAccount(), orderIDs[i].c_str(), responseListener))
                {
                    std::cout << "Order '" << orderIDs[i] << "' does not exist" << std::endl;
                    bWasError = true;
                }
            }

            if (!bWasError)
            {
                O2G2Ptr<IO2GRequest> request = joinToNewGroupRequest(session, sampleParams->getAccount(),
                        orderIDs, iContingencyGroupType);
                if (request)
                {
                    responseListener->setRequestID(request->getRequestID());
                    responseListener->setOrderIDs(orderIDs);
                    session->sendRequest(request);
                    if (responseListener->waitEvents())
                    {
                        std::cout << "Done!" << std::endl;
                    }
                    else
                    {
                        std::cout << "Response waiting timeout expired" << std::endl;
                        bWasError = true;
                    }
                }
                else
                {
                    std::cout << "Cannot create request" << std::endl;
                    bWasError = true;
                }
            }
        }
        else
        {
            std::cout << "No valid accounts" << std::endl;
            bWasError = true;
        }
        session->unsubscribeResponse(responseListener);
        responseListener->release();
        logout(session, sessionListener);
    }
    else
    {
        bWasError = true;
    }

    session->unsubscribeSessionStatus(sessionListener);
    sessionListener->release();
    session->release();

    if (bWasError)
        return -1;
    return 0;
}
Example #30
0
int main(int argc, char *argv[])
{
	std::cout << "INAV SERVER v" << INAV_VERSION << std::endl;
	std::vector<Thread *> threads;
	int returnCode;

	//Print Help
	std::string parsedString = parser( argc, argv, "-h" );
	if( parsedString.size() > 0 )
		printHelp();
	parsedString = parser( argc, argv, "--help" );
	if( parsedString.size() > 0 )
		printHelp();

	//Check for debug
	parsedString = parser( argc, argv, "-vv" );
	if( parsedString.size() > 0 )
		inav::DEBUG = true;


	//check log file
	if (!inav::log)
	{
		std::cerr << "Unable to write to log file: " << inav::logFile << std::endl;
		exit(-1);
	}
	log("INAV starting up!");

	//check command line options
	//check if we should print out pcap capabile devices
	parsedString = parser( argc, argv, "-ls" );
	if ( parsedString == "set" )
	{
		log( "Server started with -ls option printing devices and halting..." );
		printDevices();
		exit(-1);
	}

	std::string device = parser( argc, argv, "-i" );
	if( device == "set" )
	{
			log( "WARNING: device flag given but no device specified! CANNOT CONTINUE" );
			exit( -1 );
	}
	std::cout << "Device(s) set to " <<   device << std::endl;
	log( "Device(s) set to " + device );
	std::vector< std::string > devices;
	if( device.size() != 0 )
		devices = parseCommas( device );

	//Setup pcap file input
	std::string file = parser( argc, argv, "-f" );
	if( file == "set" )
	{
			log( "WARNING: input selected as pcap file with no file specified. CANNOT CONTINUE" );
			exit( -1 );
	}
	std::cout << "File(s) set to " << file << std::endl;
	log( "File(s) set to " + file );
	std::vector< std::string > files;
	if( file.size() != 0 )
		files = parseCommas( file );

	std::string cvsFile = parser( argc, argv, "-c" );
	if( cvsFile == "set" )
	{
		log( "WARNING: input for cvs files is blank. CANNOT CONTINUE" );
		exit( -1 );
	}
	std::cout << "CVSFile(s) Set To " << cvsFile << std::endl;
	log( "CVSFILE(s) Set To " + cvsFile );
  std::vector< std::string > cvsFiles;
	if( cvsFile.size() != 0 ) 
		cvsFiles = parseCommas( cvsFile );

	

	//Creating different datastructures
	SnifferData snifferTemplate( inav::coutMutex, inav::logMutex, &inav::log );
	snifferTemplate.setDevice( device );
	FilterData filterData( inav::coutMutex, inav::logMutex, &inav::log );
	GraphData graphData( inav::coutMutex, inav::logMutex, &inav::log );

	log( "Creating Sniffer Thread(s)" );
	std::vector< std::string >::iterator sitr;
	for( sitr = devices.begin(); sitr != devices.end(); ++sitr )
	{
		//Set up sniffing threads
		SnifferDataHolder snifferDataHolder;
		SnifferData *snifferData = new SnifferData( snifferTemplate );
		snifferData->setDevice( *sitr );
		snifferDataHolder.snifferData = snifferData;
		snifferDataHolder.filterData = &filterData;
		Thread* thread = new Thread( sniffer );
		thread->start( (void *) &snifferDataHolder );
		threads.push_back( thread );
	}

	log( "Creating Sniffer Offline Tread(s)" );
	for( sitr = files.begin(); sitr != files.end(); ++sitr )
	{
		//Set up pcap file threads
		SnifferDataHolder snifferDataHolder;
		SnifferData *snifferData = new SnifferData( snifferTemplate );
		snifferData->setDevice( *sitr );
		snifferDataHolder.snifferData = snifferData;
		snifferDataHolder.filterData = &filterData;

		Thread* thread = new Thread( snifferOffline );
		thread->start( (void*) &snifferDataHolder );
		threads.push_back( thread );

	}

	log( "Creating cvsFile Input Thread(s) " );
	for( sitr = cvsFiles.begin(); sitr != cvsFiles.end(); ++sitr )
	{
		//Set up pcap file threads
		SnifferDataHolder snifferDataHolder;
		SnifferData *snifferData = new SnifferData( snifferTemplate );
		snifferData->setDevice( *sitr );
		snifferDataHolder.snifferData = snifferData;
		snifferDataHolder.filterData = &filterData;

		Thread* thread = new Thread( cvsSniffer );
		thread->start( (void*)&snifferDataHolder );
		threads.push_back( thread );
	}


	//Set up Bandwidth Monitor Thread
	BandwidthDataHolder bandwidthDataHolder;
	bandwidthDataHolder.filterData = &filterData;
	bandwidthDataHolder.graphData = &graphData;
	log( "Creating Bandwidth Monitor Thread" );
	

	Thread* thread = new Thread( bandwidthMonitor );
	thread->start( (void*)&bandwidthDataHolder );
	threads.push_back( thread );

	//Set up client thread
	std::string port = parser( argc, argv, "-p" );
	int portnum = communication::ServerPort;
	if( port.size() > 0 )
	{
		log( "Seting port to " + port );
		portnum = atoi( port.c_str() );
	}
	ClientCommData clientCommData( inav::coutMutex, inav::logMutex, &inav::log, portnum );
	clientCommData.filterData = &filterData;
	clientCommData.graphData = &graphData;
	log( "Creating Communication Thread" ); 

	
	thread = new Thread( communicationChannel );
	thread->start( (void*)&clientCommData );
	threads.push_back( thread );
	

	std::string debug = parser( argc, argv, "--debug" );
	if( debug.size() > 0 )
	{
		DebugData debugData;
		debugData.filterData = &filterData;
		debugData.graphData = &graphData;

		Thread* thread = new Thread( debugThread );
		thread->start( (void*)&debugData );
		threads.push_back( thread );

	}

	//Wait for threads to exit
	//(void*) 
	std::vector<Thread*>::iterator itr;
	for( itr = threads.begin(); itr != threads.end(); ++itr )
	{
		log( "Deleting Thread... " );
		(*itr)->join();
	}
	log( "INAV server halting!" );
	return 0;
}