Exemplo n.º 1
0
// handle command line arguments
void handle_arguments(int argc, char ** argv)
{
  for (int i = 1; i < argc; ++i)
  {
    std::string arg1(argv[i]);

    if (arg1 == "-A" || arg1 == "--algorithm")
    {
      if (i + 1 < argc && argv[i + 1][0] != '-')
      {
        algorithm = argv[i + 1];
      }
      else
      {
        print_usage(argv[0], argv[i]);
      }

      ++i;
    }
    else if (arg1 == "-a" || arg1 == "--accent")
    {
      if (i + 1 < argc && argv[i + 1][0] != '-')
      {
        accents.push_back(argv[i + 1]);
      }
      else
      {
        print_usage(argv[0], argv[i]);
      }

      ++i;
    }
    else if (arg1 == "-b" || arg1 == "--broadcast")
    {
      if (i + 1 < argc && argv[i + 1][0] != '-')
      {
        settings.hosts.push_back(argv[i + 1]);
        settings.type = madara::transport::BROADCAST;
      }
      else
      {
        print_usage(argv[0], argv[i]);
      }

      ++i;
    }
    else if (arg1 == "-c" || arg1 == "--checkpoint")
    {
      if (i + 1 < argc && argv[i + 1][0] != '-')
      {
        controller_settings.checkpoint_prefix = argv[i + 1];
      }
      else
      {
        print_usage(argv[0], argv[i]);
      }

      ++i;
    }
    else if (arg1 == "--checkpoint-on-loop")
    {
      controller_settings.checkpoint_strategy =
        gams::controllers::CHECKPOINT_EVERY_LOOP;
    }
    else if (arg1 == "--checkpoint-on-send")
    {
      controller_settings.checkpoint_strategy =
        gams::controllers::CHECKPOINT_EVERY_SEND;
    }
    else if (arg1 == "--checkpoint-diffs")
    {
      controller_settings.checkpoint_strategy |=
        gams::controllers::CHECKPOINT_SAVE_DIFFS;
    }
    else if (arg1 == "--checkpoint-single-file")
    {
      controller_settings.checkpoint_strategy |=
        gams::controllers::CHECKPOINT_SAVE_ONE_FILE;
    }
    else if (arg1 == "-d" || arg1 == "--domain")
    {
      if (i + 1 < argc && argv[i + 1][0] != '-')
      {
        settings.write_domain = argv[i + 1];
      }
      else
      {
        print_usage(argv[0], argv[i]);
      }

      ++i;
    }
    else if (arg1 == "-e" || arg1 == "--rebroadcasts")
    {
      if (i + 1 < argc && argv[i + 1][0] != '-')
      {
        int hops;
        std::stringstream buffer(argv[i + 1]);
        buffer >> hops;

        settings.set_rebroadcast_ttl(hops);
        settings.enable_participant_ttl(hops);
      }
      else
      {
        print_usage(argv[0], argv[i]);
      }

      ++i;
    }
Exemplo n.º 2
0
int main(int argc, char *argv[])
{
	errcode_t ret;
	uint64_t blkno, result_blkno;
	int c, len;
	char *filename, *lookup_path, *buf;
	char *filebuf;
	char *p;
	char lookup_name[256];
	ocfs2_filesys *fs;

	blkno = 0;

	initialize_ocfs_error_table();

	while ((c = getopt(argc, argv, "i:")) != EOF) {
		switch (c) {
			case 'i':
				blkno = read_number(optarg);
				if (blkno <= OCFS2_SUPER_BLOCK_BLKNO) {
					fprintf(stderr,
						"Invalid inode block: %s\n",
						optarg);
					print_usage();
					return 1;
				}
				break;

			default:
				print_usage();
				return 1;
				break;
		}
	}

	if (optind >= argc) {
		fprintf(stderr, "Missing filename\n");
		print_usage();
		return 1;
	}
	filename = argv[optind];
	optind++;

	if (optind >= argc) {
		fprintf(stdout, "Missing path to lookup\n");
		print_usage();
		return 1;
	}
	lookup_path = argv[optind];

	ret = ocfs2_open(filename, OCFS2_FLAG_RO, 0, 0, &fs);
	if (ret) {
		com_err(argv[0], ret,
			"while opening file \"%s\"", filename);
		goto out;
	}

	ret = ocfs2_malloc_block(fs->fs_io, &buf);
	if (ret) {
		com_err(argv[0], ret,
			"while allocating inode buffer");
		goto out_close;
	}

	if (!blkno)
		blkno = OCFS2_RAW_SB(fs->fs_super)->s_root_blkno;

	for (p = lookup_path; *p == '/'; p++);

	lookup_path = p;

	for (p = lookup_path; ; p++) {
		if (*p && *p != '/')
			continue;

		memcpy(lookup_name, lookup_path, p - lookup_path);
		lookup_name[p - lookup_path] = '\0';
		ret = ocfs2_lookup(fs, blkno, lookup_name,
				   strlen(lookup_name), NULL,
				   &result_blkno);
		if (ret) {
			com_err(argv[0], ret,
				"while looking up \"%s\" in inode %"PRIu64
			       	" on \"%s\"\n",
				lookup_name, blkno, filename);
			goto out_free;
		}

		blkno = result_blkno;

		for (; *p == '/'; p++);

		lookup_path = p;

		if (!*p)
			break;
	}

	if (ocfs2_check_directory(fs, blkno) != OCFS2_ET_NO_DIRECTORY) {
		com_err(argv[0], ret, "\"%s\" is not a file", filename);
		goto out_free;
	}

	ret = ocfs2_read_whole_file(fs, blkno, &filebuf, &len);
	if (ret) {
		com_err(argv[0], ret,
			"while reading file \"%s\" -- read %d bytes",
			filename, len);
		goto out_free_filebuf;
	}
	if (!len)
		fprintf(stderr, "boo!\n");

	dump_filebuf(filebuf, len);

out_free_filebuf:
	if (len)
		ocfs2_free(&filebuf);

out_free:
	ocfs2_free(&buf);

out_close:
	ret = ocfs2_close(fs);
	if (ret) {
		com_err(argv[0], ret,
			"while closing file \"%s\"", filename);
	}

out:
	return 0;
}
Exemplo n.º 3
0
int main(int argc, char *argv[]) {
    struct option longopts[] = {
        { "listen",	no_argument,		NULL,	'l' },
        { "connect",	no_argument,		NULL,	'c' },
        { "send",	no_argument,		NULL,	's' },
        { "receive",	no_argument,		NULL,	'r' },
        { "port",	required_argument,	NULL,	'p' },
        { "buffer",	required_argument,	NULL,	'b' },
        { "help",	no_argument,		NULL,	'h' },
        { "version",	no_argument,		NULL,	'V' },
        { NULL, 0, NULL, 0 }
    };
    int opt;
    enum { LISTEN=1, CONNECT } mode = 0;
    enum { SEND=1, RECEIVE } direction = 0;
    int port = 0;
    int buffer_size = 0;
    char *rhost = NULL;
    int sock;

    argv0=argv[0];

    while ((opt=getopt_long(argc, argv, "-lcsrp:b:hV", longopts, NULL)) != -1) {
        switch (opt) {
            char *tailptr;
        case 'l':
            if (mode==0) mode=LISTEN;
            else param_error(NULL);
            break;
        case 'c':
            if (mode==0) mode=CONNECT;
            else param_error(NULL);
            break;
        case 's':
            if (direction==0) direction=SEND;
            else param_error(NULL);
            break;
        case 'r':
            if (direction==0) direction=RECEIVE;
            else param_error(NULL);
            break;
        case 'p':
            if (port==0) {
                errno=0;
                port = strtol(optarg, &tailptr, 0);
                if (errno || *tailptr!=0) param_error(NULL);
            }
            else param_error(NULL);
            break;
        case 'b':
            if (buffer_size==0) {
                errno=0;
                buffer_size = strtol(optarg, &tailptr, 0);
                if (errno || *tailptr!=0) param_error(NULL);
            }
            else param_error(NULL);
            break;
        case 'h':
            print_usage();
            break;
        case 'V':
            print_version();
            break;
        case 1:
            if (rhost==NULL) rhost=optarg;
            else param_error(NULL);
            break;
        case '?':
            param_error("");
            break;
        default:
            oops();
            break;
        }
    }
    if (mode==0) param_error(NULL);
    if (direction==0) direction = mode==LISTEN ? SEND : RECEIVE;
    if (port==0) param_error(NULL);
    if (port<0 || port>65535) param_error(NULL);
    if (buffer_size==0) buffer_size = DEFAULT_BUFFER_SIZE;
    if (buffer_size<0) param_error(NULL);
    if (mode==CONNECT && rhost==NULL) param_error(NULL);

    switch (mode) {
    case LISTEN:
        sock = do_listen(port, rhost);
        break;
    case CONNECT:
        sock = do_connect(port, rhost);
        break;
    default:
        oops();
        break;
    }
    switch (direction) {
    case SEND:
        do_transfer(STDIN_FILENO, sock, buffer_size);
        break;
    case RECEIVE:
        do_transfer(sock, STDOUT_FILENO, buffer_size);
        break;
    default:
        oops();
        break;
    }
    return 0;
}
Exemplo n.º 4
0
Arquivo: main.c Projeto: blogc/blogc
int
main(int argc, char **argv)
{
    struct sigaction new_action;
    new_action.sa_handler = SIG_IGN;
    sigemptyset(&new_action.sa_mask);
    new_action.sa_flags = 0;
    sigaction(SIGPIPE, &new_action, NULL);

    int rv = 0;
    char *host = NULL;
    char *port = NULL;
    char *docroot = NULL;
    size_t max_threads = 20;
    char *ptr;
    char *endptr;

    char *tmp_host = getenv("BLOGC_RUNSERVER_DEFAULT_HOST");
    char *default_host = bc_strdup(tmp_host != NULL ? tmp_host : "127.0.0.1");
    char *tmp_port = getenv("BLOGC_RUNSERVER_DEFAULT_PORT");
    char *default_port = bc_strdup(tmp_port != NULL ? tmp_port : "8080");

    size_t args = 0;

    for (size_t i = 1; i < argc; i++) {
        if (argv[i][0] == '-') {
            switch (argv[i][1]) {
                case 'h':
                    print_help(default_host, default_port);
                    goto cleanup;
                case 'v':
                    printf("%s\n", PACKAGE_STRING);
                    goto cleanup;
                case 't':
                    if (argv[i][2] != '\0')
                        host = bc_strdup(argv[i] + 2);
                    else
                        host = bc_strdup(argv[++i]);
                    break;
                case 'p':
                    if (argv[i][2] != '\0')
                        port = bc_strdup(argv[i] + 2);
                    else
                        port = bc_strdup(argv[++i]);
                    break;
                case 'm':
                    if (argv[i][2] != '\0')
                        ptr = argv[i] + 2;
                    else
                        ptr = argv[++i];
                    max_threads = strtoul(ptr, &endptr, 10);
                    if (*ptr != '\0' && *endptr != '\0')
                        fprintf(stderr, "blogc-runserver: warning: invalid value "
                            "for -m argument: %s. using %zu instead\n", ptr, max_threads);
                    break;
                default:
                    print_usage();
                    fprintf(stderr, "blogc-runserver: error: invalid "
                        "argument: -%c\n", argv[i][1]);
                    rv = 1;
                    goto cleanup;
            }
        }
        else {
            if (args > 0) {
                print_usage();
                fprintf(stderr, "blogc-runserver: error: only one positional "
                    "argument allowed\n");
                rv = 1;
                goto cleanup;
            }
            args++;
            docroot = bc_strdup(argv[i]);
        }
    }

    if (docroot == NULL) {
        print_usage();
        fprintf(stderr, "blogc-runserver: error: document root directory "
            "required\n");
        rv = 1;
        goto cleanup;
    }

    if (max_threads <= 0 || max_threads > 1000) {
        print_usage();
        fprintf(stderr, "blogc-runserver: error: invalid value for -m. "
            "Must be integer > 0 and <= 1000\n");
        rv = 1;
        goto cleanup;
    }

    rv = br_httpd_run(
        host != NULL ? host : default_host,
        port != NULL ? port : default_port,
        docroot, max_threads);

cleanup:
    free(default_host);
    free(default_port);
    free(host);
    free(port);
    free(docroot);

    return rv;
}
Exemplo n.º 5
0
void
get_options(int argc, char *argv[], struct dicod_conf_override *conf)
{
    
#line 176
 {
#line 176
  int c;
#line 176

#line 176
#ifdef HAVE_GETOPT_LONG
#line 176
  while ((c = getopt_long(argc, argv, "EtifsTx:I:D:hV",
#line 176
			  long_options, NULL)) != EOF)
#line 176
#else
#line 176
  while ((c = getopt(argc, argv, "EtifsTx:I:D:hV")) != EOF)
#line 176
#endif
#line 176
    {
#line 176
      switch (c)
#line 176
	{
#line 176
	default:
#line 176
	   exit(EX_USAGE);	   exit(EX_USAGE);
#line 176
	#line 38 "cmdline.opt"
	 case 'E':
#line 38
	  {
#line 38

   mode = MODE_PREPROC;

#line 40
	     break;
#line 40
	  }
#line 44 "cmdline.opt"
	 case 't':
#line 44
	  {
#line 44

   config_lint_option = 1;

#line 46
	     break;
#line 46
	  }
#line 50 "cmdline.opt"
	 case 'i':
#line 50
	  {
#line 50

   mode = MODE_INETD;

#line 52
	     break;
#line 52
	  }
#line 58 "cmdline.opt"
	 case OPTION_CONFIG:
#line 58
	  {
#line 58

   config_file = optarg;

#line 60
	     break;
#line 60
	  }
#line 64 "cmdline.opt"
	 case 'f':
#line 64
	  {
#line 64

   foreground = 1;

#line 66
	     break;
#line 66
	  }
#line 70 "cmdline.opt"
	 case OPTION_STDERR:
#line 70
	  {
#line 70

   log_to_stderr = 1;

#line 72
	     break;
#line 72
	  }
#line 76 "cmdline.opt"
	 case OPTION_SYSLOG:
#line 76
	  {
#line 76

   log_to_stderr = 0;

#line 78
	     break;
#line 78
	  }
#line 82 "cmdline.opt"
	 case 's':
#line 82
	  {
#line 82

   single_process = 1;

#line 84
	     break;
#line 84
	  }
#line 90 "cmdline.opt"
	 case 'T':
#line 90
	  {
#line 90

   conf->transcript = 1;

#line 92
	     break;
#line 92
	  }
#line 96 "cmdline.opt"
	 case OPTION_NO_TRANSCRIPT:
#line 96
	  {
#line 96

   conf->transcript = 0;

#line 98
	     break;
#line 98
	  }
#line 102 "cmdline.opt"
	 case 'x':
#line 102
	  {
#line 102

   debug_level_str = optarg;
   debug_level = atoi(optarg);

#line 105
	     break;
#line 105
	  }
#line 109 "cmdline.opt"
	 case OPTION_SOURCE_INFO:
#line 109
	  {
#line 109

  debug_source_info = 1;

#line 111
	     break;
#line 111
	  }
#line 115 "cmdline.opt"
	 case OPTION_TRACE_GRAMMAR:
#line 115
	  {
#line 115

   grecs_gram_trace(1);

#line 117
	     break;
#line 117
	  }
#line 121 "cmdline.opt"
	 case OPTION_TRACE_LEX:
#line 121
	  {
#line 121

   grecs_lex_trace(1);

#line 123
	     break;
#line 123
	  }
#line 129 "cmdline.opt"
	 case OPTION_CONFIG_HELP:
#line 129
	  {
#line 129

   config_help();
   exit(0);

#line 132
	     break;
#line 132
	  }
#line 138 "cmdline.opt"
	 case OPTION_PREPROCESSOR:
#line 138
	  {
#line 138

   grecs_preprocessor = optarg;

#line 140
	     break;
#line 140
	  }
#line 144 "cmdline.opt"
	 case OPTION_NO_PREPROCESSOR:
#line 144
	  {
#line 144

   grecs_preprocessor = NULL;

#line 146
	     break;
#line 146
	  }
#line 150 "cmdline.opt"
	 case 'I':
#line 150
	  {
#line 150

   grecs_preproc_add_include_dir(optarg); 

#line 152
	     break;
#line 152
	  }
#line 156 "cmdline.opt"
	 case 'D':
#line 156
	  {
#line 156

   char *p;

   if (!pp_cmd_acc)
       pp_cmd_acc = grecs_txtacc_create();
   grecs_txtacc_grow(pp_cmd_acc, " \"-D", 4);
   for (p = optarg; *p; p++) {
       if (*p == '\\' || *p == '"')
	   grecs_txtacc_grow_char(pp_cmd_acc, '\\');
       grecs_txtacc_grow_char(pp_cmd_acc, *p);
   }
   grecs_txtacc_grow_char(pp_cmd_acc, '"');			

#line 168
	     break;
#line 168
	  }
#line 171 "cmdline.opt"
	 case 'h':
#line 171
	  {
#line 171

#line 171
		print_help ();
#line 171
		exit (0);
#line 171
	 
#line 171
	     break;
#line 171
	  }
#line 171 "cmdline.opt"
	 case OPTION_USAGE:
#line 171
	  {
#line 171

#line 171
		print_usage ();
#line 171
		exit (0);
#line 171
	 
#line 171
	     break;
#line 171
	  }
#line 171 "cmdline.opt"
	 case 'V':
#line 171
	  {
#line 171

#line 171
		/* Give version */
#line 171
		print_version(program_version, stdout);
#line 171
		exit (0);
#line 171
	 
#line 171
	     break;
#line 171
	  }

#line 176 "cmdline.opt"
	}
#line 176
    }
#line 176
  
#line 176
    if (optind < argc) {
#line 176
	fprintf(stderr, "%s: unexpected arguments\n", argv[0]);
#line 176
	exit(EX_USAGE);
#line 176
    }
#line 176

#line 176
  if (cmdline_tree)
#line 176
    {
#line 176
      struct grecs_node *rn = grecs_node_create(grecs_node_root, NULL);
#line 176
      rn->down = cmdline_tree;
#line 176
      cmdline_tree = rn;
#line 176
    }
#line 176
 }
#line 176

    if (pp_cmd_acc && grecs_preprocessor) {
	char *args, *cmd;

	grecs_txtacc_grow_char(pp_cmd_acc, 0);
	args = grecs_txtacc_finish(pp_cmd_acc, 0);
	cmd = grecs_malloc(strlen(grecs_preprocessor) +
			   strlen(args) + 1);
	strcpy(cmd, grecs_preprocessor);
	strcat(cmd, args);
	grecs_preprocessor = cmd;
    }
    grecs_txtacc_free(pp_cmd_acc);
}
Exemplo n.º 6
0
int main (int argc, char ** argv)
{
	//const clock_t begin_time = clock();
	
	if (argc<3) {
		print_usage ();
	}
	
	////////////////////////////////////////////////////////////
	// Init parameters
	//
	std::string input_file_name;
	std::string bv_file_name;
	std::string output_file_name;
	bool compress = false;
	
	////////////////////////////////////////////////////////////
	// Read command line arguments
	//
	int arg_pos = 1;
	while (arg_pos < argc){
		std::string flag = argv[arg_pos];
		if (flag[0] != '-') {
			if (input_file_name.empty()) {
				input_file_name = flag;
			} else if (bv_file_name.empty()){
				bv_file_name = flag;
			} else {
				std::cerr << "The mandatory files are already set, unknown file " << flag << " -> ignore\n";
			}
		} else if (flag.compare("-o") == 0) {
			arg_pos++;
			output_file_name = argv[arg_pos];
		} else if (flag.compare("-h") == 0) {
			print_usage ();
			return 0;
		} else if (flag.compare("-v") == 0) {
			std::cout << "\nextract_reads version " << version << "\n";
			return 0;
		} else {
			std::cerr << "Unknown option " << flag << "\n";
            print_usage ();
			return (0);
		}
		arg_pos++;
	}
	
	if (input_file_name.empty()) {
		std::cerr << "Error: An input file name is needed -> exit\n";
		print_usage ();
		return (0);
	} else if (bv_file_name.empty()) {
		std::cerr << "Error: A bv file name is needed -> exit\n";
		print_usage ();
		return (0);
	}
	
	////////////////////////////////////////////////////////////
	// Open the given file to check its type (fasta, fastq, gzip ?)
	//
	ReadFile * read_file = NULL;
	
	std::ifstream infile;
	infile.open(input_file_name.c_str());
	if (!infile.good()) {
		std::cerr << "Cannot open file file " << input_file_name << " -> ignore\n";
	}
	// Check the first char
	std::string basename = input_file_name.substr(input_file_name.rfind("/")+1);
	char c = infile.get();
	if (c == '>') {
		infile.close();
		read_file = new FastaFile(input_file_name, bv_file_name);
	} else if (c == '@') {
		infile.close();
		read_file = new FastqFile(input_file_name, bv_file_name);
	} else {
		infile.close();
		gzFile tmp_gz_file = (gzFile) gzopen(input_file_name.c_str(), "r");
		if (!tmp_gz_file) {
			std::cerr << "Cannot open file " << input_file_name << " -> ignore\n";
			exit(1);
		}
		c = gzgetc(tmp_gz_file);
		if (c == '>') {
			gzclose(tmp_gz_file);
			compress = true;
			read_file = new GzFastaFile(input_file_name, bv_file_name);
		} else if (c == '@') {
			gzclose(tmp_gz_file);
			compress = true;
			read_file = new GzFastqFile(input_file_name, bv_file_name);
		} else {
			std::cerr << "Unknown format: " << input_file_name << " -> ignore\n";
		}
	}
	
	////////////////////////////////////////////////////////////
	// Open the output file and write selected reads in it
	// Different behaviors if : - output file name is given
	//                          - compress is true or not
	//
	if (compress) {
		if (output_file_name.empty()) {
			std::cerr << "Error, try to compress results but no output file name is given\n";
			exit(1);
		}
		gzFile filetmp = (gzFile) gzopen(output_file_name.c_str(), "w6");
		if (filetmp == NULL) {
			std::cerr << "Error, cannot open file " << output_file_name << "\n";
		}
		std::string & current_read = read_file->get_next_read();
		while (!current_read.empty()) {
			gzprintf(filetmp, "%s", read_file->get_data().c_str());
			current_read = read_file->get_next_read();
		}
		gzclose(filetmp);
	} else {
		if (!output_file_name.empty()) {
			std::ofstream outfile;
			outfile.open (output_file_name.c_str());
			if (!outfile.good()) {
				std::cerr << "Cannot write on file " << output_file_name << "\n";
				return 1;
			}
			std::string & current_read = read_file->get_next_read();
			while (!current_read.empty()) {
				outfile << read_file->get_data();
				current_read = read_file->get_next_read();
			}
			outfile.close();
		} else {
			std::string & current_read = read_file->get_next_read();
			while (!current_read.empty()) {
				std::cout << read_file->get_data();
				current_read = read_file->get_next_read();
			}
		}
	}
	
	if (read_file != NULL) {
		delete read_file;
	}
	return 0;
}
Exemplo n.º 7
0
int
main(int argc, char *argv[])
#endif
{
	iptc_handle_t handle = NULL;
	char buffer[10240];
	int c;
	char curtable[IPT_TABLE_MAXNAMELEN + 1];
	FILE *in;
	const char *modprobe = 0;
	int in_table = 0, testing = 0;

	program_name = "iptables-restore";
	program_version = IPTABLES_VERSION;
	line = 0;

	lib_dir = getenv("IPTABLES_LIB_DIR");
	if (!lib_dir)
		lib_dir = IPT_LIB_DIR;

#ifdef NO_SHARED_LIBS
	init_extensions();
#endif

	while ((c = getopt_long(argc, argv, "bcvthnM:", options, NULL)) != -1) {
		switch (c) {
			case 'b':
				binary = 1;
				break;
			case 'c':
				counters = 1;
				break;
			case 'v':
				verbose = 1;
				break;
			case 't':
				testing = 1;
				break;
			case 'h':
				print_usage("iptables-restore",
					    IPTABLES_VERSION);
				break;
			case 'n':
				noflush = 1;
				break;
			case 'M':
				modprobe = optarg;
				break;
		}
	}
	
	if (optind == argc - 1) {
		in = fopen(argv[optind], "r");
		if (!in) {
			fprintf(stderr, "Can't open %s: %s\n", argv[optind],
				strerror(errno));
			exit(1);
		}
	}
	else if (optind < argc) {
		fprintf(stderr, "Unknown arguments found on commandline\n");
		exit(1);
	}
	else in = stdin;
	
	/* Grab standard input. */
	while (fgets(buffer, sizeof(buffer), in)) {
		int ret = 0;

		line++;
		if (buffer[0] == '\n')
			continue;
		else if (buffer[0] == '#') {
			if (verbose)
				fputs(buffer, stdout);
			continue;
		} else if ((strcmp(buffer, "COMMIT\n") == 0) && (in_table)) {
			if (!testing) {
				DEBUGP("Calling commit\n");
				ret = iptc_commit(&handle);
			} else {
				DEBUGP("Not calling commit, testing\n");
				ret = 1;
			}
			in_table = 0;
		} else if ((buffer[0] == '*') && (!in_table)) {
			/* New table */
			char *table;

			table = strtok(buffer+1, " \t\n");
			DEBUGP("line %u, table '%s'\n", line, table);
			if (!table) {
				exit_error(PARAMETER_PROBLEM, 
					"%s: line %u table name invalid\n",
					program_name, line);
				exit(1);
			}
			strncpy(curtable, table, IPT_TABLE_MAXNAMELEN);
			curtable[IPT_TABLE_MAXNAMELEN] = '\0';

			if (handle)
				iptc_free(&handle);

			handle = create_handle(table, modprobe);
			if (noflush == 0) {
				DEBUGP("Cleaning all chains of table '%s'\n",
					table);
				for_each_chain(flush_entries, verbose, 1, 
						&handle);
	
				DEBUGP("Deleting all user-defined chains "
				       "of table '%s'\n", table);
				for_each_chain(delete_chain, verbose, 0, 
						&handle) ;
			}

			ret = 1;
			in_table = 1;

		} else if ((buffer[0] == ':') && (in_table)) {
			/* New chain. */
			char *policy, *chain;

			chain = strtok(buffer+1, " \t\n");
			DEBUGP("line %u, chain '%s'\n", line, chain);
			if (!chain) {
				exit_error(PARAMETER_PROBLEM,
					   "%s: line %u chain name invalid\n",
					   program_name, line);
				exit(1);
			}

			if (iptc_builtin(chain, handle) <= 0) {
				if (noflush && iptc_is_chain(chain, handle)) {
					DEBUGP("Flushing existing user defined chain '%s'\n", chain);
					if (!iptc_flush_entries(chain, &handle))
						exit_error(PARAMETER_PROBLEM,
							   "error flushing chain "
							   "'%s':%s\n", chain,
							   strerror(errno));
				} else {
					DEBUGP("Creating new chain '%s'\n", chain);
					if (!iptc_create_chain(chain, &handle))
						exit_error(PARAMETER_PROBLEM,
							   "error creating chain "
							   "'%s':%s\n", chain,
							   strerror(errno));
				}
			}

			policy = strtok(NULL, " \t\n");
			DEBUGP("line %u, policy '%s'\n", line, policy);
			if (!policy) {
				exit_error(PARAMETER_PROBLEM,
					   "%s: line %u policy invalid\n",
					   program_name, line);
				exit(1);
			}

			if (strcmp(policy, "-") != 0) {
				struct ipt_counters count;

				if (counters) {
					char *ctrs;
					ctrs = strtok(NULL, " \t\n");

					if (!ctrs || !parse_counters(ctrs, &count))
						exit_error(PARAMETER_PROBLEM,
							   "invalid policy counters "
							   "for chain '%s'\n", chain);

				} else {
					memset(&count, 0, 
					       sizeof(struct ipt_counters));
				}

				DEBUGP("Setting policy of chain %s to %s\n",
					chain, policy);

				if (!iptc_set_policy(chain, policy, &count,
						     &handle))
					exit_error(OTHER_PROBLEM,
						"Can't set policy `%s'"
						" on `%s' line %u: %s\n",
						chain, policy, line,
						iptc_strerror(errno));
			}

			ret = 1;

		} else if (in_table) {
			int a;
			char *ptr = buffer;
			char *pcnt = NULL;
			char *bcnt = NULL;
			char *parsestart;

			/* the parser */
			char *curchar;
			int quote_open;
			int param_len;

			/* reset the newargv */
			newargc = 0;

			if (buffer[0] == '[') {
				/* we have counters in our input */
				ptr = strchr(buffer, ']');
				if (!ptr)
					exit_error(PARAMETER_PROBLEM,
						   "Bad line %u: need ]\n",
						   line);

				pcnt = strtok(buffer+1, ":");
				if (!pcnt)
					exit_error(PARAMETER_PROBLEM,
						   "Bad line %u: need :\n",
						   line);

				bcnt = strtok(NULL, "]");
				if (!bcnt)
					exit_error(PARAMETER_PROBLEM,
						   "Bad line %u: need ]\n",
						   line);

				/* start command parsing after counter */
				parsestart = ptr + 1;
			} else {
				/* start command parsing at start of line */
				parsestart = buffer;
			}

			add_argv(argv[0]);
			add_argv("-t");
			add_argv((char *) &curtable);
			
			if (counters && pcnt && bcnt) {
				add_argv("--set-counters");
				add_argv((char *) pcnt);
				add_argv((char *) bcnt);
			}

			/* After fighting with strtok enough, here's now
			 * a 'real' parser. According to Rusty I'm now no
			 * longer a real hacker, but I can live with that */

			quote_open = 0;
			param_len = 0;
			
			for (curchar = parsestart; *curchar; curchar++) {
				char param_buffer[1024];

				if (*curchar == '"') {
					/* quote_open cannot be true if there
					 * was no previous character.  Thus, 
					 * curchar-1 has to be within bounds */
					if (quote_open && 
					    *(curchar-1) != '\\') {
						quote_open = 0;
						*curchar = ' ';
					} else if (!quote_open) {
						quote_open = 1;
						continue;
					}
				} 
				if (*curchar == ' '
				    || *curchar == '\t'
				    || * curchar == '\n') {

					if (quote_open) {
						param_buffer[param_len++] = 
								*curchar;
						continue;
					}

					if (!param_len) {
						/* two spaces? */
						continue;
					}

					param_buffer[param_len] = '\0';

					/* check if table name specified */
					if (!strncmp(param_buffer, "-t", 3)
                                            || !strncmp(param_buffer, "--table", 8)) {
						exit_error(PARAMETER_PROBLEM, 
						   "Line %u seems to have a "
						   "-t table option.\n", line);
						exit(1);
					}

					add_argv(param_buffer);
					param_len = 0;
				} else {
					/* Skip backslash that escapes quote: 
					 * the standard input does not require
					 * escaping. However, the output
					 * generated by iptables-save
					 * introduces bashlash to keep
					 * consistent with iptables
					 */
					if (quote_open &&
					    *curchar == '\\' &&
					    *(curchar+1) == '"')
						continue;

					/* regular character, copy to buffer */
					param_buffer[param_len++] = *curchar;

					if (param_len >= sizeof(param_buffer))
						exit_error(PARAMETER_PROBLEM, 
						   "Parameter too long!");
				}
			}

			DEBUGP("calling do_command(%u, argv, &%s, handle):\n",
				newargc, curtable);

			for (a = 0; a < newargc; a++)
				DEBUGP("argv[%u]: %s\n", a, newargv[a]);

			ret = do_command(newargc, newargv, 
					 &newargv[2], &handle);

			free_argv();
		}
		if (!ret) {
			fprintf(stderr, "%s: line %u failed\n",
					program_name, line);
			exit(1);
		}
	}
	if (in_table) {
		fprintf(stderr, "%s: COMMIT expected at line %u\n",
				program_name, line + 1);
		exit(1);
	}

	return 0;
}
Exemplo n.º 8
0
/* --------------------------------------------- */
static void print_help(void) {
    print_usage() ;
    printf("WARNING: this program is not yet tested!\n");
    exit(1) ;
}
Exemplo n.º 9
0
int main(int argc, char *const *argv){
	char buf[PATH_MAX+1];
	char *simcount = 0;
	int simul_count = 10;
	char *original_path = 0;
	int path_passed = 0;

	int opt= 0;
	//Specifying the expected options
	// TODO: set simcount as an optional parameter
	static struct option long_options[] = {
		{"simcount",  required_argument, 0,  's' },
		{"path",      required_argument, 0,  'p' },
		{"help",      no_argument,       0,  'h' },
		{0,           0,                 0,   0  }
	};

	int long_index =0;
	while ((opt = getopt_long(argc, argv, "s:p:",
				long_options, &long_index )) != -1) {
		switch (opt) {
			// `optarg` is a global variable from getopt.h
			case 's' : simcount = strdup(optarg);
				break;
			case 'p' : path_passed = 1; original_path = realpath(optarg, buf);
				break;
			case 'h' : print_usage(); exit(0);
			default: print_usage();
				exit(EXIT_FAILURE);
		}
	}

	// Check that a path was specified and that it is a valid path
	if (path_passed && !original_path) {
		printf("Path was given, but was invalid.\n");
		print_usage();
		exit(EXIT_FAILURE);
	} else if (!path_passed) {
		printf("Path was not specified.\n");
		print_usage();
		exit(EXIT_FAILURE);
	}

	// Convert the given "simcount" to a number, store in `simul_count`
	if (simcount){
		errno = 0;
		long tmp = strtol(simcount, 0, 10);
		// TODO: implement converter
		if (errno != 0){
			printf("Could not convert specified simcount into a valid number.\n");
			print_usage();
			exit(EXIT_FAILURE);
		}
		simul_count = tmp;
	}

	printf("original_path: %s, simul_count: %d\n", original_path, simul_count);

	reverse_file(original_path, simul_count);

	//char* test[] = {
	//	"spinelessness prayed doppelgangers notabilities syllabification unflinching",
	//	"coccyx Msgr environments subjecting Duroc ibis  fetus whack wile",
	//	"nippy demoed pretax voltmeters bougainvillea garish weedkillers",
	//};
	//int i = 0;
	//for (i = 0; i < 3; ++i){
	//	char* rv = in_place_reverse_words(strdup(test[i]));
	//	free(rv);
	//}
	return 0;
}
Exemplo n.º 10
0
void do_config(int argc, char **argv)
{
	char *s;
	int i, c, known;
	int got_conffile = 0, print_config = 0;
	size_t s_len;

	for (i = 1; i < argc; i++) {
		if (argv[i][0] && (argv[i][0] != '-' || argv[i][1] == '\0')) {
			read_config_file(argv[i], config, 0);
			got_conffile = 1;
			continue;
		}

		known = 0;

		for (c = 0; config_names[c].name != NULL && !known; c++) {
			if (config_names[c].option == NULL
				|| strncmp(argv[i], config_names[c].option,
					strlen(config_names[c].option)) != 0)
				continue;

			s = NULL;

			known = 1;
			if (argv[i][strlen(config_names[c].option)] == '=')
				s = argv[i] + strlen(config_names[c].option) + 1;
			else if (argv[i][strlen(config_names[c].option)] == 0) {
				if (config_names[c].needsArgument) {
					if (i + 1 < argc)
						s = argv[++i];
					else
						known = 0;
				} else
					s = argv[i]; /* no arg, fill in something */
			} else
				known = 0;
			if (known)
				config[config_names[c].nm] = s;
		}

		if (!known && strcmp(argv[i], "--version") == 0) {
			print_version();
			exit(0);
		}
		if (!known && strcmp(argv[i], "--print-config") == 0) {
			print_config = 1;
			known = 1;
		}
		if (!known && strcmp(argv[i], "--help") == 0) {
			print_usage(argv[0], 0);
			exit(0);
		}
		if (!known && strcmp(argv[i], "--long-help") == 0) {
			print_usage(argv[0], 1);
			exit(0);
		}
		if (!known) {
			printf("%s: unknown option %s\n\n", argv[0], argv[i]);

			print_usage(argv[0], 1);
			exit(1);
		}
	}
	
	if (!got_conffile) {
		read_config_file("/etc/vpnc/default.conf", config, 1);
		read_config_file("/etc/vpnc.conf", config, 1);
	}
	
	if (!print_config) {
		for (i = 0; config_names[i].name != NULL; i++)
			if (!config[config_names[i].nm]
				&& config_names[i].get_def != NULL)
				config[config_names[i].nm] = config_names[i].get_def();
		
		opt_debug = (config[CONFIG_DEBUG]) ? atoi(config[CONFIG_DEBUG]) : 0;
		opt_nd = (config[CONFIG_ND]) ? 1 : 0;
		opt_1des = (config[CONFIG_ENABLE_1DES]) ? 1 : 0;

		if (!strcmp(config[CONFIG_AUTH_MODE], "psk")) {
			opt_auth_mode = AUTH_MODE_PSK;
		} else if (!strcmp(config[CONFIG_AUTH_MODE], "cert")) {
			opt_auth_mode = AUTH_MODE_CERT;
		} else if (!strcmp(config[CONFIG_AUTH_MODE], "hybrid")) {
			opt_auth_mode = AUTH_MODE_HYBRID;
		} else {
			printf("%s: unknown authentication mode %s\nknown modes: psk cert hybrid\n", argv[0], config[CONFIG_AUTH_MODE]);
			exit(1);
		}
#ifndef OPENSSL_GPL_VIOLATION
		if (opt_auth_mode == AUTH_MODE_HYBRID ||
			opt_auth_mode == AUTH_MODE_CERT) {
			printf("%s was built without openssl: Can't do hybrid or cert mode.\n", argv[0]);
			exit(1);
		}
#endif
		opt_no_encryption = (config[CONFIG_ENABLE_NO_ENCRYPTION]) ? 1 : 0;
		opt_udpencapport=atoi(config[CONFIG_UDP_ENCAP_PORT]);
		
		if (!strcmp(config[CONFIG_NATT_MODE], "natt")) {
			opt_natt_mode = NATT_NORMAL;
		} else if (!strcmp(config[CONFIG_NATT_MODE], "none")) {
			opt_natt_mode = NATT_NONE;
		} else if (!strcmp(config[CONFIG_NATT_MODE], "force-natt")) {
			opt_natt_mode = NATT_FORCE;
		} else if (!strcmp(config[CONFIG_NATT_MODE], "cisco-udp")) {
			opt_natt_mode = NATT_CISCO_UDP;
		} else {
			printf("%s: unknown nat traversal mode %s\nknown modes: natt none force-natt cisco-udp\n", argv[0], config[CONFIG_NATT_MODE]);
			exit(1);
		}
		
		if (!strcmp(config[CONFIG_IF_MODE], "tun")) {
			opt_if_mode = IF_MODE_TUN;
		} else if (!strcmp(config[CONFIG_IF_MODE], "tap")) {
			opt_if_mode = IF_MODE_TAP;
		} else {
			printf("%s: unknown interface mode %s\nknown modes: tun tap\n", argv[0], config[CONFIG_IF_MODE]);
			exit(1);
		}
		
		if (!strcmp(config[CONFIG_VENDOR], "cisco")) {
			opt_vendor = VENDOR_CISCO;
		} else if (!strcmp(config[CONFIG_VENDOR], "netscreen")) {
			opt_vendor = VENDOR_NETSCREEN;
		} else {
			printf("%s: unknown vendor %s\nknown vendors: cisco netscreen\n", argv[0], config[CONFIG_VENDOR]);
			exit(1);
		}
	}
	
	if (opt_debug >= 99) {
		printf("WARNING! active debug level is >= 99, output includes username and password (hex encoded)\n");
		fprintf(stderr,
			"WARNING! active debug level is >= 99, output includes username and password (hex encoded)\n");
	}
	
	config_deobfuscate(CONFIG_IPSEC_SECRET_OBF, CONFIG_IPSEC_SECRET);
	config_deobfuscate(CONFIG_XAUTH_PASSWORD_OBF, CONFIG_XAUTH_PASSWORD);
	
	for (i = 0; i < LAST_CONFIG; i++) {
		if (config[i] != NULL || config[CONFIG_NON_INTERACTIVE] != NULL)
			continue;
		if (config[CONFIG_XAUTH_INTERACTIVE] && i == CONFIG_XAUTH_PASSWORD)
			continue;
		
		s = NULL;
		s_len = 0;

		switch (i) {
		case CONFIG_IPSEC_GATEWAY:
			printf("Enter IPSec gateway address: ");
			break;
		case CONFIG_IPSEC_ID:
			printf("Enter IPSec ID for %s: ", config[CONFIG_IPSEC_GATEWAY]);
			break;
		case CONFIG_IPSEC_SECRET:
			printf("Enter IPSec secret for %s@%s: ",
				config[CONFIG_IPSEC_ID], config[CONFIG_IPSEC_GATEWAY]);
			break;
		case CONFIG_XAUTH_USERNAME:
			printf("Enter username for %s: ", config[CONFIG_IPSEC_GATEWAY]);
			break;
		case CONFIG_XAUTH_PASSWORD:
			printf("Enter password for %s@%s: ",
				config[CONFIG_XAUTH_USERNAME],
				config[CONFIG_IPSEC_GATEWAY]);
			break;
		}
		fflush(stdout);
		switch (i) {
		case CONFIG_IPSEC_SECRET:
		case CONFIG_XAUTH_PASSWORD:
			s = strdup(getpass(""));
			break;
		case CONFIG_IPSEC_GATEWAY:
		case CONFIG_IPSEC_ID:
		case CONFIG_XAUTH_USERNAME:
			getline(&s, &s_len, stdin);
		}
		if (s != NULL && strlen(s) > 0 && s[strlen(s) - 1] == '\n')
			s[strlen(s) - 1] = 0;
		config[i] = s;
	}

	if (print_config) {
		fprintf(stderr, "vpnc.conf:\n\n");
		for (i = 0; config_names[i].name != NULL; i++) {
			if (config[config_names[i].nm] == NULL)
				continue;
			printf("%s%s\n", config_names[i].name,
				config_names[i].needsArgument ?
					config[config_names[i].nm] : "");
		}
		exit(0);
	}

	if (!config[CONFIG_IPSEC_GATEWAY])
		error(1, 0, "missing IPSec gatway address");
	if (!config[CONFIG_IPSEC_ID])
		error(1, 0, "missing IPSec ID");
	if (!config[CONFIG_IPSEC_SECRET])
		error(1, 0, "missing IPSec secret");
	if (!config[CONFIG_XAUTH_USERNAME])
		error(1, 0, "missing Xauth username");
	if (!config[CONFIG_XAUTH_PASSWORD] && !config[CONFIG_XAUTH_INTERACTIVE])
		error(1, 0, "missing Xauth password");
	if (get_dh_group_ike() == NULL)
		error(1, 0, "IKE DH Group \"%s\" unsupported\n", config[CONFIG_IKE_DH]);
	if (get_dh_group_ipsec(-1) == NULL)
		error(1, 0, "Perfect Forward Secrecy \"%s\" unsupported\n",
			config[CONFIG_IPSEC_PFS]);
	if (get_dh_group_ike()->ike_sa_id == 0)
		error(1, 0, "IKE DH Group must not be nopfs\n");

	return;
}
Exemplo n.º 11
0
/* ------------------------------------------------------ */
static void usage_exit(void) {
    print_usage() ;
    exit(1) ;
}
Exemplo n.º 12
0
int main (int    argc, char **argv)
{
    const char *file_name;
    const char *set_value;
    const char *attr_name;
    int         watch_mode;

    struct sigaction sigact;

    sigemptyset(&sigact.sa_mask);
    sigact.sa_flags     = SA_SIGINFO;
    sigact.sa_restorer  = NULL;
    sigact.sa_sigaction = sig_handler;

    sigaction(SIGUSR1, &sigact, 0);
    sigaction(SIGINT, &sigact, 0);
    sigaction(SIGTERM, &sigact, 0);

    /* Parse command line arguments. */
    file_name  = "./person.dat";
    set_value  = NULL;
    watch_mode = 0;

    while (1)
    {
        int opt;

        opt = getopt (argc, argv, "ws:f:");
        if (opt < 0)
            break;

        switch (opt)
        {
            case 'w':
                watch_mode = 1;
                break;
            case 's':
                set_value = optarg;
                break;
            case 'f':
                file_name = optarg;
                break;
            default:
                print_usage (argv[0]);
                return -1;
        }
    }
    if (!watch_mode && optind >= argc)
    {
        print_usage (argv[0]);
        return -1;
    }
    attr_name = argv[optind];

    /* ###################################################### */

    setup(file_name);

    if(watch_mode) // watch mode 
    {
        int i = 0;

        printf("waiting...\n");
        printf("my pid is %x\n", getpid());

        // add self on watchers list
        for(i = 0; i < NOTIFY_MAX * sizeof(pid_t); i += sizeof(pid_t))
        {
            pid_t* p_pid = (pid_t *)((char *)p_mmap + i);

            if( *p_pid == 0 )
            {
                *p_pid = getpid();
                break;
            }
        }

        if(i/sizeof(pid_t) == NOTIFY_MAX)
        {
            *((pid_t *)p_mmap) = getpid();
        }

        while(1){
            sleep(2);
        }
    }

    else // not watch_mode
    {
        int         off;
        char *      data;

        if( 0 > (off = person_get_offset_of_attr(attr_name)) )
        {
            fprintf(stderr, "invalid attr name \'%s\'\n", attr_name);
            return -1;
        }

        if(set_value != NULL) // set mode
        {
            printf("attr name is %s(%d)\n", attr_name, off);

            if( person_attr_is_integer(attr_name) )
            {
                int * addr = (int *)(((char *)p_mmap) + off);

                *addr = atoi(set_value);
                msync(addr, sizeof(int), MS_SYNC);
            }
            else
            {
                char* addr = ((char *)p_mmap) + off;
                int len = strlen(set_value) * sizeof(char) + 1;

                memcpy(addr, set_value, len);
                msync(addr, sizeof(Person), MS_SYNC);
            }
            send_signal(off);
        }

        else // print mode
        {
            if( person_attr_is_integer(attr_name) )
            {
                int * addr = (int *)(((char *)p_mmap) + off);
                printf("%d\n", *addr);
            }
            else
            {
                char* addr = ((char *)p_mmap) + off;
                printf("%s\n", addr);
            }
        }
        print_person(p_mmap);
    }

    cleanup();
    return 0;
}
Exemplo n.º 13
0
int
main(int argc, char *argv[])
#endif
{
	DYNMEM_KNP_DEFN	*p_dynmem_knp;
	kstat_ctl_t	*kctl;
	KSTAT_INFO_DEF	info_ksp;
	int		val;
	char		**pargs, **cur_pargs;

	/*
	 * grab and parse argument list
	 */
	p_dynmem_knp = dynmem_knp;
	pargs = argv;
	while (*pargs) {
		(void) printf("pargs=%x - %s\n", (uint_t)pargs, *pargs);

		cur_pargs = pargs;
		pargs++;

		if (strcmp(*cur_pargs, "h") == 0) {
			print_usage();
			return (0);
		}

		if (strcmp(*cur_pargs, "wake") == 0) {
			if ((p_dynmem_knp+DIRECTIVE)->newval == NO_VALUE)
				(p_dynmem_knp+DIRECTIVE)->newval = 0;
			(p_dynmem_knp+DIRECTIVE)->newval |= 0x01;
			continue;
		}

		if (strcmp(*cur_pargs, "hys") == 0) {
			if ((p_dynmem_knp+DIRECTIVE)->newval == NO_VALUE)
				(p_dynmem_knp+DIRECTIVE)->newval = 0;
			(p_dynmem_knp+DIRECTIVE)->newval |= 0x02;
			continue;
		}

		if (strcmp (*cur_pargs, "mon") == 0) {
			val = atoi(*pargs);
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			pargs++;
			(p_dynmem_knp+MONITOR)->newval = val;
		}

		if (strcmp (*cur_pargs, "age1") == 0) {
			val = atoi(*pargs);
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			pargs++;
			(p_dynmem_knp+AGECT1)->newval = val;
		}

		if (strcmp(*cur_pargs, "age2") == 0) {
			val = atoi(*pargs);
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			pargs++;
			(p_dynmem_knp+AGECT2)->newval = val;
		}

		if (strcmp(*cur_pargs, "age3") == 0) {
			val = atoi(*pargs);
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			pargs++;
			(p_dynmem_knp+AGECT3)->newval = val;
		}

		if (strcmp (*cur_pargs, "sec1") == 0) {
			val = atoi(*pargs);
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			pargs++;
			if (val == 0)
				break;
			else {
				(p_dynmem_knp+SEC1)->newval = val;
				continue;
			}
		}

		if (strcmp(*cur_pargs, "sec2") == 0) {
			val = atoi(*pargs);
			pargs++;
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			if (val == 0)
				break;
			else {
				(p_dynmem_knp+SEC2)->newval = val;
				continue;
			}
		}

		if (strcmp(*cur_pargs, "sec3") == 0) {
			val = atoi(*pargs);
			pargs++;
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			if (val == 0)
				break;
			else {
				(p_dynmem_knp+SEC3)->newval = val;
				continue;
			}
		}

		if (strcmp(*cur_pargs, "pcnt1") == 0) {
			val = atoi(*pargs);
			pargs++;
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			if (val == 0)
				break;
			else {
				(p_dynmem_knp+PCNT1)->newval = val;
				continue;
			}
		}

		if (strcmp(*cur_pargs, "pcnt2") == 0) {
			val = atoi(*pargs);
			pargs++;
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			if (val == 0)
				break;
			else {
				(p_dynmem_knp+PCNT2)->newval = val;
				continue;
			}
		}

		if (strcmp(*cur_pargs, "hdpcnt") == 0) {
			val = atoi(*pargs);
			pargs++;
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			if (val < 0)
				break;
			else {
				(p_dynmem_knp+HDPCNT)->newval = val;
				continue;
			}
		}

		if (strcmp(*cur_pargs, "list") == 0) {
			val = atoi(*pargs);
			pargs++;
			(void) printf("errno=%x, %s=%x\n", errno, *cur_pargs,
			    val);
			if (val == 0)
				break;
			else {
				(p_dynmem_knp+MAXLIST)->newval = val;
				continue;
			}
		}
	}   /* while(*pargs && cl) */

	/*
	 * open the kstat library
	 */
	kctl = kstat_open();
	if (kctl == NULL) {
		(void) printf("kstat_open() failed\n");
		return (1);
	}

	/*
	 * is the name module about
	 */
	info_ksp.instance = 0;
	info_ksp.ksp = kstat_lookup(kctl, SDBC_KSTAT_MODULE, 0,
	    SDBC_KSTAT_DYNMEM);
	if (info_ksp.ksp == NULL) {
		(void) printf("No module to report\n");
		return (1);
	}

	/*
	 * using the info get a copy of the data
	 */
	if (kstat_read(kctl, info_ksp.ksp, NULL) == -1) {
		(void) printf("Can't read kstat\n");
		return (1);
	}

	/*
	 * print the current data
	 */
	p_dynmem_knp = dynmem_knp;
	while (p_dynmem_knp->named) {
		p_dynmem_knp->knp =
			kstat_data_lookup(info_ksp.ksp, p_dynmem_knp->named);
		if (p_dynmem_knp->knp == NULL) {
			(void) printf("kstat_data_lookup(%s) failed\n",
			    p_dynmem_knp->named);
			return (1);
		} else {
			(void) printf("%s: %x\n", p_dynmem_knp->named,
			    (uint_t)p_dynmem_knp->knp->value.ul);
			p_dynmem_knp++;
		}
	}

	/*
	 * modify the data and write it back
	 */
	p_dynmem_knp = dynmem_knp;
	while (p_dynmem_knp->named) {
		if (p_dynmem_knp->newval != NO_VALUE)
			p_dynmem_knp->knp->value.ul = p_dynmem_knp->newval;
		p_dynmem_knp++;
	}

	if (kstat_write(kctl, info_ksp.ksp, NULL) == -1) {
		(void) printf("kstat_write() failed\n");
		return (1);
	}

	(void) printf("Finished (h for help)\n");
	return (0);
}
Exemplo n.º 14
0
static void parse_opts(int argc, char *argv[])
{
	while (1) {
		static const struct option lopts[] = {
			{ "device",  1, 0, 'D' },
			{ "speed",   1, 0, 's' },
			{ "delay",   1, 0, 'd' },
			{ "bpw",     1, 0, 'b' },
			{ "loop",    0, 0, 'l' },
			{ "cpha",    0, 0, 'H' },
			{ "cpol",    0, 0, 'O' },
			{ "lsb",     0, 0, 'L' },
			{ "cs-high", 0, 0, 'C' },
			{ "3wire",   0, 0, '3' },
			{ "no-cs",   0, 0, 'N' },
			{ "ready",   0, 0, 'R' },
			{ NULL, 0, 0, 0 },
		};
		int c;

		c = getopt_long(argc, argv, "D:s:d:b:lHOLC3NR", lopts, NULL);

		if (c == -1)
			break;

		switch (c) {
		case 'D':
			device = optarg;
			break;
		case 's':
			speed = atoi(optarg);
			break;
		case 'd':
			delay = atoi(optarg);
			break;
		case 'b':
			bits = atoi(optarg);
			break;
		case 'l':
			mode |= SPI_LOOP;
			break;
		case 'H':
			mode |= SPI_CPHA;
			break;
		case 'O':
			mode |= SPI_CPOL;
			break;
		case 'L':
			mode |= SPI_LSB_FIRST;
			break;
		case 'C':
			mode |= SPI_CS_HIGH;
			break;
		case '3':
			mode |= SPI_3WIRE;
			break;
		case 'N':
			mode |= SPI_NO_CS;
			break;
		case 'R':
			mode |= SPI_READY;
			break;
		default:
			print_usage(argv[0]);
			break;
		}
	}
}
Exemplo n.º 15
0
int bam_mpileup(int argc, char *argv[])
{
    int c;
    const char *file_list = NULL;
    char **fn = NULL;
    int nfiles = 0, use_orphan = 0;
    mplp_conf_t mplp;
    memset(&mplp, 0, sizeof(mplp_conf_t));
    mplp.min_baseQ = 13;
    mplp.capQ_thres = 0;
    mplp.max_depth = 250; mplp.max_indel_depth = 250;
    mplp.openQ = 40; mplp.extQ = 20; mplp.tandemQ = 100;
    mplp.min_frac = 0.002; mplp.min_support = 1;
    mplp.flag = MPLP_NO_ORPHAN | MPLP_REALN | MPLP_SMART_OVERLAPS;
    mplp.argc = argc; mplp.argv = argv;
    mplp.rflag_filter = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP;
    mplp.output_fname = NULL;
    mplp.all = 0;
    sam_global_args_init(&mplp.ga);

    static const struct option lopts[] =
    {
        SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0),
        {"rf", required_argument, NULL, 1},   // require flag
        {"ff", required_argument, NULL, 2},   // filter flag
        {"incl-flags", required_argument, NULL, 1},
        {"excl-flags", required_argument, NULL, 2},
        {"output", required_argument, NULL, 3},
        {"open-prob", required_argument, NULL, 4},
        {"illumina1.3+", no_argument, NULL, '6'},
        {"count-orphans", no_argument, NULL, 'A'},
        {"bam-list", required_argument, NULL, 'b'},
        {"no-BAQ", no_argument, NULL, 'B'},
        {"no-baq", no_argument, NULL, 'B'},
        {"adjust-MQ", required_argument, NULL, 'C'},
        {"adjust-mq", required_argument, NULL, 'C'},
        {"max-depth", required_argument, NULL, 'd'},
        {"redo-BAQ", no_argument, NULL, 'E'},
        {"redo-baq", no_argument, NULL, 'E'},
        {"fasta-ref", required_argument, NULL, 'f'},
        {"exclude-RG", required_argument, NULL, 'G'},
        {"exclude-rg", required_argument, NULL, 'G'},
        {"positions", required_argument, NULL, 'l'},
        {"region", required_argument, NULL, 'r'},
        {"ignore-RG", no_argument, NULL, 'R'},
        {"ignore-rg", no_argument, NULL, 'R'},
        {"min-MQ", required_argument, NULL, 'q'},
        {"min-mq", required_argument, NULL, 'q'},
        {"min-BQ", required_argument, NULL, 'Q'},
        {"min-bq", required_argument, NULL, 'Q'},
        {"ignore-overlaps", no_argument, NULL, 'x'},
        {"BCF", no_argument, NULL, 'g'},
        {"bcf", no_argument, NULL, 'g'},
        {"VCF", no_argument, NULL, 'v'},
        {"vcf", no_argument, NULL, 'v'},
        {"output-BP", no_argument, NULL, 'O'},
        {"output-bp", no_argument, NULL, 'O'},
        {"output-MQ", no_argument, NULL, 's'},
        {"output-mq", no_argument, NULL, 's'},
        {"output-tags", required_argument, NULL, 't'},
        {"uncompressed", no_argument, NULL, 'u'},
        {"ext-prob", required_argument, NULL, 'e'},
        {"gap-frac", required_argument, NULL, 'F'},
        {"tandem-qual", required_argument, NULL, 'h'},
        {"skip-indels", no_argument, NULL, 'I'},
        {"max-idepth", required_argument, NULL, 'L'},
        {"min-ireads ", required_argument, NULL, 'm'},
        {"per-sample-mF", no_argument, NULL, 'p'},
        {"per-sample-mf", no_argument, NULL, 'p'},
        {"platforms", required_argument, NULL, 'P'},
        {NULL, 0, NULL, 0}
    };
    while ((c = getopt_long(argc, argv, "Agf:r:l:q:Q:uRC:BDSd:L:b:P:po:e:h:Im:F:EG:6OsVvxt:a",lopts,NULL)) >= 0) {
        switch (c) {
        case 'x': mplp.flag &= ~MPLP_SMART_OVERLAPS; break;
        case  1 :
            mplp.rflag_require = bam_str2flag(optarg);
            if ( mplp.rflag_require<0 ) { fprintf(stderr,"Could not parse --rf %s\n", optarg); return 1; }
            break;
        case  2 :
            mplp.rflag_filter = bam_str2flag(optarg);
            if ( mplp.rflag_filter<0 ) { fprintf(stderr,"Could not parse --ff %s\n", optarg); return 1; }
            break;
        case  3 : mplp.output_fname = optarg; break;
        case  4 : mplp.openQ = atoi(optarg); break;
        case 'f':
            mplp.fai = fai_load(optarg);
            if (mplp.fai == NULL) return 1;
            mplp.fai_fname = optarg;
            break;
        case 'd': mplp.max_depth = atoi(optarg); break;
        case 'r': mplp.reg = strdup(optarg); break;
        case 'l':
                  // In the original version the whole BAM was streamed which is inefficient
                  //  with few BED intervals and big BAMs. Todo: devise a heuristic to determine
                  //  best strategy, that is streaming or jumping.
                  mplp.bed = bed_read(optarg);
                  if (!mplp.bed) { print_error_errno("mpileup", "Could not read file \"%s\"", optarg); return 1; }
                  break;
        case 'P': mplp.pl_list = strdup(optarg); break;
        case 'p': mplp.flag |= MPLP_PER_SAMPLE; break;
        case 'g': mplp.flag |= MPLP_BCF; break;
        case 'v': mplp.flag |= MPLP_BCF | MPLP_VCF; break;
        case 'u': mplp.flag |= MPLP_NO_COMP | MPLP_BCF; break;
        case 'B': mplp.flag &= ~MPLP_REALN; break;
        case 'D': mplp.fmt_flag |= B2B_FMT_DP; fprintf(stderr, "[warning] samtools mpileup option `-D` is functional, but deprecated. Please switch to `-t DP` in future.\n"); break;
        case 'S': mplp.fmt_flag |= B2B_FMT_SP; fprintf(stderr, "[warning] samtools mpileup option `-S` is functional, but deprecated. Please switch to `-t SP` in future.\n"); break;
        case 'V': mplp.fmt_flag |= B2B_FMT_DV; fprintf(stderr, "[warning] samtools mpileup option `-V` is functional, but deprecated. Please switch to `-t DV` in future.\n"); break;
        case 'I': mplp.flag |= MPLP_NO_INDEL; break;
        case 'E': mplp.flag |= MPLP_REDO_BAQ; break;
        case '6': mplp.flag |= MPLP_ILLUMINA13; break;
        case 'R': mplp.flag |= MPLP_IGNORE_RG; break;
        case 's': mplp.flag |= MPLP_PRINT_MAPQ; break;
        case 'O': mplp.flag |= MPLP_PRINT_POS; break;
        case 'C': mplp.capQ_thres = atoi(optarg); break;
        case 'q': mplp.min_mq = atoi(optarg); break;
        case 'Q': mplp.min_baseQ = atoi(optarg); break;
        case 'b': file_list = optarg; break;
        case 'o': {
                char *end;
                long value = strtol(optarg, &end, 10);
                // Distinguish between -o INT and -o FILE (a bit of a hack!)
                if (*end == '\0') mplp.openQ = value;
                else mplp.output_fname = optarg;
            }
            break;
        case 'e': mplp.extQ = atoi(optarg); break;
        case 'h': mplp.tandemQ = atoi(optarg); break;
        case 'A': use_orphan = 1; break;
        case 'F': mplp.min_frac = atof(optarg); break;
        case 'm': mplp.min_support = atoi(optarg); break;
        case 'L': mplp.max_indel_depth = atoi(optarg); break;
        case 'G': {
                FILE *fp_rg;
                char buf[1024];
                mplp.rghash = khash_str2int_init();
                if ((fp_rg = fopen(optarg, "r")) == NULL)
                    fprintf(stderr, "(%s) Fail to open file %s. Continue anyway.\n", __func__, optarg);
                while (!feof(fp_rg) && fscanf(fp_rg, "%s", buf) > 0) // this is not a good style, but forgive me...
                    khash_str2int_inc(mplp.rghash, strdup(buf));
                fclose(fp_rg);
            }
            break;
        case 't': mplp.fmt_flag |= parse_format_flag(optarg); break;
        case 'a': mplp.all++; break;
        default:
            if (parse_sam_global_opt(c, optarg, lopts, &mplp.ga) == 0) break;
            /* else fall-through */
        case '?':
            print_usage(stderr, &mplp);
            return 1;
        }
    }
    if (!mplp.fai && mplp.ga.reference) {
        mplp.fai_fname = mplp.ga.reference;
        mplp.fai = fai_load(mplp.fai_fname);
        if (mplp.fai == NULL) return 1;
    }

    if ( !(mplp.flag&MPLP_REALN) && mplp.flag&MPLP_REDO_BAQ )
    {
        fprintf(stderr,"Error: The -B option cannot be combined with -E\n");
        return 1;
    }
    if (use_orphan) mplp.flag &= ~MPLP_NO_ORPHAN;
    if (argc == 1)
    {
        print_usage(stderr, &mplp);
        return 1;
    }
    int ret;
    if (file_list) {
        if ( read_file_list(file_list,&nfiles,&fn) ) return 1;
        ret = mpileup(&mplp,nfiles,fn);
        for (c=0; c<nfiles; c++) free(fn[c]);
        free(fn);
    }
    else
        ret = mpileup(&mplp, argc - optind, argv + optind);
    if (mplp.rghash) khash_str2int_destroy_free(mplp.rghash);
    free(mplp.reg); free(mplp.pl_list);
    if (mplp.fai) fai_destroy(mplp.fai);
    if (mplp.bed) bed_destroy(mplp.bed);
    return ret;
}
Exemplo n.º 16
0
int
main(int ac, char **av) {
	char *cmd = *av;
	char *cname;
	unsigned long delimiters[MAX_DELIMITER];
	char *localmappers[MAX_LOCALMAPPER];
	char *nameprep_version = NULL;
	int ndelimiters = 0;
	int nlocalmappers = 0;
	char *in_code = NULL;
	char *out_code = NULL;
	char *resconf_file = NULL;
	int no_resconf = 0;
	char *encoding_alias = NULL;
	int flags = DEFAULT_FLAGS;
	FILE *fp;
	idn_result_t r;
	idn_resconf_t resconf1, resconf2;
	idn_converter_t conv;
	int exit_value;

#ifdef HAVE_SETLOCALE
	(void)setlocale(LC_ALL, "");
#endif

	/*
	 * If the command name begins with 'r', reverse mode is assumed.
	 */
	if ((cname = strrchr(cmd, '/')) != NULL)
		cname++;
	else
		cname = cmd;
	if (cname[0] == 'r')
		flags |= FLAG_REVERSE;

	ac--;
	av++;
	while (ac > 0 && **av == '-') {

#define OPT_MATCH(opt) (strcmp(*av, opt) == 0)
#define MUST_HAVE_ARG if (ac < 2) print_usage(cmd)
#define APPEND_LIST(array, size, item, what) \
	if (size >= (sizeof(array) / sizeof(array[0]))) { \
		errormsg("too many " what "\n"); \
		exit(1); \
	} \
	array[size++] = item; \
	ac--; av++

		if (OPT_MATCH("-in") || OPT_MATCH("-i")) {
			MUST_HAVE_ARG;
			in_code = av[1];
			ac--;
			av++;
		} else if (OPT_MATCH("-out") || OPT_MATCH("-o")) {
			MUST_HAVE_ARG;
			out_code = av[1];
			ac--;
			av++;
		} else if (OPT_MATCH("-conf") || OPT_MATCH("-c")) {
			MUST_HAVE_ARG;
			resconf_file = av[1];
			ac--;
			av++;
		} else if (OPT_MATCH("-nameprep") || OPT_MATCH("-n")) {
			MUST_HAVE_ARG;
			nameprep_version = av[1];
			ac--;
			av++;
		} else if (OPT_MATCH("-noconf") || OPT_MATCH("-C")) {
			no_resconf = 1;
		} else if (OPT_MATCH("-reverse") || OPT_MATCH("-r")) {
			flags |= FLAG_REVERSE;
		} else if (OPT_MATCH("-nolocalmap") || OPT_MATCH("-L")) {
			flags &= ~FLAG_LOCALMAP;
		} else if (OPT_MATCH("-nonameprep") || OPT_MATCH("-N")) {
			flags &= ~FLAG_NAMEPREP;
		} else if (OPT_MATCH("-unassigncheck") || OPT_MATCH("-u")) {
			flags |= FLAG_UNASSIGNCHECK;
		} else if (OPT_MATCH("-nounassigncheck") || OPT_MATCH("-U")) {
			flags &= ~FLAG_UNASSIGNCHECK;
		} else if (OPT_MATCH("-nobidicheck") || OPT_MATCH("-B")) {
			flags &= ~FLAG_BIDICHECK;
		} else if (OPT_MATCH("-noasciicheck") || OPT_MATCH("-A")) {
			flags &= ~FLAG_ASCIICHECK;
		} else if (OPT_MATCH("-nolengthcheck")) {
			flags &= ~FLAG_LENGTHCHECK;
		} else if (OPT_MATCH("-noroundtripcheck")) {
			flags &= ~FLAG_ROUNDTRIPCHECK;
		} else if (OPT_MATCH("-whole") || OPT_MATCH("-w")) {
			flags &= ~FLAG_SELECTIVE;
		} else if (OPT_MATCH("-localmap")) {
			MUST_HAVE_ARG;
			APPEND_LIST(localmappers, nlocalmappers, av[1],
				    "local maps");
		} else if (OPT_MATCH("-delimiter")) {
			unsigned long v;
			MUST_HAVE_ARG;
			v = get_ucs(av[1]);
			APPEND_LIST(delimiters, ndelimiters, v,
				    "delimiter maps");
		} else if (OPT_MATCH("-alias") || OPT_MATCH("-a")) {
			MUST_HAVE_ARG;
			encoding_alias = av[1];
			ac--;
			av++;
		} else if (OPT_MATCH("-flush")) {
			flush_every_line = 1;
		} else if (OPT_MATCH("-version") || OPT_MATCH("-v")) {
			print_version();
		} else {
			print_usage(cmd);
		}
#undef OPT_MATCH
#undef MUST_HAVE_ARG
#undef APPEND_LIST

		ac--;
		av++;
	}

	if (ac > 1)
		print_usage(cmd);

	/* Initialize. */
	if ((r = idn_resconf_initialize()) != idn_success) {
		errormsg("error initializing library\n");
		return (1);
	}

	/*
	 * Create resource contexts.
	 * `resconf1' and `resconf2' are almost the same but local and
	 * IDN encodings are reversed.
	 */
	resconf1 = NULL;
	resconf2 = NULL;
	if (idn_resconf_create(&resconf1) != idn_success ||
	    idn_resconf_create(&resconf2) != idn_success) {
		errormsg("error initializing configuration contexts\n");
		return (1);
	}

	/* Load configuration file. */
	if (no_resconf) {
		set_defaults(resconf1);
		set_defaults(resconf2);
	} else {
		load_conf_file(resconf1, resconf_file);
		load_conf_file(resconf2, resconf_file);
	}

	/* Set encoding alias file. */
	if (encoding_alias != NULL)
		set_encoding_alias(encoding_alias);

	/* Set input codeset. */
	if (flags & FLAG_REVERSE) {
		if (in_code == NULL) {
			conv = idn_resconf_getidnconverter(resconf1);
			if (conv == NULL) {
				errormsg("cannot get the IDN encoding.\n"
					 "please specify an appropriate one "
			 		 "with `-in' option.\n");
				exit(1);
			}
			idn_resconf_setlocalconverter(resconf2, conv);
			idn_converter_destroy(conv);
		} else {
			set_idncode(resconf1, in_code);
			set_localcode(resconf2, in_code);
		}
	} else {
		if (in_code == NULL) {
			conv = idn_resconf_getlocalconverter(resconf1);
			if (conv == NULL) {
				errormsg("cannot get the local encoding.\n"
					 "please specify an appropriate one "
			 		 "with `-in' option.\n");
				exit(1);
			}
			idn_resconf_setidnconverter(resconf2, conv);
			idn_converter_destroy(conv);
		} else {
			set_localcode(resconf1, in_code);
			set_idncode(resconf2, in_code);
		}
	}

	/* Set output codeset. */
	if (flags & FLAG_REVERSE) {
		if (out_code == NULL) {
			conv = idn_resconf_getlocalconverter(resconf1);
			if (conv == NULL) {
				errormsg("cannot get the local encoding.\n"
					 "please specify an appropriate one "
			 		 "with `-out' option.\n");
				exit(1);
			}
			idn_resconf_setidnconverter(resconf2, conv);
			idn_converter_destroy(conv);
		} else {
			set_localcode(resconf1, out_code);
			set_idncode(resconf2, out_code);
		}
	} else {
		if (out_code == NULL) {
			conv = idn_resconf_getidnconverter(resconf1);
			if (conv == NULL) {
				errormsg("cannot get the IDN encoding.\n"
					 "please specify an appropriate one "
			 		 "with `-out' option.\n");
				exit(1);
			}
			idn_resconf_setlocalconverter(resconf2, conv);
			idn_converter_destroy(conv);
		} else {
			set_idncode(resconf1, out_code);
			set_localcode(resconf2, out_code);
		}
	}

	/* Set delimiter map(s). */
	if (ndelimiters > 0) {
		set_delimitermapper(resconf1, delimiters, ndelimiters);
		set_delimitermapper(resconf2, delimiters, ndelimiters);
	}

	/* Set local map(s). */
	if (nlocalmappers > 0) {
		set_localmapper(resconf1, localmappers, nlocalmappers);
		set_localmapper(resconf2, localmappers, nlocalmappers);
	}

	/* Set NAMEPREP version. */
	if (nameprep_version != NULL) {
		set_nameprep(resconf1, nameprep_version);
		set_nameprep(resconf2, nameprep_version);
	}

	idn_res_enable(1);

	/* Open input file. */
	if (ac > 0) {
		if ((fp = fopen(av[0], "r")) == NULL) {
			errormsg("cannot open file %s: %s\n",
				 av[0], strerror(errno));
			return (1);
		}
	} else {
		fp = stdin;
	}

	/* Do the conversion. */
	if (flags & FLAG_REVERSE)
		exit_value = decode_file(resconf1, resconf2, fp, flags);
	else
		exit_value = encode_file(resconf1, resconf2, fp, flags);

	idn_resconf_destroy(resconf1);
	idn_resconf_destroy(resconf2);

	return exit_value;
}
int main(int argc, char** argv)
{
		int opt,adc;
		char buffer[MAX_BUFFER]={0};
		int fd;
		int res,c,counter,i,in;
		FILE *fp;
		float v_in,v_out;
		char *param_port = NULL;
		char *param_speed = NULL;
		char *param_imagefile=NULL;
		char *param_mode=NULL;
		char *param_backlight=NULL;
		BITMAPFILEHEADER header;
		BITMAPINFO *headerinfo;
		int headersize,bitmapsize;
		uint8_t *i_bits=NULL,*o_bits=NULL;  // input bits array from original bitmap file, output bit as converted
		int chunksize=300 * 3 ;  //default chunk of bytes to send must be set to max the device can handle without loss of data
		uint8_t b[3] ={0};
		BOOL breakout=FALSE;
		BOOL verbose_mode=FALSE;
		BOOL   has_more_data=TRUE;
		BOOL param_init=FALSE;
		BOOL  show_image=FALSE;
		BOOL show_version=FALSE;
		BOOL test_pattern_full=FALSE;
        BOOL  ADC_read=FALSE;
		printf("-----------------------------------------------------------------------------\n");
		printf("\n");
		printf(" BMP image sender for Nokia LCD Backpack V.0.3 \n");
		printf(" Wiki Docs: http://dangerousprototypes.com/docs/Mathieu:_Another_LCD_backpack\n");
		printf(" http://www.dangerousprototypes.com\n");
		printf("\n");
		printf("-----------------------------------------------------------------------------\n");

		if (argc <= 1)  {
			print_usage(argv[0]);
			exit(-1);
		}

		while ((opt = getopt(argc, argv, "iTtvVas:p:f:d:B:")) != -1) {

			switch (opt) {
				case 'p':  // device   eg. com1 com12 etc
					if ( param_port != NULL){
						printf(" Device/PORT error!\n");
						exit(-1);
					}
					param_port = strdup(optarg);
					break;
				case 'f':
					if (param_imagefile != NULL) {
						printf(" Invalid Parameter after Option -f \n");
						exit(-1);
					}
					param_imagefile = strdup(optarg);
					break;
				case 's':
					if (param_speed != NULL) {
						printf(" Speed should be set: eg  921600 \n");
						exit(-1);
					}
					param_speed = strdup(optarg);
					break;
				case 'B':    // added new: chuck size should be multiply by 3
				    // 1 * 3 up to max of file size or max port speed?
				    if ((atol(optarg) < MAX_BUFFER/3 )&&(atol(optarg)!=0) )
				         chunksize=atol(optarg)*3;
				    else {
				       printf(" Invalid chunk size parameter: using default: %i x 3 = %i Bytes\n",chunksize/3,chunksize);

				    }
				    break;
				case 'd':  // dim the backlight
					if ( param_backlight != NULL){
						printf(" Error: Parameter required to dim the backlight, Range: 0-100\n");
						exit(-1);
					}
					param_backlight = strdup(optarg);
					break;
                case 'i':    //  initialize
				    if (optarg!=NULL) {
				        printf("Invalid option in -i\n");
				    } else {
				        param_init=TRUE;
				    }
					break;
                case 'V':    //talk show some display
				    if (optarg !=NULL) {
				        printf("Invalid option in -V\n");
				    }
				    else {
				        verbose_mode=TRUE;
				    }
					break;
                case 'v':    //
				    if (optarg !=NULL) {
				        printf("Invalid option in -v\n");
				    }
				    else {
				        show_version=TRUE;
				    }
					break;
			    case 'T':    //
				    if (optarg !=NULL) {
				        printf("Invalid option in -T\n");
				    }
				    else {
				        test_pattern_full=TRUE;
				    }
					break;
				 case 'a':    //
				    if (optarg !=NULL) {
				        printf("Invalid option in -a\n");
				    }
				    else {
				        ADC_read=TRUE;
				    }
					break;
				case 'h':
					print_usage(argv[0]);
					exit(-1);
					break;
				default:
					printf(" Invalid argument %c", opt);
					print_usage(argv[0]);
					exit(-1);
					break;
			}
		}

		if (param_port==NULL){
			printf(" No serial port specified\n");
			print_usage(argv[0]);
			exit(-1);
		}

		if (param_speed==NULL)
           param_speed=strdup("921600");  //default is 921600kbps

        fd = serial_open(param_port);
		if (fd < 0) {
			fprintf(stderr, " Error opening serial port\n");
			return -1;
		}

		//setup port and speed
		serial_setup(fd,(speed_t) param_speed);
        if(param_init==TRUE) {
            // i Reset and initialize the LCD.
            buffer[0]='i';
            serial_write( fd, buffer,1 );
		    printf(" LCD Initialized and reset\n");

        }
         if(show_version==TRUE) {
            // i Reset and initialize the LCD.
            buffer[0]='v';
            serial_write( fd, buffer,1 );
            Sleep(1);
			res= serial_read(fd, buffer, sizeof(buffer));
		    printf(" Hardware/Software Version %s\n",buffer);

        }
        if(test_pattern_full==TRUE) {
            // i Reset and initialize the LCD.
            buffer[0]='T';
            serial_write( fd, buffer,1 );
		    printf(" Test Pattern Command Send %c\n",buffer[0]);
		    printf(" Hit any key to end test \n");
		    if (getch()) {
		        buffer[0]=0x00;   //any bytes to end
                serial_write( fd, buffer,1 );
		    }
		    Sleep(1);
            res= serial_read(fd, buffer, sizeof(buffer));
            printf(" Full Screen Test Ends: ");
            if(res==1 && buffer[0]==0x01 ){
                   printf(" Success!\n");
				}
				else {
				    printf(" Reply received: ");
                    for (i=0;i <res;i++)
                      printf(" %02x",(uint8_t) buffer[i]);
                   printf("\n");
				}


        }

        if( ADC_read==TRUE) {
            // LCD backlight voltage reading
            //Raw reading: 0x182 (386)
            //Actual voltage: (386/1024)*3.3volts=1.24volts
            //Scale for resistor divider: Vin = (Vout*(R1+R2))/R2 = (1.24volts*(18K+3.9K))/3.9K = 7.01volts (ideal is 7volts)
            buffer[0]='a';
            serial_write( fd, buffer,1);

		    printf(" ADC read command  Send: %c \n",buffer[0]);
            Sleep(1);
			res= serial_read(fd, buffer, sizeof(buffer));
			//expects 2 bytes at buffer[0] and buffer[1]
			printf(" Voltage Reading : ");
            for (i=0;i< res;i++)
                printf(" %02x",buffer[i]);
            adc = buffer[0] << 8;
            adc += buffer[1];
            v_out=((float)(adc)/1024.0)*3.3;
			v_in = (1.24*(18000.0+3900.0))/3900.0;
			printf("= %2.2f",v_in);
            if((v_in>6.5) && (v_in<7.5)){
                printf(" **PASS**\n");
            }else{
                printf(" FAIL!!!! :(\n");
            }

        }
        if(param_backlight !=NULL) {
          // convert 0-100 to bytes, 0x00 - 0xff
            buffer[0]='d';
            char dx=(atol(param_backlight)*255)/100;
            buffer[1]=dx;
            serial_write( fd, buffer,2 );

            printf(" Dimlight Command  Send: %c %c\n",buffer[0],buffer[1]);
            Sleep(1);
            res= serial_read(fd, buffer, sizeof(buffer));
            printf(" Dim command reply: ");
            if(res==1 && buffer[0]==0x01 ){
               printf(" Success!\n");
			}
			else {
			   printf(" Reply received: ");
               for (i=0;i <res;i++)
                  printf(" %02x",(uint8_t) buffer[i]);
               printf("\n");
			}

        }
		if (param_imagefile !=NULL) {
		    show_image=TRUE;
		}
		if (show_image==TRUE) {
		 //checks is needed to make sure this is a valid bmp file
			//open the Imagefile  file
			   if ((fp = fopen(param_imagefile, "rb")) == NULL) {
				   printf(" Cannot open image file: %s\n",param_imagefile);
				   exit(-1);
			   }
			    if (fread(&header, sizeof(BITMAPFILEHEADER), 1, fp) < 1){
                    printf(" Invalid Image file.. requires BMP file \n");
                    fclose(fp);
                    exit(-1);
               }
                if (header.bfType != BF_TYPE) {    //BM as signature
                     printf("File: %s is not a valid bitmap file! \n ",param_imagefile);
                     fclose(fp);
                     exit(-1);
               }
               headersize = header.bfOffBits - sizeof(BITMAPFILEHEADER);
            //   printf("Header.bfoffbits: %lu  Sizeof Bitmapfilehader: %i Headersize is : %i\n",header.bfOffBits,sizeof(BITMAPFILEHEADER),headersize);
               if ((headerinfo = (BITMAPINFO *)malloc(headersize)) == NULL){
                    printf("Error allocating memory\n");
                    fclose(fp);
                    exit(-1);
               }
               //error in debian here-> might be because I am using 64 bit
               if ((res=fread(headerinfo, 1, headersize, fp)) < headersize){
                    printf("Error: Headersize Error %i < %i\n",res,headersize );
                    fclose(fp);
                    exit(-1);
               }
               printf(" Header size is %lu\n",headerinfo->bmiHeader.biSize);
               printf(" Image size is  %lupx x %lupx\n",headerinfo->bmiHeader.biWidth,headerinfo->bmiHeader.biHeight);
               printf(" Number of colour planes is %d\n",headerinfo->bmiHeader.biPlanes);
               printf(" Bits per pixel is %d\n",headerinfo->bmiHeader.biBitCount);
             //  printf(" Compression type is %lu\n",headerinfo->bmiHeader.biCompression);
             //  printf(" Image size is %lu\n",headerinfo->bmiHeader.biSizeImage);
             //  printf(" Number of colours is %lu\n",headerinfo->bmiHeader.biClrUsed);
              // printf(" Number of required colours is %lu\n",headerinfo->bmiHeader.biClrImportant);


               if ((bitmapsize = headerinfo->bmiHeader.biSizeImage) == 0){
                    bitmapsize = (headerinfo->bmiHeader.biWidth * headerinfo->bmiHeader.biBitCount + 7) / 8 * abs(headerinfo->bmiHeader.biHeight);
                }
               if ((i_bits = malloc(bitmapsize)) == NULL){  //allocate enough memory
					printf(" Error: Cannot allocate enough memory \n");
					fclose(fp);
					exit(-1);
                }
                if ((o_bits = malloc(bitmapsize/2+1)) == NULL){  //allocate enough memory
					printf(" Error: Cannot allocate enough memory \n");
					fclose(fp);
					exit(-1);
                }
               for (i=0;i < bitmapsize/2+1;i++)
                     o_bits[i]=0x00;    // make sure padding is there

				fclose(fp);
				fp = fopen(param_imagefile, "rb");
				printf(" Offset to image data is %lu bytes\n",header.bfOffBits);
				//close and reopen bmp file


				//send the command 	//Send 'p' or 'P' send page of image data.
				printf(" Setting image mode \n");
				buffer[0]='P';
				serial_write( fd, buffer,1 );

				fseek(fp,header.bfOffBits,SEEK_SET); //and disable this if above fgets is enabled

				if ((res=fread(i_bits,sizeof(unsigned char),bitmapsize,fp)) != bitmapsize) {
					 printf(" Header information error: image data size inconsistent. %i %i\n",res,bitmapsize);
					 fclose(fp);
					 exit(-1);

				}
				printf(" Opening Port on %s at %sbps, using image file %s chunksize = %i X %i \n", param_port, param_speed,param_imagefile,chunksize/3,3);
				printf(" Ready to convert %d bit into 12 bit image data.. \n",headerinfo->bmiHeader.biBitCount);
				printf(" Press any key when ready...\n");
				getch();
				switch (headerinfo->bmiHeader.biBitCount) {
                    case 1:
                        printf(" 1 bit (black and white) not yet done");
                        fclose(fp);
                        exit(-1);
                        break;
                    case 4:
                        printf(" 4-bit (16 colors) not yet done");
                          fclose(fp);
                        exit(-1);
                        break;
                    case 8:
                        printf(" 8 bit (256 colors) not yet done");
                        fclose(fp);
                        exit(-1);
                        break;
                    case 16:
                        printf(" 16-bit not yet done");
                        fclose(fp);
                        exit(-1);
                        break;
                    case 24:  //convert i_bits to 12bits into o_bits

                        counter=0; // counter for original bitmap data
                        in=0;   //counter for putting bytes in o_bits
                        breakout=FALSE;
                        while(1) {

                                //the LCD needs 12bit color, this is 24bit
                                //we need to discard the lower 4 bits of each byte
                                //and pack six half bytes into 3 bytes to send the LCD
                                //if we only have one pixel to process (3bytes) instead of 2, then the last should be 0
                                //need to do checks for end of data, make this more effecient
                                //BMP byte order of BGR...
                               //rrrrgggg	bbbbrrrr	ggggbbbb	...	ggggbbbb

                                //grab six bytes
                                for (i=0;i < 6;i++){

                                   if (counter > bitmapsize-1){
                                       buffer[i]=0x00; //pad remaining then exit the loop
                                       breakout=TRUE;
                                   } else {


                                   buffer[i]=i_bits[counter++];
                                   }
                                   if(verbose_mode==TRUE)
                                      printf(" %02x",(unsigned char) buffer[i]);

                                }

                                // convert to 4 bits each RGB
                                if(verbose_mode==TRUE)
                                    printf("--->");

                                //R G
                                b[0]=((buffer[2]&0xf0)|((buffer[1]>>4)&0x0f));
                                //B R2
                                b[1]=(buffer[0]&0xf0)|((buffer[5]>>4)&0x0f);
                                //G2B2
                                b[2]=(buffer[4]&0xf0)|((buffer[3]>>4)&0x0f);
                               // put in o_bits
                                o_bits[in++] =b[0];
                                o_bits[in++] =b[1];
                                o_bits[in++] =b[2];
                                if(verbose_mode==TRUE)
                                   printf("%02X %02X %02X \n",b[0],b[1],b[2]);
                                if (breakout==TRUE) {
                                    //try to clean
                                    if ((b[0]==0x00)&& (b[1] == 0x00)&& (b[2]==0x00)) {
                                       //remove excess padding
                                       in-=3;
                                       break;
                                    }
                                }
                            }

                        break;
                    case 32:
                         printf(" 32-bit not yet done");
                        fclose(fp);
                        exit(-1);
                        break;

                    default:
                        printf(" Unrecognize Bit count \n");
                        fclose(fp);
                        exit(-1);
				}

				printf(" sending image data..\n ");
				has_more_data=TRUE;
				i=0;
				while(i< in){

					for (c=0; c < chunksize; c++) {
						if (i+c < in){
							buffer[c]= o_bits[i+c];
						}
						else {
			            // no more data
						has_more_data=FALSE;
						break;   //breakout of for loop, c has the last chunk
						}
					}
					if(verbose_mode==TRUE) {
						for(counter=0;counter < c;counter++) {
							printf(" [%i] %02X \n", i+counter, (uint8_t) buffer[counter]);
					//        printf(" %02X \n",  (uint8_t) buffer[counter]);
						}

					}
					serial_write( fd, buffer,c);
					i=i+c;
					if(has_more_data==FALSE)
					   break;
				}
				printf(" Total Bytes Sent: %i\n",i);
				Sleep(1);
				res= serial_read(fd, buffer, sizeof(buffer));

				if(res==1 && buffer[0]==0x01 ){
                   printf(" Success!\n");
				}
				else {
				    printf(" Reply received: ");
                    for (i=0;i <res;i++)
                      printf(" %02x",(uint8_t) buffer[i]);
                   printf("\n");
				}

                printf(" Done! :-)\n\n");
				//close lcd
				fclose(fp);
		}
		serial_close(fd);
		FREE(param_port);
		FREE(param_speed);
		FREE(param_imagefile);
		FREE(param_mode);
		return 0;
 }  //end main()
Exemplo n.º 18
0
int main(int argc, char *argv[])
{
	LINX *linx;
	LINX_SPID server_spid;
	union LINX_SIGNAL *sig;
	pthread_t server_th;
	int c;
	int loop_cnt = LOOP_CNT;
	int use_linx_api = LINX_SOCKET;
	size_t msg_size = BURST_SIZE;
	unsigned long burst_cnt = BURST_CNT;
	size_t start_msg_size = START_MSG_SIZE;
	size_t end_msg_size = END_MSG_SIZE;
	unsigned long throughput_instances = THROUGHPUT_INSTANCES;
	int iterations = ITERATIONS;
	LINX_SIGSELECT any_sig[] = { 0 };

	char *path = NULL;
	char *server_name = NULL;
	int run_attach_test = 0;
	int run_com_test = 0;
	int kill_server = 0;
	int all = 0;
	int use_pthreads = 0;

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

	while ((c = getopt(argc, argv, "S?p:ac:n:m:b:i:s:e:Alt:qP")) != -1) {
		switch (c) {
		case 'S':
			/* Start server */
			server_name = (optarg == NULL ? SERVER_NAME : optarg);
			break;

		case 'P':
			/* Start server as posix thread */
			server_name = SERVER_NAME;
			use_pthreads = 1;
			break;

		case 'p':
			/* Hunt path */
			path = optarg;
			break;

		case 'a':
			/* Run attach test */
			run_attach_test = 1;
			break;

		case 'c':
			/* Connection test */
			run_com_test = atoi(optarg);
			break;

		case 'n':
			/* Loop count */
			loop_cnt = atoi(optarg);
			break;

		case 'm':
			/* Message size */
			msg_size = atol(optarg);
			break;

		case 'b':
			/* Burst count */
			burst_cnt = atol(optarg);
			break;

		case 'i':
			/* Iterations */
			iterations = atoi(optarg);
			break;

		case 's':
			/* Start message size */
			start_msg_size = atol(optarg);
			break;

		case 'e':
			/* End message size */
			end_msg_size = atol(optarg);
			break;

		case 'A':
			/* Run all tests */
			all = 1;
			break;

		case 'l':
			/* Use linx api in tests */
			use_linx_api = LINX_API;
			break;

		case 't':
			/* Number of instances in throughput */
			throughput_instances = atoi(optarg);
			break;

		case 'q':
			/* Quit the server */
			kill_server = 1;
			break;
		default:
			print_usage(argv[0]);
			return 0;
		}
	}

	if(use_pthreads) {
		kill_server = 1;
		if (pthread_create(&server_th, NULL, server,
				   (void *)server_name)) {
			fprintf(stderr, "pthread_create(): %d\n", errno);
			exit(errno);
		}
	} else if (server_name != NULL) {
		(void)server(server_name);
		return 0;
	}

	/* Path to server */
	path = path && *path ? path : CS_PATH SERVER_NAME;

	/* Hunt for server */
	linx = linx_open(CLIENT_NAME, 0, NULL);
	linx_hunt(linx, path, NULL);
	linx_receive_w_tmo(linx, &sig, 1000, any_sig);
	if (sig == NULL) {
		printf("Hunt failed. No server found at path '%s'.\n"
		       "Is the server started and path ok? "
		       "(Server started with -S option)\n", path);
		linx_close(linx);
		return 1;
	}
	if (sig->sigNo != LINX_OS_HUNT_SIG) {
		ERR("Failed to hunt for '%s'", path);
		linx_free_buf(linx, &sig);
		linx_close(linx);
		return 1;
	}
	server_spid = linx_sender(linx, &sig);
	linx_free_buf(linx, &sig);

	/* Attach to server */
	sig = linx_alloc(linx, sizeof(LINX_SIGSELECT), ATTACH_SERV_SIG);
	linx_attach(linx, &sig, server_spid);

	if (run_attach_test) {
		attach_test(linx, path, loop_cnt, server_spid, use_linx_api,
			    use_pthreads);
	}

	switch (run_com_test) {
	case 1:
		/* Start com test 1 */
		linx_bmark_latency(linx, path, loop_cnt, msg_size, msg_size,
				   ONE_ITERATION, server_spid, use_linx_api,
				   use_pthreads);
		break;
	case 2:
		/* Start com test 2 */
		linx_bmark_burst(linx, path, loop_cnt, msg_size,
				 msg_size, ONE_ITERATION,
				 burst_cnt, server_spid, use_linx_api,
				 use_pthreads);
		break;
	case 3:
		/* Start com test 3 */
		linx_bmark_latency(linx, path, loop_cnt, start_msg_size,
				   end_msg_size, iterations, server_spid,
				   use_linx_api, use_pthreads);
		break;
	case 4:
		/* Start com test 4 */
		linx_bmark_burst(linx, path, loop_cnt, start_msg_size,
				 end_msg_size, iterations, burst_cnt,
				 server_spid, use_linx_api, use_pthreads);
		break;
	case 5:
		/* Start com test 5 */
		linx_bmark_throughput(path, loop_cnt, msg_size,
				      server_spid, use_linx_api,
				      throughput_instances, use_pthreads);
		break;
	default:
		break;
	}

	if (all) {
		/* All tests  */
		attach_test(linx, path, loop_cnt, server_spid, use_linx_api,
			    use_pthreads);
		linx_bmark_latency(linx, path, loop_cnt, msg_size, msg_size,
				   ONE_ITERATION, server_spid, use_linx_api,
				   use_pthreads);
		linx_bmark_burst(linx, path, loop_cnt, msg_size, msg_size,
				 ONE_ITERATION, burst_cnt,
				 server_spid, use_linx_api, use_pthreads);
		linx_bmark_latency(linx, path, loop_cnt, start_msg_size,
				   end_msg_size, iterations,
				   server_spid, use_linx_api, use_pthreads);
		linx_bmark_burst(linx, path, loop_cnt, start_msg_size,
				 end_msg_size, iterations, burst_cnt,
				 server_spid, use_linx_api, use_pthreads);
		linx_bmark_throughput(path, loop_cnt, msg_size,
				      server_spid, use_linx_api,
				      throughput_instances, use_pthreads);
	}

	if (kill_server) {
		/* If no test argument specified, let server close */
		sig = linx_alloc(linx, sizeof(LINX_SIGSELECT), CONN_TERM);
		linx_send(linx, &sig, server_spid);
		printf("Waiting for attach from server.\n");
		linx_receive(linx, &sig, any_sig);
		if (sig == LINX_NIL) {
			ERR("No attach signal was received from the server.");
		}
		if (sig->sigNo != ATTACH_SERV_SIG) {
			ERR("Wrong signal received while waiting for "
			    "attach signal from server.");
		}
		linx_free_buf(linx, &sig);

		/* Close client spid */
		linx_close(linx);
	}

	if(use_pthreads)
		pthread_join(server_th, NULL);
	
	return 0;
}
Exemplo n.º 19
0
static void process_command_line(int argc, char *argv[]) {
  cmdline_parser_t parser;
  cmdline_elem_t elem;

  input_filename = NULL;
  dump_filename = NULL;
  dump_requested = false;

  init_cmdline_parser(&parser, options, NUM_OPTIONS, argv, argc);

  for (;;) {
    cmdline_parse_element(&parser, &elem);
    switch (elem.status) {
    case cmdline_done:
      goto done;

    case cmdline_argument:
      if (input_filename == NULL) {
	input_filename = elem.arg;
      } else {
	fprintf(stderr, "%s: can't have several input files\n", parser.command_name);
	goto bad_usage;
      }
      break;

    case cmdline_option:
      switch (elem.key) {
      case version_flag:
	print_version();
	goto quick_exit;

      case help_flag:
	print_help(parser.command_name);
	goto quick_exit;

      case set_dump:
	dump_requested = true;
	if (elem.s_value != NULL) {
	  if (dump_filename == NULL) {
	    dump_filename = elem.s_value;
	  } else {
	    fprintf(stderr, "%s: can't have several dump files\n", parser.command_name);
	    goto bad_usage;
	  }
	}
	break;

      default:
	assert(false);
	break;
      }
      break;

    case cmdline_error:
      cmdline_print_error(&parser, &elem);
      goto bad_usage;
    }
  }

 quick_exit:
  exit(YICES_EXIT_SUCCESS);

 bad_usage:
  print_usage(parser.command_name);
  exit(YICES_EXIT_USAGE);

 done:
  return;
}
Exemplo n.º 20
0
int main (int argc, char **argv)
{

  args_t args;
  LTE_DL_FRAME_PARMS frame_parms0;
  LTE_DL_FRAME_PARMS *frame_parms=&frame_parms;
  char sdu0[16],sdu1[64],sdu2[1024],sdu3[1024],sdu4[1024];
  unsigned short sdu_len0,sdu_len1,sdu_len2,sdu_len3,sdu_len4;
  char ulsch_buffer[1024],dlsch_buffer[1024];
  u8 lcid;
  u8 payload_offset;
  int i,comp;

  logInit();

  NB_UE_INST  = 1;
  NB_eNB_INST = 1;
  NB_INST=2;

  // Parse arguments
  if(parse_args(argc, argv, &args) > 0) {
    print_usage(argv[0]);
    exit(1);
  }

  set_taus_seed(0);
  logInit();
  set_glog(LOG_TRACE, 1);

  for (comp = PHY; comp < MAX_LOG_COMPONENTS ; comp++)
    set_comp_log(comp,
                 LOG_TRACE,
                 LOG_NONE,
                 1);

  /*
  set_log(OMG,  LOG_INFO, 20);
   set_log(EMU,  LOG_INFO, 10);
   set_log(OCG,  LOG_INFO, 1);
   set_log(MAC,  LOG_TRACE, 1);
   set_log(RLC,  LOG_TRACE, 1);
   set_log(PHY,  LOG_DEBUG, 1);
   set_log(PDCP, LOG_TRACE, 1);
   set_log(RRC,  LOG_TRACE, 1);
  */
  mac_xface = (MAC_xface *)malloc(sizeof(MAC_xface));
  init_lte_vars (&frame_parms, 0, 1, 0, 0, 25, 0, 0, 1, 1);
  l2_init(frame_parms);

  // Generate eNB SI
  if (args.input_sib == 0) {
    openair_rrc_lite_eNB_init(0);
  } else {
    printf("Got SI from files (%d,%d,%d,%d,%d)\n",args.input_sib,args.input1_sdu_flag,args.input2_sdu_flag);
  }

  openair_rrc_on(0,0);
  openair_rrc_lite_ue_init(0,0);

  switch (args.SDUsource) {
  case eNB_RRC:
    if (args.RRCmessage == RRCSIB1) {
      if (args.input1_sdu_flag == 1) {
        for (i=0; i<args.input1_sdu_len; i++)
          printf("%02x",args.input1_sdu[i]);

        printf("\n");
        ue_decode_si(0,142,0,args.input1_sdu,args.input1_sdu_len);
      } else {
        printf("\n\nSIB1\n\n");

        for (i=0; i<eNB_rrc_inst[0].sizeof_SIB1; i++)
          printf("%02x",eNB_rrc_inst[0].SIB1[i]);

        printf("\n");
      }
    } else if (args.RRCmessage == RRCSIB2_3) {
      if (args.input1_sdu_flag == 1) {
        for (i=0; i<args.input2_sdu_len; i++)
          printf("%02x",args.input2_sdu[i]);

        printf("\n");
        ue_decode_si(0,149,0,args.input1_sdu,args.input1_sdu_len);
      } else {
        printf("\n\nSIB2_3\n\n");

        for (i=0; i<eNB_rrc_inst[0].sizeof_SIB23; i++)
          printf("%02x",eNB_rrc_inst[0].SIB23[i]);

        printf("\n");
      }
    } else if ((args.input1_sdu_flag == 1)&&
               ((args.RRCmessage == RRCConnectionSetup) ||
                (args.RRCmessage == RRCConnectionReconfiguration))) {
      sdu_len0 = attach_ue0(sdu0);
      ue_send_sdu(0,143,args.input1_sdu,args.input1_sdu_len,0);

      if (args.RRCmessage == RRCConnectionReconfiguration)
        ue_send_sdu(0,144,args.input2_sdu,args.input2_sdu_len,0);
    } else {
      switch (args.RRCmessage) {

      case RRCConnectionSetup:
        printf("Doing eNB RRCConnectionSetup\n");
        sdu_len0 = attach_ue0(sdu0);
        sdu_len1 = attach_ue1(sdu1);
        lcid = 0;
        payload_offset = generate_dlsch_header(dlsch_buffer,
                                               1,              //num_sdus
                                               &sdu_len1,      //
                                               &lcid,          // sdu_lcid
                                               255,                                   // no drx
                                               0,                                   // no timing advance
                                               sdu0,        // contention res id
                                               0,0);
        memcpy(&dlsch_buffer[payload_offset],sdu1,sdu_len1);
        printf("\nRRCConnectionSetup (DLSCH input / MAC output)\n\n");

        for (i=0; i<sdu_len1+payload_offset; i++)
          printf("%02x ",(unsigned char)sdu1[i]);

        printf("\n");

        break;

      case RRCConnectionReconfiguration:
        printf("Doing eNB RRCConnectionReconfiguration\n");
        sdu_len0 = attach_ue0(sdu0);
        sdu_len1 = attach_ue1(sdu1);
        sdu_len2 = attach_ue2(sdu1,sdu_len1,sdu2);
        sdu_len3 = attach_ue3(sdu2,sdu_len2,sdu3);

        lcid=1;
        payload_offset = generate_dlsch_header(dlsch_buffer,
                                               // offset = generate_dlsch_header((unsigned char*)eNB_mac_inst[0].DLSCH_pdu[0][0].payload[0],
                                               1,              //num_sdus
                                               &sdu_len3,  //
                                               &lcid,
                                               255,                                   // no drx
                                               1,      // timing advance
                                               NULL,                                  // contention res idk
                                               0,0);
        memcpy(&dlsch_buffer[payload_offset],sdu3,sdu_len3);
        printf("\nRRCConnectionReconfiguration (DLSCH input / MAC output)\n\n");

        for (i=0; i<sdu_len3+payload_offset; i++)
          printf("%02x ",(unsigned char)dlsch_buffer[i]);

        printf("\n");

        break;

      default:
        printf("Unknown eNB_RRC SDU (%d), exiting\n",args.RRCmessage);
        break;
      }

      break;
    }

    break;

  case eNB_MAC:
    sdu_len0 = attach_ue0(sdu0);
    ue_send_sdu(0,143,args.input1_sdu,args.input1_sdu_len,0);
    break;

  case UE_RRC:
    switch (args.RRCmessage) {

    case RRCConnectionRequest:

      sdu_len0 = attach_ue0(sdu0);
      printf("\n\nRRCConnectionRequest\n\n");

      for (i=0; i<sdu_len0; i++)
        printf("%02x ",(unsigned char)sdu0[i]);

      printf("\n");

      break;

    case RRCConnectionSetupComplete:

      sdu_len0=attach_ue0(sdu0);
      sdu_len1 = attach_ue1(sdu1);
      sdu_len2 = attach_ue2(sdu1,sdu_len1,sdu2);


      lcid=1;
      printf("Got sdu of length %d\n",sdu_len2);
      payload_offset = generate_ulsch_header((u8*)ulsch_buffer,  // mac header
                                             1,      // num sdus
                                             0,            // short pading
                                             &sdu_len2,  // sdu length
                                             &lcid,    // sdu lcid
                                             NULL,  // power headroom
                                             NULL,  // crnti
                                             NULL,  // truncated bsr
                                             NULL, // short bsr
                                             NULL, // long_bsr
                                             0);
      printf("Got MAC header of length %d\n",payload_offset);
      memcpy(&ulsch_buffer[payload_offset],sdu2,sdu_len2);

      printf("\n\nRRCConnectionSetupComplete (ULSCH input / MAC output)\n\n");

      for (i=0; i<sdu_len2+payload_offset; i++)
        printf("%02x ",(unsigned char)ulsch_buffer[i]);

      printf("\n");
      break;

    case RRCConnectionReconfigurationComplete:

      sdu_len0=attach_ue0(sdu0);
      sdu_len1=attach_ue1(sdu1);
      sdu_len2 = attach_ue2(sdu1,sdu_len1,sdu2);
      sdu_len3 = attach_ue3(sdu2,sdu_len2,sdu3);
      sdu_len4 = attach_ue4(sdu3,sdu_len3,sdu4);

      lcid=1;
      printf("Got sdu of length %d\n",sdu_len4);
      payload_offset = generate_ulsch_header((u8*)ulsch_buffer,  // mac header
                                             1,      // num sdus
                                             0,            // short pading
                                             &sdu_len4,  // sdu length
                                             &lcid,    // sdu lcid
                                             NULL,  // power headroom
                                             NULL,  // crnti
                                             NULL,  // truncated bsr
                                             NULL, // short bsr
                                             NULL, // long_bsr
                                             0);
      printf("Got MAC header of length %d\n",payload_offset);
      memcpy(&ulsch_buffer[payload_offset],sdu4,sdu_len4);

      printf("\n\nRRCConnectionReconfigurationComplete (ULSCH input / MAC output)\n\n");

      for (i=0; i<sdu_len4+payload_offset; i++)
        printf("%02x ",(unsigned char)ulsch_buffer[i]);

      printf("\n");

      break;

    default:
      printf("Unknown UE_RRC SDU (%d), exiting\n",args.RRCmessage);
      break;
    }

    break;
  }


  free(mac_xface);

  return(0);
}
Exemplo n.º 21
0
int main(int argc, char **argv)
{
  signal(SIGINT, do_cleanup);

  for(;;)
    {
      int options_index = 0;
      int c = getopt_long(argc, argv, ":", long_options, &options_index);

      if(c == -1)
        break;

      if(c == 1 || c == 2)
        {
          if(optarg == NULL)
            {
              print_usage(argv[0]);
            }

          if(strncmp("true", optarg, 5) == 0)
            {
              if(c == 1)
                bus_pirate_flag = 0;
              if(c == 2)
                termiobaud = 1;
            }
        }
    }

  if (optind + 1 != argc) {
    print_usage(argv[0]);
  }

  device_file = malloc(strlen(argv[optind])+1);
  memcpy(device_file, argv[optind], strlen(argv[optind])+1);

  //Initialization complete!

  devicefd = open(device_file, O_RDWR | O_NOCTTY);

  if(devicefd == -1)
    {
      fprintf(stderr, "E: Cannot open device %s\n", device_file);
      exit(1);
    }
  printf("Device file: %s\n", device_file);

  if(termiobaud)
    {
      struct termios options;
      speed_t speed = B9600;

      if(bus_pirate_flag)
        {
          speed = B115200;
        }

      tcgetattr(devicefd, &options);

      //8N1
      options.c_cflag &= ~PARENB;
      options.c_cflag &= ~CSTOPB;
      options.c_cflag &= ~CSIZE;
      options.c_cflag |= CS8;

      cfsetispeed(&options, speed);
      cfsetospeed(&options, speed);
      tcsetattr(devicefd, TCSAFLUSH, &options);
    }

  if(bus_pirate_flag)
    {
      bp_enter_uart_binary(devicefd);
      bp_uart_set_power(devicefd, 1);
      fprintf(stderr, "Entered BP binary mode.\n");
    }

  struct gt511c1r fpr;
  gt511c1r_init(&fpr, devicefd, do_usrt);
  gt511c1r_open(&fpr);

  int userinput = 0;
  int id = 0;

  for(;;)
    {
      printf("Input number\n"
             "0 - Exit program\n"
             "1 - Clear fingerprint memory\n"
             "2 - Enroll finger\n"
             "3 - Identify finger\n"
             "select>");
      scanf("%d", &userinput);

      switch(userinput)
        {
        case 0:
          do_cleanup();
        case 1:
          gt511c1r_delete_all_fingerprint(&fpr);
          break;
        case 2:
          printf("Input slot number: ");
          scanf("%d", &userinput);
          if(userinput < 0 || userinput > 19)
            {
              printf("Wrong number!\n");
              break;
            }
          gt511c1r_enroll_fingerprint(&fpr, userinput);
          break;
        case 3:
          printf("Identifying!\n");
          id = gt511c1r_identify_fingerprint(&fpr);
          printf("Identified as fingerprint #%d\n", id);
          break;
        default:
          printf("Not in range!\n");
        }
    }

  //TODO: Display interactive console.

  sleep(1);
  do_cleanup();
  return 0;
}
Exemplo n.º 22
0
int main(int argc, const char** argv)
{
    argv0 = argv[0];


    bool print_stats = false;


    U.start();

    // Set up smsh related error codes
    if (! (w_error_t::insert(
                "ss_m shell",
                smsh_error_list, SSH_MAX_ERROR - SSH_MIN_ERROR - 1))) {
        abort();
    }


    /*
     * The following section of code sets up all the various options
     * for the program.  The following steps are performed:
        - determine the name of the program
        - setup an option group for the program
        - initialize the ssm options
        - scan default option configuration files ($HOME/.shoreconfig .shoreconfig)
        - process any options found on the command line
        - use getopt() to process smsh specific flags on the command line
        - check that all required options are set before initializing sm
     */         

    // set prog_name to the file name of the program
    const char* prog_name = strrchr(argv[0], '/');
    if (prog_name == NULL) {
            prog_name = argv[0];
    } else {
            prog_name += 1; /* skip the '/' */
            if (prog_name[0] == '\0')  {
                    prog_name = argv[0];
            }
    }

    /*
     * Set up and option group (list of options) for use by
     * all layers of the system.  Level "smsh" indicates
     * that the program is a a part to the smsh test suite.
     * Level "server" indicates
     * the type of program (the smsh server program).  The third
     * level is the program name itself.
     */
    option_group_t options(3);
    W_COERCE(options.add_class_level("smsh"));
    W_COERCE(options.add_class_level("server"));
    W_COERCE(options.add_class_level(prog_name));

    /*
     * Set up and smsh option for the name of the tcl library directory
     * and the name of the .smshrc file.
     */
    option_t* smsh_libdir;
    option_t* smsh_smshrc;
    W_COERCE(options.add_option("smsh_libdir", "directory name", NULL,
                "directory for smsh tcl libraries",
                true, option_t::set_value_charstr, smsh_libdir));
    W_COERCE(options.add_option("smsh_smshrc", "rc file name", ".smshrc",
                "full path name of the .smshrc file",
                false, option_t::set_value_charstr, smsh_smshrc));

    // have the sm add its options to the group
    W_COERCE(ss_m::setup_options(&options));


    /*
     * Scan the default configuration files: $HOME/.shoreconfig, .shoreconfig.  Note
     * That OS errors are ignored since it is not an error
     * for this file to not be found.
     */
    rc_t        rc;
    {
    char                opt_file[ss_m::max_devname+1];
    for(int file_num = 0; file_num < 2 && !rc.is_error(); file_num++) {
        // scan default option files
        w_ostrstream        err_stream;
        const char*        config = ".shoreconfig";
        if (file_num == 0) {
            if (!getenv("HOME")) {
                // ignore it ...
                // cerr << "Error: environment variable $HOME is not set" << endl;
                // rc = RC(SSH_FAILURE);
                break;
            }
            if (sizeof(opt_file) <= strlen(getenv("HOME")) + strlen("/") + strlen(config) + 1) {
                cerr << "Error: environment variable $HOME is too long" << endl;
                rc = RC(SSH_FAILURE);
                break;
            }
            strcpy(opt_file, getenv("HOME"));
            strcat(opt_file, "/");
            strcat(opt_file, config);
        } else {
            w_assert3(file_num == 1);
            strcpy(opt_file, "./");
            strcat(opt_file, config);
        }
        {
            option_file_scan_t opt_scan(opt_file, &options);
            rc = opt_scan.scan(true, err_stream);
            err_stream << ends;
            if (rc.is_error()) {
                // ignore OS error messages
                if (rc.err_num() == fcOS) {
                    rc = RCOK;
                } else {
                    // this error message is kind of gross but is
                    // sufficient for now
                    cerr << "Error in reading option file: " << opt_file << endl;
                    //cerr << "\t" << w_error_t::error_string(rc.err_num()) << endl;
                    cerr << "\t" << err_stream.c_str() << endl;
                }
            }
        }
    }
    }

    /* 
     * Assuming there has been no error so far, the command line
     * is processed for any options in the option group "options".
     */
    if (!rc.is_error()) {
        // parse command line
        w_ostrstream        err_stream;
        rc = options.parse_command_line(argv, argc, 2, &err_stream);
        err_stream << ends;
        if (rc.is_error()) {
            cerr << "Error on command line " << endl;
            cerr << "\t" << w_error_t::error_string(rc.err_num()) << endl;
            cerr << "\t" << err_stream.c_str() << endl;
            print_usage(cerr, prog_name, false, options);
        }
    } 

    /* 
     * Assuming there has been no error so far, the command line
     * is processed for any smsh specific flags.
     */
    int option;
    //if (!rc) 
    {  // do even if error so that smsh -h can be recognized
        bool verbose_opt = false; // print verbose option values
        while ((option = getopt(argc, (char * const*) argv, "Cf:hLOsTvV")) != -1) {
            switch (option) {
            case 'T':
                extern bool logtrace;
                logtrace = true;
                break;
            case 'O':
                    // Force use of old sort
                cout << "Force use of old sort implementation." <<endl;
                newsort = false;
                break;

            case 'C':
                // force compression of btrees
                force_compress = true;
                break;

            case 's':
                print_stats = true;
                break;

            case 'f':
                f_arg = optarg;
                break;

            case 'L':
                // use log warning callback
                log_warn_callback = true;
                break;

            case 'h':
                // print a help message describing options and flags
                print_usage(cerr, prog_name, true, options);
                // free rc structure to avoid complaints on exit
                W_IGNORE(rc);
                goto done;
                break;
            case 'v':
                verbose_opt = true;
                break;
            case 'V':
                verbose = true;
                break;
            default:
                cerr << "unknown flag: " << option << endl;
                rc = RC(SSH_COMMAND_LINE);
            }
        }

        if (verbose_opt) {
            options.print_values(false, cerr);
        }
    }

    /*
     * Assuming no error so far, check that all required options
     * in option_group_t options are set.  
     */
    if (!rc.is_error()) {
        // check required options
        w_ostrstream        err_stream;
        rc = options.check_required(&err_stream);
        err_stream << ends;
        if (rc.is_error()) {
            cerr << "These required options are not set:" << endl;
            cerr << err_stream.c_str() << endl;
            print_usage(cerr, prog_name, false, options);
        }
    } 


    /* 
     * If there have been any problems so far, then exit
     */
    if (rc.is_error()) {
        // free the rc error structure to avoid complaints on exit
        W_IGNORE(rc);
        goto errordone;
    }

    /*
     * At this point, all options and flags have been properly
     * set.  What follows is initialization for the rest of
     * the program.  The ssm will be started by a tcl_thread.
     */


    // setup table of sm commands - doesn't involve the Tcl_Interp
    dispatch_init();

    // set up the linked variables
    // either these should be read-only or
    // they need to be made thread-safe.  We can assume for smsh they
    // are for all purposes read-only, since only the mama thread sets
    // them in the scripts.
    linked.sm_page_sz = ss_m::page_sz;
    linked.sm_max_exts = ss_m::max_exts;
    linked.sm_max_vols = ss_m::max_vols;
    linked.sm_max_servers = ss_m::max_servers;
    linked.sm_max_keycomp = ss_m::max_keycomp;
    linked.sm_max_dir_cache = ss_m::max_dir_cache;
    linked.sm_max_rec_len = ss_m::max_rec_len;
    linked.sm_srvid_map_sz = ss_m::srvid_map_sz;
    linked.verbose_flag = verbose?1:0;
    linked.verbose2_flag = verbose2?1:0;
    linked.instrument_flag = instrument?1:0;
    linked.compress_flag = force_compress?1:0;
    linked.log_warn_callback_flag = log_warn_callback?1:0;

    {
        int tty = isatty(0);
        interactive = tty && f_arg;
    }

    // Create the main tcl_thread
    {
        tcl_thread_t* tcl_thread = NULL;
        bool ok = true;

        if(ok) {
            if (f_arg) {
                TCL_AV char* av[2];
                av[0] = TCL_AV1 "source";
                av[1] = f_arg;
                // smsh -f <file>
                tcl_thread = new tcl_thread_t(2, av, 
                                smsh_libdir->value(),
                                smsh_smshrc->value()
                                );
            } else {
                // interactive
                /*
                cerr << __func__ << " " << __LINE__ << " " << __FILE__
                << " INTERACTIVE libdir " << smsh_libdir->value()
                << " msshrc " << smsh_smshrc->value()
                << endl;
                */
                tcl_thread = new tcl_thread_t(0, 0,
                                smsh_libdir->value(),
                                smsh_smshrc->value()
                                );
            }
            assert(tcl_thread);

            W_COERCE( tcl_thread->fork() );
            W_COERCE( tcl_thread->join() );

            delete tcl_thread;
        }
    }


    // Shutdown TCL and have it deallocate resources still held!
    Tcl_Finalize();

    U.stop(1); // 1 iteration

    if(print_stats) 
    {
        cout << "Thread stats" <<endl;
        sthread_t::dump_stats(cout);
        cout << endl;

        cout << "Unix stats for parent:" <<endl;
        cout << U << endl << endl;

    }
    cout << flush;

done:
    clean_up_shell();
    fprintf(stderr, "%d tcl threads ran\n", num_tcl_threads_ttl);
    return 0;

errordone:
    clean_up_shell();
    return 1;
}
Exemplo n.º 23
0
int main(int argc, char *argv[])
{
	struct iscsi_context *iscsi;
	const char *url = NULL;
	struct iscsi_url *iscsi_url = NULL;
	int show_help = 0, show_usage = 0, debug = 0;
	int c;
	int ret = 0;
	int swp = 0;
	struct scsi_task *sense_task = NULL;
	struct scsi_task *select_task = NULL;
	struct scsi_mode_sense *ms;
	struct scsi_mode_page *mp;

	static struct option long_options[] = {
		{"help",           no_argument,          NULL,        'h'},
		{"usage",          no_argument,          NULL,        'u'},
		{"debug",          no_argument,          NULL,        'd'},
		{"initiator-name", required_argument,    NULL,        'i'},
		{"swp",            required_argument,    NULL,        's'},
		{0, 0, 0, 0}
	};
	int option_index;

	while ((c = getopt_long(argc, argv, "h?udi:s:", long_options,
			&option_index)) != -1) {
		switch (c) {
		case 'h':
		case '?':
			show_help = 1;
			break;
		case 'u':
			show_usage = 1;
			break;
		case 'd':
			debug = 1;
			break;
		case 'i':
			initiator = optarg;
			break;
		case 's':
			if (!strcmp(optarg, "on") || !strcmp(optarg, "ON")) {
				swp = 1;
			}
			if (!strcmp(optarg, "off") || !strcmp(optarg, "OFF")) {
				swp = 2;
			}
			break;
		default:
			fprintf(stderr, "Unrecognized option '%c'\n\n", c);
			print_help();
			exit(0);
		}
	}

	if (show_help != 0) {
		print_help();
		exit(0);
	}

	if (show_usage != 0) {
		print_usage();
		exit(0);
	}

	iscsi = iscsi_create_context(initiator);
	if (iscsi == NULL) {
		fprintf(stderr, "Failed to create context\n");
		exit(10);
	}

	if (debug > 0) {
		iscsi_set_log_level(iscsi, debug);
		iscsi_set_log_fn(iscsi, iscsi_log_to_stderr);
	}

	if (argv[optind] != NULL) {
		url = strdup(argv[optind]);
	}
	if (url == NULL) {
		fprintf(stderr, "You must specify the URL\n");
		print_usage();
		ret = 10;
		goto finished;
	}
	iscsi_url = iscsi_parse_full_url(iscsi, url);
	
	free(discard_const(url));

	if (iscsi_url == NULL) {
		fprintf(stderr, "Failed to parse URL: %s\n", 
			iscsi_get_error(iscsi));
		ret = 10;
		goto finished;
	}

	iscsi_set_session_type(iscsi, ISCSI_SESSION_NORMAL);
	iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);

	if (iscsi_full_connect_sync(iscsi, iscsi_url->portal, iscsi_url->lun) != 0) {
		fprintf(stderr, "Login Failed. %s\n", iscsi_get_error(iscsi));
		ret = 10;
		goto finished;
	}


	sense_task = iscsi_modesense10_sync(iscsi, iscsi_url->lun,
		0, 1, SCSI_MODESENSE_PC_CURRENT,
		SCSI_MODEPAGE_CONTROL,
		0, 255);
	if (sense_task == NULL) {
		printf("Failed to send MODE_SENSE10 command: %s\n",
			iscsi_get_error(iscsi));
		ret = 10;
		goto finished;
	}
	if (sense_task->status != SCSI_STATUS_GOOD) {
		printf("MODE_SENSE10 failed: %s\n",
			iscsi_get_error(iscsi));
		ret = 10;
		goto finished;
	}
	ms = scsi_datain_unmarshall(sense_task);
	if (ms == NULL) {
		printf("failed to unmarshall mode sense datain blob\n");
		ret = 10;
		goto finished;
	}
	mp = scsi_modesense_get_page(ms, SCSI_MODEPAGE_CONTROL, 0);
	if (mp == NULL) {
		printf("failed to read control mode page\n");
		ret = 10;
		goto finished;
	}

	/* For MODE SELECT PS is reserved and hence must be cleared */
	mp->ps = 0;

	printf("SWP:%d\n", mp->control.swp);

	switch (swp) {
	case 1:
		mp->control.swp = 1;
		break;
	case 2:
		mp->control.swp = 0;
		break;
	default:
		goto finished;
	}

	printf("Turning SWP %s\n", (swp == 1) ? "ON" : "OFF"); 
	select_task = iscsi_modeselect10_sync(iscsi, iscsi_url->lun,
		    1, 0, mp);
	if (select_task == NULL) {
		printf("Failed to send MODE_SELECT10 command: %s\n",
			iscsi_get_error(iscsi));
		ret = 10;
		goto finished;
	}
	if (select_task->status != SCSI_STATUS_GOOD) {
		printf("MODE_SELECT10 failed: %s\n",
			iscsi_get_error(iscsi));
		ret = 10;
		goto finished;
	}


finished:
	if (sense_task != NULL) {
		scsi_free_scsi_task(sense_task);
	}
	if (select_task != NULL) {
		scsi_free_scsi_task(select_task);
	}
	if (iscsi_url != NULL) {
		iscsi_destroy_url(iscsi_url);
	}
	iscsi_logout_sync(iscsi);
	iscsi_destroy_context(iscsi);
	return ret;
}
Exemplo n.º 24
0
/*==================================
 * main -- Main routine of LifeLines
 *================================*/
int
main (int argc, char **argv)
{
	extern char *optarg;
	extern int optind;
	char * msg;
	int c;
	BOOLEAN ok=FALSE;
	STRING dbrequested=NULL; /* database (path) requested */
	STRING dbused=NULL; /* database (path) found */
	BOOLEAN forceopen=FALSE, lockchange=FALSE;
	char lockarg = 0; /* option passed for database lock */
	INT alteration=0;
	LIST exprogs=NULL;
	TABLE exargs=NULL;
	STRING progout=NULL;
	BOOLEAN graphical=TRUE;
	STRING configfile=0;
	STRING crashlog=NULL;
	int i=0;

	/* initialize all the low-level library code */
	init_stdlib();

#if HAVE_SETLOCALE
	/* initialize locales */
	setlocale(LC_ALL, "");
#endif /* HAVE_SETLOCALE */
	
#if ENABLE_NLS
	/* setup gettext translation */
	/* NB: later we may revise locale dir or codeset
	based on user settings */
	ll_bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
#endif

	save_original_locales();
	load_usage();

	/* handle conventional arguments --version and --help */
	/* needed for help2man to synthesize manual pages */
	for (i=1; i<argc; ++i) {
		if (!strcmp(argv[i], "--version")
			|| !strcmp(argv[i], "-v")) {
			print_version("llines");
			return 0;
		}
		if (!strcmp(argv[i], "--help")
			|| !strcmp(argv[i], "-h")
			|| !strcmp(argv[i], "-?")) {
			print_usage();
			return 0;
		}
	}

	/* Parse Command-Line Arguments */
	opterr = 0;	/* turn off getopt's error message */
	while ((c = getopt(argc, argv, "adkrwil:fntc:Fu:x:o:zC:I:vh?")) != -1) {
		switch (c) {
		case 'c':	/* adjust cache sizes */
			while(optarg && *optarg) {
				if(isasciiletter((uchar)*optarg) && isupper((uchar)*optarg))
					*optarg = tolower((uchar)*optarg);
				if(*optarg == 'i') {
					INT icsz_indi=0;
					sscanf(optarg+1, "%ld,%ld", &csz_indi, &icsz_indi);
				}
				else if(*optarg == 'f') {
					INT icsz_fam=0;
					sscanf(optarg+1, "%ld,%ld", &csz_fam, &icsz_fam);
				}
				else if(*optarg == 's') {
					INT icsz_sour=0;
					sscanf(optarg+1, "%ld,%ld", &csz_sour, &icsz_sour);
				}
				else if(*optarg == 'e') {
					INT icsz_even=0;
					sscanf(optarg+1, "%ld,%ld", &csz_even, &icsz_even);
				}
				else if((*optarg == 'o') || (*optarg == 'x')) {
					INT icsz_othr=0;
					sscanf(optarg+1, "%ld,%ld", &csz_othr, &icsz_othr);
				}
				optarg++;
				while(*optarg && isdigit((uchar)*optarg)) optarg++;
				if(*optarg == ',') optarg++;
				while(*optarg && isdigit((uchar)*optarg)) optarg++;
			}
			break;
#ifdef FINNISH
# ifdef FINNISHOPTION
		case 'F':	/* Finnish sorting order [toggle] */
			opt_finnish = !opt_finnish;
			/*
			TODO - need to mark Finnish databases, as 
			name records are not interoperable, because of
			different soundex encoding
			2001-02-17, Perry Rapp
			TODO, 2002-11-07, Perry Rapp:
			Need to see if we can fix database so locale sort doesn't affect btree
			because it would be nicer if changing locale didn't hurt the btree !
			Perhaps locale collates can only be used inside name records ? needs research
			*/
			break;
# endif
#endif
		case 'a':	/* debug allocation */
			alloclog = TRUE;
			break;
		case 'd':	/* debug = no signal catchers */
			debugmode = TRUE;
			break;
		case 'k':	/* don't show key values */
			keyflag = FALSE;
			break;
		case 'r':	/* request for read only access */
			readonly = TRUE;
			break;
		case 'w':	/* request for write access */
			writeable = TRUE;
			break;
		case 'i': /* immutable access */
			immutable = TRUE;
			readonly = TRUE;
			break;
		case 'l': /* locking switch */
			lockchange = TRUE;
			lockarg = *optarg;
			break;
		case 'f':	/* force database open in all cases */
			forceopen = TRUE;
			break;
		case 'n':	/* use non-traditional family rules */
			traditional = FALSE;
			break;
		case 't': /* show lots of trace statements for debugging */
			prog_trace = TRUE;
			break;
		case 'u': /* specify screen dimensions */
			sscanf(optarg, "%ld,%ld", &winx, &winy);
			break;
		case 'x': /* execute program */
			if (!exprogs) {
				exprogs = create_list2(LISTDOFREE);
			}
			push_list(exprogs, strdup(optarg ? optarg : ""));
			break;
		case 'I': /* program arguments */
			{
				STRING optname=0, optval=0;
				parse_arg(optarg, &optname, &optval);
				if (optname && optval) {
					if (!exargs) {
						exargs = create_table_str();
					}
					insert_table_str(exargs, optname, optval);
				}
				strfree(&optname);
				strfree(&optval);
			}
			break;
		case 'o': /* output directory */
			progout = optarg;
			break;
		case 'z': /* nongraphical box */
			graphical = FALSE;
			break;
		case 'C': /* specify config file */
			configfile = optarg;
			break;
		case 'v': /* show version */
			showversion = TRUE;
			goto usage;
			break;
		case 'h': /* show usage */
		case '?': /* show usage */
			showusage = TRUE;
			showversion = TRUE;
			goto usage;
			break;
		}
	}

prompt_for_db:

	/* catch any fault, so we can close database */
	if (!debugmode)
		set_signals();
	else /* developer wants to drive without seatbelt! */
		stdstring_hardfail();

	set_displaykeys(keyflag);
	/* initialize options & misc. stuff */
	llgettext_set_default_localedir(LOCALEDIR);
	if (!init_lifelines_global(configfile, &msg, &main_db_notify)) {
		llwprintf("%s", msg);
		goto finish;
	}
	/* setup crashlog in case init_screen fails (eg, bad menu shortcuts) */
	crashlog = getlloptstr("CrashLog_llines", NULL);
	if (!crashlog) { crashlog = "CrashLog_llines.log"; }
	crash_setcrashlog(crashlog);

	/* start (n)curses and create windows */
	{
		char errmsg[512];
		if (!init_screen(errmsg, sizeof(errmsg)/sizeof(errmsg[0])))
		{
			endwin();
			fprintf(stderr, errmsg);
			goto finish;
		}
		set_screen_graphical(graphical);
	}
	init_interpreter(); /* give interpreter its turn at initialization */

	/* Validate Command-Line Arguments */
	if ((readonly || immutable) && writeable) {
		llwprintf(_(qSnorwandro));
		goto finish;
	}
	if (forceopen && lockchange) {
		llwprintf(_(qSnofandl));
		goto finish;
	}
	if (lockchange && lockarg != 'y' && lockarg != 'n') {
		llwprintf(_(qSbdlkar));
		goto finish;
	}
	if (forceopen)
		alteration = 3;
	else if (lockchange) {
		if (lockarg == 'y')
			alteration = 2;
		else
			alteration = 1;
	}
	c = argc - optind;
	if (c > 1) {
		showusage = TRUE;
		goto usage;
	}

	/* Open database, prompting user if necessary */
	if (1) {
		STRING errmsg=0;
		if (!alldone && c>0) {
			dbrequested = strsave(argv[optind]);
		} else {
			strupdate(&dbrequested, "");
		}
		if (!select_database(dbrequested, alteration, &errmsg)) {
			if (errmsg) {
				llwprintf(errmsg);
			}
			alldone = 0;
			goto finish;
		}
	}

	/* Start Program */
	if (!init_lifelines_postdb()) {
		llwprintf(_(qSbaddb));
		goto finish;
	}
	if (!int_codeset[0]) {
		msg_info(_("Warning: database codeset unspecified"));
	} else if (!transl_are_all_conversions_ok()) {
		msg_info(_("Warning: not all conversions available"));
	}

	init_show_module();
	init_browse_module();
	if (exargs) {
		set_cmd_options(exargs);
		release_table(exargs);
		exargs = 0;
	}
	if (exprogs) {
		BOOLEAN picklist = FALSE;
		BOOLEAN timing = FALSE;
		interp_main(exprogs, progout, picklist, timing);
		destroy_list(exprogs);
	} else {
		alldone = 0;
		while (!alldone)
			main_menu();
	}
	term_show_module();
	term_browse_module();
	ok=TRUE;

finish:
	/* we free this not because we care so much about these tiny amounts
	of memory, but to ensure we have the memory management right */
	/* strfree frees memory & nulls pointer */
	strfree(&dbused);
	strfree(&dbrequested);
	strfree(&readpath_file);
	shutdown_interpreter();
	close_lifelines();
	shutdown_ui(!ok);
	if (alldone == 2)
		goto prompt_for_db; /* changing databases */
	termlocale();

usage:
	/* Display Version and/or Command-Line Usage Help */
	if (showversion) { print_version("llines"); }
	if (showusage) puts(usage_summary);

	/* Exit */
	return !ok;
}
Exemplo n.º 25
0
int main(int argc, char *argv[]) {
	int nb_platform_attr = DEFAULT_ISSUER_ATTRIBUTES;
	int nb_issuer_attr = DEFAULT_RECEIVER_ATTRIBUTES;
	char *filename = DEFAULT_FILENAME;
	char *issuer = DEFAULT_ISSUER;
	int i;
	char *param;
	TSS_HCONTEXT hContext;
	TSS_DAA_KEY_PAIR *key_pair;
	TSS_DAA_PK_PROOF *public_keyproof;
	TSS_RESULT result;
	TSS_HDAA hDAA;
	TSS_DAA_PK_PROOF_internal *public_keyproof_internal;
	TSS_DAA_PK_internal *pk;
	TSS_DAA_PRIVATE_KEY *private_key;
	DAA_PRIVATE_KEY_internal *private_key_internal;
	KEY_PAIR_WITH_PROOF_internal *key_pair_with_proof;

	printf("Issuer Setup (%s:%s,%s)\n", argv[0], __DATE__, __TIME__);
	i = 1;
	while( i < argc) {
		param = argv[ i];
		if         ( strcmp( param, "-if") == 0 || strcmp( param, "--issuer_file")) {
			i++;
			if( i == argc) return print_usage( argv[0]);
			filename = argv[i];
		} else if( strcmp( param, "-npa") == 0 || strcmp( param, "--nb_platform_attr")) {
			i++;
			if( i == argc) return print_usage( argv[0]);
			nb_platform_attr = atoi( argv[i]);
		} else if( strcmp( param, "-nia") == 0 || strcmp( param, "--nb_issuer_attr")) {
			i++;
			if( i == argc) return print_usage( argv[0]);
			nb_issuer_attr = atoi(argv[i]);
		} else if( strcmp( param, "-i") == 0 || strcmp( param, "--issuer")) {
			i++;
			if( i == argc) return print_usage( argv[0]);
			issuer = argv[i];
		} else {
			fprintf(stderr, 	"%s:unrecognized option `%s'\n", argv[0], param);
			return print_usage( argv[0]);
		}
		i++;
	}
	bi_init( NULL);
	// Create Context
	printf("Create Context\n");
	result = Tspi_Context_Create( &hContext );
	if ( result != TSS_SUCCESS )
	{
		fprintf( stderr, "Tspi_Context_Create %d\n", result );
		exit( result );
	}

	// Connect to Context
	printf("Connect to the context\n");
	result = Tspi_Context_Connect( hContext, NULL );
	if ( result != TSS_SUCCESS )
	{
		fprintf( stderr, "Tspi_Context_Connect error:%d\n", result );
		Tspi_Context_FreeMemory( hContext, NULL );
		Tspi_Context_Close( hContext );
		exit( result );
	}
	//Create Object
	result = obj_daa_add( hContext, &hDAA);
	if (result != TSS_SUCCESS) {
		goto close;
	}
	result = Tspi_DAA_IssueSetup(
		hDAA,	// in
		strlen( issuer),	// in
		(BYTE *)issuer,	// in
		nb_platform_attr,	// in
		nb_issuer_attr,	// in
		(TSS_HKEY *)&key_pair,	// out
		&public_keyproof);	// out
	if( result != TSS_SUCCESS) goto close;

	// TSS_DAA_KEY_PAIR_internal *key_pair_internal = DAA_KEY_PAIR_2_internal( key_pair);
	public_keyproof_internal = e_2_i_TSS_DAA_PK_PROOF( public_keyproof);
	pk = e_2_i_TSS_DAA_PK( key_pair->public_key);
	private_key = key_pair->private_key;
	private_key_internal = e_2_i_TSS_DAA_PRIVATE_KEY( private_key);
	key_pair_with_proof =
		(KEY_PAIR_WITH_PROOF_internal *)malloc( sizeof(KEY_PAIR_WITH_PROOF_internal));
	if( key_pair_with_proof == NULL) {
		fprintf("malloc of %d bytes failed", sizeof(KEY_PAIR_WITH_PROOF_internal));
		goto close;
	}
	key_pair_with_proof->pk = pk;
	key_pair_with_proof->private_key = private_key_internal;
	key_pair_with_proof->proof = public_keyproof_internal;

	printf("Saving key pair with proof  -> 	\'%s\'", filename);
	FILE *file = fopen( filename, "w");
	if( file == NULL) {
		fprintf( stderr, "%s: Error when saving \'%s\': %s\n",
			argv[0],
			filename,
			strerror( errno));
		return -1;
	}
	if( save_KEY_PAIR_WITH_PROOF( file, key_pair_with_proof) != 0) {
		fprintf( stderr, "%s: Error when saving \'%s\': %s\n",
			argv[0],
			filename,
			strerror( errno));
		return -1;
	}
	fclose( file);
	printf("\nDone.\n");
close:
	obj_daa_remove( hDAA, hContext);
	printf("Closing the context\n");
	Tspi_Context_FreeMemory( hContext, NULL );
	Tspi_Context_Close( hContext );
	bi_release();
	printf("Result: %d", result);
	return result;
}
Exemplo n.º 26
0
int
cmd_print(int argc, char *argv[])
{
	struct smb_ctx sctx, *ctx = &sctx;
	smbfh fh;
	off_t offset;
	char buf[8192];
	char *filename;
	char fnamebuf[256];
	int error, opt, i, file, count;

	if (argc < 2)
		view_usage();
	if (smb_ctx_init(ctx, argc, argv, SMBL_SHARE, SMBL_SHARE, SMB_ST_PRINTER) != 0)
		exit(1);
	if (smb_ctx_readrc(ctx) != 0)
		exit(1);
	if (smb_rc)
		rc_close(smb_rc);
	while ((opt = getopt(argc, argv, STDPARAM_OPT)) != EOF) {
		switch(opt){
		    case STDPARAM_ARGS:
			error = smb_ctx_opt(ctx, opt, optarg);
			if (error)
				exit(1);
			break;
		    default:
			view_usage();
			/*NOTREACHED*/
		}
	}
	if (optind + 1 >= argc)
		print_usage();
	filename = argv[optind + 1];

	if (strcmp(filename, "-") == 0) {
		file = 0;	/* stdin */
		filename = "stdin";
	} else {
		file = open(filename, O_RDONLY, 0);
		if (file < 0) {
			smb_error("could not open file %s\n", errno, filename);
			exit(1);
		}
	}

	if (smb_ctx_resolve(ctx) != 0)
		exit(1);
	error = smb_ctx_lookup(ctx, SMBL_SHARE, SMBLK_CREATE);
	if (error) {
		smb_error("could not login to server %s", error, ctx->ct_ssn.ioc_srvname);
		exit(1);
	}
	snprintf(fnamebuf, sizeof(fnamebuf), "%s_%s_%s", ctx->ct_ssn.ioc_user,
	    ctx->ct_ssn.ioc_srvname, filename);
	error = smb_smb_open_print_file(ctx, 0, 1, fnamebuf, &fh);
	if (error) {
		smb_error("could not open print job", error);
		exit(1);
	}
	offset = 0;
	error = 0;
	for(;;) {
		count = read(file, buf, sizeof(buf));
		if (count == 0)
			break;
		if (count < 0) {
			error = errno;
			smb_error("error reading input file\n", error);
			break;
		}
		i = smb_write(ctx, fh, offset, count, buf);
		if (i < 0) {
			error = errno;
			smb_error("error writing spool file\n", error);
			break;
		}
		if (i != count) {
			smb_error("incomplete write to spool file\n", 0);
			error = EIO;
			break;
		}
		offset += count;
	}
	close(file);
	error = smb_smb_close_print_file(ctx, fh);
	if (error)
		smb_error("an error while closing spool file\n", error);
	return error ? 1 : 0;
}
Exemplo n.º 27
0
int main_dbghelper(int argc, char *argv[])
{
	main_argc = argc;
	main_argv = argv;

#ifdef DEDI
	if(argc <= 1)
		return print_usage(argv[0]);
#else
	if(argc <= 1)
	{
		//print_usage(argv[0]);
		net_port = 0;
		mod_basedir = "pkg/iceball/halp";
		printf("Starting server on port %i, mod \"%s\"\n", net_port, mod_basedir);
		main_largstart = 4;
		
		boot_mode = 3;
	} else
#endif
	
#ifndef DEDI
	if((!strcmp(argv[1], "-h")) || (!strcmp(argv[1], "/?")) || (!strcmp(argv[1], "-?")) || (!strcmp(argv[1], "--help"))) {
		return print_usage(argv[0]);
	} else if(!strcmp(argv[1], "-c")) {
		if(argc <= 3)
			return print_usage(argv[0]);
		
		net_addr = argv[2];
		net_port = atoi(argv[3]);
		printf("Connecting to \"%s\" port %i (ENet mode)\n", net_addr, net_port);
		mod_basedir = NULL;
		main_largstart = 4;
		
		boot_mode = 1 | 16;
	} else if(!strcmp(argv[1], "-C")) {
		if(argc <= 3)
			return print_usage(argv[0]);
		
		net_addr = argv[2];
		net_port = atoi(argv[3]);
		printf("Connecting to \"%s\" port %i (TCP mode)\n", net_addr, net_port);
		mod_basedir = NULL;
		main_largstart = 4;
		
		boot_mode = 1;
		//return 101;
	} else if(!strcmp(argv[1], "-s")) {
		if(argc <= 3)
			return print_usage(argv[0]);
		
		net_port = atoi(argv[2]);
		mod_basedir = argv[3];
		printf("Starting server on port %i, mod \"%s\" (local mode client)\n", net_port, mod_basedir);
		main_largstart = 4;
		
		boot_mode = 3;
	} else
#endif
	if(!strcmp(argv[1], "-d")) {
		if(argc <= 3)
			return print_usage(argv[0]);
		
		net_port = atoi(argv[2]);
		mod_basedir = argv[3];
		printf("Starting headless/dedicated server on port %i, mod \"%s\"\n", net_port, mod_basedir);
		main_largstart = 4;
		
		boot_mode = 2;
		//return 101;
	} else {
		return print_usage(argv[0]);
	}
	
	if(boot_mode & 2)
	{
		if(memcmp(mod_basedir,"pkg/",4))
		{
			fprintf(stderr, "ERROR: package base dir must start with \"pkg/\"!\n");
			return 109;
		}
		
		if(strlen(mod_basedir) < 5)
		{
			fprintf(stderr, "ERROR: package base dir can't actually be \"pkg/\"!\n");
			return 109;
		}
	}
	
#ifndef DEDI
	if((!(boot_mode & 1)) || !platform_init()) {
#endif
	if(!net_init()) {
	if(!icelua_init()) {
	if((!(boot_mode & 2)) || !net_bind()) {
#ifndef DEDI
	if((!(boot_mode & 1)) || !net_connect()) {
	if((!(boot_mode & 1)) || !video_init()) {
	if((!(boot_mode & 1)) || !wav_init()) {
	if((!(boot_mode & 1)) || !render_init(screen->w, screen->h)) {
#endif
		run_game();
#ifndef DEDI
		if(boot_mode & 1) render_deinit();
	} if(boot_mode & 1) wav_deinit();
	} if(boot_mode & 1) video_deinit();
	} if(boot_mode & 1) net_disconnect();
#endif
	} if(boot_mode & 2) net_unbind();
	} icelua_deinit();
	} net_deinit();
#ifndef DEDI
	} if(boot_mode & 1) platform_deinit();
	}
#endif
	
	return 0;
}
Exemplo n.º 28
0
static int
parse_args (int argc, ACE_TCHAR *argv[])
{
  if (argc == 1) // no arguments , so one button test
    {
      both = 1;               // client and server simultaneosly
      duplex = 1;             // full duplex is on
      host = ACE_TEXT ("localhost");      // server to connect
      port = ACE_DEFAULT_SERVER_PORT; // port to connect/listen
      threads = 3;            // size of Proactor thread pool
      senders = 20;           // number of senders
      loglevel = 1;           // log level : 0 full/ 1 only errors
      seconds = 20;           // time to run in seconds
#if defined(SOMAXCONN) // The test is invalid if senders > SOMAXCONN
      if(SOMAXCONN < senders)
        senders = SOMAXCONN;
#endif
      return 0;
    }

  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT ("i:n:p:d:h:s:v:ub"));
  int c;

  while ((c = get_opt ()) != EOF)
    {
      switch (c)
        {
        case 'i':  // time to run
          seconds = ACE_OS::atoi (get_opt.opt_arg());
          if (seconds < MIN_TIME)
            seconds = MIN_TIME;
          if (seconds > MAX_TIME)
            seconds = MAX_TIME;
          break;
        case 'b':  // both client and server
          both = 1;
          break;
        case 'v':  // log level
          loglevel = ACE_OS::atoi (get_opt.opt_arg());
          break;
        case 'd':         // duplex
          duplex = ACE_OS::atoi (get_opt.opt_arg());
          break;
        case 'h':         // host for sender
          host = get_opt.opt_arg();
          break;
        case 'p':         // port number
          port = ACE_OS::atoi (get_opt.opt_arg());
          break;
        case 'n':         // thread pool size
          threads = ACE_OS::atoi (get_opt.opt_arg());
          break;
        case 's':     // number of senders
          senders = ACE_OS::atoi (get_opt.opt_arg());
          if (size_t (senders) > MAX_SENDERS)
            senders = MAX_SENDERS;
          break;
        case 'u':
        default:
          return print_usage (argc,argv);
        } // switch
    } // while

  return 0;
}
Exemplo n.º 29
0
void listen_loop(int do_init) {
	struct client_struct* new_client;
	struct np_sock npsock = {.count = 0};
	pthread_t client_tid;
	int ret;
#ifdef NP_SSH
	ssh_bind sshbind = NULL;
#endif
#ifdef NP_TLS
	SSL_CTX* tlsctx = NULL;
#endif

	/* Init */
	if (do_init) {
#ifdef NP_SSH
		np_ssh_init();
#endif
#ifdef NP_TLS
		np_tls_init();
#endif
	}

	/* Main accept loop */
	do {
		new_client = NULL;

		/* Binds change check */
		if (netopeer_options.binds_change_flag) {
			/* BINDS LOCK */
			pthread_mutex_lock(&netopeer_options.binds_lock);

			sock_cleanup(&npsock);
			sock_listen(netopeer_options.binds, &npsock);

			netopeer_options.binds_change_flag = 0;
			/* BINDS UNLOCK */
			pthread_mutex_unlock(&netopeer_options.binds_lock);

			if (npsock.count == 0) {
				nc_verb_warning("Server is not listening on any address!");
			}
		}

#ifdef NP_SSH
		sshbind = np_ssh_server_id_check(sshbind);
#endif
#ifdef NP_TLS
		tlsctx = np_tls_server_id_check(tlsctx);
#endif

		/* Callhome client check */
		if (callhome_client != NULL) {
			/* CALLHOME LOCK */
			pthread_mutex_lock(&callhome_lock);
			new_client = callhome_client;
			callhome_client = NULL;
			/* CALLHOME UNLOCK */
			pthread_mutex_unlock(&callhome_lock);
		}

		/* Listen client check */
		if (new_client == NULL) {
			new_client = sock_accept(&npsock);
		}

		/* New client full structure creation */
		if (new_client != NULL) {

			/* Maximum number of sessions check */
			if (netopeer_options.max_sessions > 0) {
				ret = 0;
#ifdef NP_SSH
				ret += np_ssh_session_count();
#endif
#ifdef NP_TLS
				ret += np_tls_session_count();
#endif

				if (ret >= netopeer_options.max_sessions) {
					nc_verb_error("Maximum number of sessions reached, droppping the new client.");
					new_client->to_free = 1;
					switch (new_client->transport) {
#ifdef NP_SSH
					case NC_TRANSPORT_SSH:
						client_free_ssh((struct client_struct_ssh*)new_client);
						break;
#endif
#ifdef NP_TLS
					case NC_TRANSPORT_TLS:
						client_free_tls((struct client_struct_tls*)new_client);
						break;
#endif
					default:
						free(new_client);
						nc_verb_error("%s: internal error (%s:%d)", __func__, __FILE__, __LINE__);
					}

					/* sleep to prevent clients from immediate connection retry */
					usleep(netopeer_options.response_time*1000);
					continue;
				}
			}

			switch (new_client->transport) {
#ifdef NP_SSH
			case NC_TRANSPORT_SSH:
				ret = np_ssh_create_client((struct client_struct_ssh*)new_client, sshbind);
				if (ret != 0) {
					new_client->to_free = 1;
					client_free_ssh((struct client_struct_ssh*)new_client);
				}
				break;
#endif
#ifdef NP_TLS
			case NC_TRANSPORT_TLS:
				ret = np_tls_create_client((struct client_struct_tls*)new_client, tlsctx);
				if (ret != 0) {
					new_client->to_free = 1;
					client_free_tls((struct client_struct_tls*)new_client);
				}
				break;
#endif
			default:
				nc_verb_error("Client with an unknown transport protocol, dropping it.");
				free(new_client);
				ret = 1;
			}

			/* client is not valid, some error occured */
			if (ret != 0) {
				continue;
			}

			/* add the client into the global clients structure */
			/* GLOBAL WRITE LOCK */
			pthread_rwlock_wrlock(&netopeer_state.global_lock);
			client_append(&netopeer_state.clients, new_client);
			/* GLOBAL WRITE UNLOCK */
			pthread_rwlock_unlock(&netopeer_state.global_lock);

			/* start the client thread */
			if ((ret = pthread_create((pthread_t*)&new_client->tid, NULL, client_main_thread, (void*)new_client)) != 0) {
				nc_verb_error("%s: failed to create a thread (%s)", __func__, strerror(ret));
				np_client_detach(&netopeer_state.clients, new_client);

				new_client->tid = 0;
				new_client->to_free = 1;
				switch (new_client->transport) {
#ifdef NP_SSH
				case NC_TRANSPORT_SSH:
					client_free_ssh((struct client_struct_ssh*)new_client);
					break;
#endif
#ifdef NP_TLS
				case NC_TRANSPORT_TLS:
					client_free_tls((struct client_struct_tls*)new_client);
					break;
#endif
				default:
					free(new_client);
					break;
				}
				continue;
			}
		}

	} while (!quit && !restart_soft);

	/* Cleanup */
	sock_cleanup(&npsock);
#ifdef NP_SSH
	ssh_bind_free(sshbind);
#endif
#ifdef NP_TLS
	SSL_CTX_free(tlsctx);
#endif
	if (!restart_soft) {
		/* wait for all the clients to exit nicely themselves */
		while (1) {
			/* GLOBAL READ LOCK */
			pthread_rwlock_rdlock(&netopeer_state.global_lock);

			if (netopeer_state.clients == NULL) {
				/* GLOBAL READ UNLOCK */
				pthread_rwlock_unlock(&netopeer_state.global_lock);

				break;
			}

			client_tid = netopeer_state.clients->tid;

			/* GLOBAL READ UNLOCK */
			pthread_rwlock_unlock(&netopeer_state.global_lock);

			ret = pthread_join(client_tid, NULL);
			if (ret != 0 && errno != EINTR) {
				nc_verb_error("Failed to join client thread (%s).", strerror(errno));
			}
		}

#ifdef NP_SSH
		np_ssh_cleanup();
#endif
#ifdef NP_TLS
		np_tls_cleanup();
#endif
	}
}

int main(int argc, char** argv) {
	struct sigaction action;
	sigset_t block_mask;

	char *aux_string = NULL, path[PATH_MAX+1];
	int next_option;
	int daemonize = 0, len;
	int listen_init = 1;
	struct np_module* netopeer_module = NULL, *server_module = NULL;

	/* initialize message system and set verbose and debug variables */
	if ((aux_string = getenv(ENVIRONMENT_VERBOSE)) == NULL) {
		netopeer_options.verbose = NC_VERB_ERROR;
	} else {
		netopeer_options.verbose = atoi(aux_string);
	}

	aux_string = NULL; /* for sure to avoid unwanted changes in environment */

	/* parse given options */
	while ((next_option = getopt(argc, argv, OPTSTRING)) != -1) {
		switch (next_option) {
		case 'd':
			daemonize = 1;
			break;
		case 'h':
			print_usage(argv[0]);
			break;
		case 'v':
			netopeer_options.verbose = atoi(optarg);
			break;
		case 'V':
			print_version(argv[0]);
			break;
		default:
			print_usage(argv[0]);
			break;
		}
	}

	/* set signal handler */
	sigfillset (&block_mask);
	action.sa_handler = signal_handler;
	action.sa_mask = block_mask;
	action.sa_flags = 0;
	sigaction(SIGINT, &action, NULL);
	sigaction(SIGQUIT, &action, NULL);
	sigaction(SIGABRT, &action, NULL);
	sigaction(SIGTERM, &action, NULL);
	sigaction(SIGHUP, &action, NULL);

	nc_callback_print(clb_print);

	/* normalize value if not from the enum */
	if (netopeer_options.verbose > NC_VERB_DEBUG) {
		netopeer_options.verbose = NC_VERB_DEBUG;
	}
	nc_verbosity(netopeer_options.verbose);

	/* go to the background as a daemon */
	if (daemonize == 1) {
		if (daemon(0, 0) != 0) {
			nc_verb_error("Going to background failed (%s)", strerror(errno));
			return EXIT_FAILURE;
		}
		openlog("netopeer-server", LOG_PID, LOG_DAEMON);
	} else {
		openlog("netopeer-server", LOG_PID|LOG_PERROR, LOG_DAEMON);
	}

	/* make sure we were executed by root */
	if (geteuid() != 0) {
		nc_verb_error("Failed to start, must have root privileges.");
		return EXIT_FAILURE;
	}

	/*
	 * this initialize the library and check potential ABI mismatches
	 * between the version it was compiled for and the actual shared
	 * library used.
	 */
	LIBXML_TEST_VERSION

	/* initialize library including internal datastores and maybee something more */
	if (nc_init(NC_INIT_ALL | NC_INIT_MULTILAYER) < 0) {
		nc_verb_error("Library initialization failed.");
		return EXIT_FAILURE;
	}

	server_start = 1;

restart:
	/* start NETCONF server module */
	if ((server_module = calloc(1, sizeof(struct np_module))) == NULL) {
		nc_verb_error("Creating necessary NETCONF server plugin failed!");
		return EXIT_FAILURE;
	}
	server_module->name = strdup(NCSERVER_MODULE_NAME);
	if (module_enable(server_module, 0)) {
		nc_verb_error("Starting necessary NETCONF server plugin failed!");
		free(server_module->name);
		free(server_module);
		return EXIT_FAILURE;
	}

	/* start netopeer device module - it will start all modules that are
	 * in its configuration and in server configuration */
	if ((netopeer_module = calloc(1, sizeof(struct np_module))) == NULL) {
		nc_verb_error("Creating necessary Netopeer plugin failed!");
		module_disable(server_module, 1);
		return EXIT_FAILURE;
	}
	netopeer_module->name = strdup(NETOPEER_MODULE_NAME);
	if (module_enable(netopeer_module, 0)) {
		nc_verb_error("Starting necessary Netopeer plugin failed!");
		module_disable(server_module, 1);
		free(netopeer_module->name);
		free(netopeer_module);
		return EXIT_FAILURE;
	}

	server_start = 0;
	nc_verb_verbose("Netopeer server successfully initialized.");

	listen_loop(listen_init);

	/* unload Netopeer module -> unload all modules */
	module_disable(server_module, 1);
	module_disable(netopeer_module, 1);

	/* main cleanup */

	if (!restart_soft) {
		/* close libnetconf only when shutting down or hard restarting the server */
		nc_close();
	}

	if (restart_soft) {
		nc_verb_verbose("Server is going to soft restart.");
		restart_soft = 0;
		listen_init = 0;
		goto restart;
	} else if (restart_hard) {
		nc_verb_verbose("Server is going to hard restart.");
		len = readlink("/proc/self/exe", path, PATH_MAX);
		if (len > 0) {
			path[len] = 0;
			xmlCleanupParser();
			execv(path, argv);
		}
		nc_verb_error("Failed to get the path to self.");
		xmlCleanupParser();
		return EXIT_FAILURE;
	}

	/*
	 *Free the global variables that may
	 *have been allocated by the parser.
	 */
	xmlCleanupParser();

	return EXIT_SUCCESS;
}
Exemplo n.º 30
0
int main ( int argc , char ** argv )
{

    if( argc != 2 )
    {
	print_usage();
	return 0;
    }

    fprintf( stderr , "This program wil format the %s file, continue? y/n : ", argv[1]);

    char in;
    in = getchar();

    if( 'y' != in && 'Y' != in )
    {
	fprintf( stderr , "format cancelled!\n");
	return 0;
    }

    int fd;
    if( (fd = open( argv[1] , O_WRONLY )) < 0 )
    {
	fprintf( stderr , "Error on open():%s\n", strerror( errno ) );
	return 1;
    }

    struct sb tSuperBlock;
    
    //good habit is to memset
    memset( &tSuperBlock , 0 , sizeof( struct sb ) );

    tSuperBlock.fs_size = (long)get_file_size( argv[1] ) / BLOCK_SIZE;
    tSuperBlock.us_size = 1 + SUPER_BLOCK_N + BITMAP_BLOCK_N ;     //because the superblock and bitmapblock and root alread occupy some blocks
    tSuperBlock.bk_size = BLOCK_SIZE;
    tSuperBlock.first_blk = BLOCK_SIZE * ( SUPER_BLOCK_N + BITMAP_BLOCK_N );
    tSuperBlock.bitmap = BITMAP_BLOCK_N;

    printf("Disk image file:%s\n" , argv[1] );
    printf("Ready to Write :\n");
    printf("fs_size(in blocks)  : %ld\n", tSuperBlock.fs_size );
    printf("us_size(in blocks)  : %ld\n", tSuperBlock.us_size );
    printf("bk_size(in bytes )  : %ld\n", tSuperBlock.bk_size );
    printf("first_blk(location) : %ld\n", tSuperBlock.first_blk );
    printf("bitmap(in blocks)   : %ld\n\n", tSuperBlock.bitmap );


    //diskimage too small no way to do
    if( tSuperBlock.fs_size < (SUPER_BLOCK_N + BITMAP_BLOCK_N + 1 ) )
    {
	fprintf( stderr , "Diskimage file too small! Can't format, sorry!\n");
	exit(1);
    }

    //write super block
    lseek( fd , (off_t) 0 , SEEK_SET );
    
    ssize_t wc;
    struct u_fs_disk_block block;
    memset( &block , 0 , sizeof( struct u_fs_disk_block ) );
    memcpy( &block , &tSuperBlock , sizeof( struct sb ) );

    wc = write( fd , (void *) &block , sizeof( struct u_fs_disk_block ));
    if( wc != sizeof( struct u_fs_disk_block ))
    {
	fprintf( stderr , "Error on write():%s\n",strerror(errno));
	exit(1); //it will help me to close file ?
    }
    //super block done

    //write bitmap block
    lseek( fd , (off_t) (SUPER_BLOCK_N * BLOCK_SIZE) , SEEK_SET );
    char buffer[BLOCK_SIZE];
    (void *) memset((void *) buffer , 0 , BLOCK_SIZE);

    int count;
    for( count=0; count < tSuperBlock.bitmap ; count++ )
    {
	wc = write( fd , (void *)buffer , BLOCK_SIZE);
	if( wc != BLOCK_SIZE )
	{
	    fprintf( stderr , "Error on write():%s\n",strerror(errno));
	    exit(1); //it will help me to close file ?
	}
    }

    //the first block is occupy by the root dir
    lseek( fd , SUPER_BLOCK_N * BLOCK_SIZE , SEEK_SET );
    unsigned char oc = 0x80;
    write( fd , (void *)&oc , sizeof( oc ));
    //bitmap block done

    //write data block. no much to do. clear the root block
    struct u_fs_disk_block root;
    memset( &root , 0 , sizeof( root ));
    root.size=0;
    root.nNextBlock=0;

    lseek( fd , tSuperBlock.first_blk , SEEK_SET );
    write( fd , (void*)&root , sizeof( root));

    (void) close(fd);

    //read and comfirm
    if( (fd = open( argv[1] , O_RDONLY )) < 0 )
    {
	fprintf( stderr , "Error on open():%s\n", strerror( errno ) );
	return 1;
    }

    struct sb uSuperBlock;
    struct u_fs_disk_block ablock;

    read( fd , (void *)&ablock , sizeof( struct u_fs_disk_block ) );
    memcpy( &uSuperBlock , &ablock , sizeof( struct sb ) );

    printf("Disk image file:%s\n" , argv[1] );
    printf("After Writing :\n");
    printf("fs_size(in blocks)  : %ld\n", tSuperBlock.fs_size );
    printf("us_size(in blocks)  : %ld\n", tSuperBlock.us_size );
    printf("bk_size(in bytes )  : %ld\n", tSuperBlock.bk_size );
    printf("first_blk(location) : %ld\n", tSuperBlock.first_blk );
    printf("bitmap(in blocks)   : %ld\n\n", tSuperBlock.bitmap );

    if( 0 == memcmp( (void*)&tSuperBlock , (void*)&uSuperBlock , sizeof( struct sb) ))
    {
	printf("Check....OK. Format Complete!\n");
    }
    else
    {
	fprintf( stderr , "Check....FAILED. Format Failed!\n");
    }

    ( void ) close( fd );
    
    return 0;
}