Exemple #1
0
int
main (int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_ccache  ccache;
    krb5_principal principal;
    int optidx = 0;
    krb5_deltat ticket_life = 0;
    int parseflags = 0;

    setprogname (argv[0]);

    setlocale (LC_ALL, "");
#if defined(HEIMDAL_LOCALEDIR)
    bindtextdomain ("heimdal_kuser", HEIMDAL_LOCALEDIR);
    textdomain("heimdal_kuser");
#endif

    ret = krb5_init_context (&context);
    if (ret == KRB5_CONFIG_BADFORMAT)
	errx (1, "krb5_init_context failed to parse configuration file");
    else if (ret)
	errx(1, "krb5_init_context failed: %d", ret);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage (0);

    if(version_flag) {
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (canonicalize_flag)
	parseflags |= KRB5_PRINCIPAL_PARSE_ENTERPRISE;

    if (argv[0]) {
	ret = krb5_parse_name_flags (context, argv[0], parseflags, &principal);
	if (ret)
	    krb5_err (context, 1, ret, "krb5_parse_name");
    } else {
	ret = krb5_get_default_principal (context, &principal);
	if (ret)
	    krb5_err (context, 1, ret, "krb5_get_default_principal");
    }

    if(fcache_version)
	krb5_set_fcache_version(context, fcache_version);

    if(renewable_flag == -1)
	/* this seems somewhat pointless, but whatever */
	krb5_appdefault_boolean(context, "kinit",
				krb5_principal_get_realm(context, principal),
				"renewable", FALSE, &renewable_flag);
#ifndef HEIMDAL_SMALLER
    if(get_v4_tgt == -1)
	krb5_appdefault_boolean(context, "kinit",
				krb5_principal_get_realm(context, principal),
				"krb4_get_tickets", FALSE, &get_v4_tgt);
#endif
    if(do_afslog == -1)
	krb5_appdefault_boolean(context, "kinit",
				krb5_principal_get_realm(context, principal),
				"afslog", TRUE, &do_afslog);

    if(cred_cache)
	ret = krb5_cc_resolve(context, cred_cache, &ccache);
    else {
	if(argc > 1) {
	    char s[1024];
	    ret = krb5_cc_gen_new(context, &krb5_fcc_ops, &ccache);
	    if(ret)
		krb5_err(context, 1, ret, "creating cred cache");
	    snprintf(s, sizeof(s), "%s:%s",
		     krb5_cc_get_type(context, ccache),
		     krb5_cc_get_name(context, ccache));
	    setenv("KRB5CCNAME", s, 1);
#ifndef HEIMDAL_SMALLER
	    if (get_v4_tgt) {
		int fd;
		if (asprintf(&krb4_cc_name, "%s_XXXXXX", TKT_ROOT) < 0)
		    krb5_errx(context, 1, "out of memory");
		if((fd = mkstemp(krb4_cc_name)) >= 0) {
		    close(fd);
		    setenv("KRBTKFILE", krb4_cc_name, 1);
		} else {
		    free(krb4_cc_name);
		    krb4_cc_name = NULL;
		}
	    }
#endif
	} else {
	    ret = krb5_cc_cache_match(context, principal, &ccache);
	    if (ret)
		ret = krb5_cc_default (context, &ccache);
	}
    }
    if (ret)
	krb5_err (context, 1, ret, N_("resolving credentials cache", ""));

    if(argc > 1 && k_hasafs ())
	k_setpag();

    if (lifetime) {
	int tmp = parse_time (lifetime, "s");
	if (tmp < 0)
	    errx (1, N_("unparsable time: %s", ""), lifetime);

	ticket_life = tmp;
    }

    if(addrs_flag == 0 && extra_addresses.num_strings > 0)
	krb5_errx(context, 1,
		  N_("specifying both extra addresses and "
		     "no addresses makes no sense", ""));
    {
	int i;
	krb5_addresses addresses;
	memset(&addresses, 0, sizeof(addresses));
	for(i = 0; i < extra_addresses.num_strings; i++) {
	    ret = krb5_parse_address(context, extra_addresses.strings[i],
				     &addresses);
	    if (ret == 0) {
		krb5_add_extra_addresses(context, &addresses);
		krb5_free_addresses(context, &addresses);
	    }
	}
	free_getarg_strings(&extra_addresses);
    }

    if(renew_flag || validate_flag) {
	ret = renew_validate(context, renew_flag, validate_flag,
			     ccache, server_str, ticket_life);
	exit(ret != 0);
    }

#ifndef HEIMDAL_SMALLER
    if(!convert_524)
#endif
	get_new_tickets(context, principal, ccache, ticket_life, 1);

#ifndef HEIMDAL_SMALLER
    if(get_v4_tgt || convert_524)
	do_524init(context, ccache, NULL, server_str);
#endif
    if(do_afslog && k_hasafs())
	krb5_afslog(context, ccache, NULL, NULL);
    if(argc > 1) {
	struct renew_ctx ctx;
	time_t timeout;

	timeout = ticket_lifetime(context, ccache, principal, server_str) / 2;

	ctx.context = context;
	ctx.ccache = ccache;
	ctx.principal = principal;
	ctx.ticket_life = ticket_life;

	ret = simple_execvp_timed(argv[1], argv+1,
				  renew_func, &ctx, timeout);
#define EX_NOEXEC	126
#define EX_NOTFOUND	127
	if(ret == EX_NOEXEC)
	    krb5_warnx(context, N_("permission denied: %s", ""), argv[1]);
	else if(ret == EX_NOTFOUND)
	    krb5_warnx(context, N_("command not found: %s", ""), argv[1]);
	
	krb5_cc_destroy(context, ccache);
#ifndef HEIMDAL_SMALLER
	_krb5_krb_dest_tkt(context, krb4_cc_name);
#endif
	if(k_hasafs())
	    k_unlog();
    } else {
	krb5_cc_close (context, ccache);
	ret = 0;
    }
    krb5_free_principal(context, principal);
    krb5_free_context (context);
    return ret;
}
Exemple #2
0
static
int parse_command_line(int argc, const char **argv, pack_opt_t* options) {

	int opt;
	int ret_value = 0;

	/* parse command line options */
	while ((opt = get_option(argc, argv, s_opts, l_opts)) != EOF) {
		switch ((char) opt) {

		/* -i for backward compability */
		case 'i':
			infile = opt_arg;
			has_i_o = 1;
			break;

			/* -o for backward compability */
		case 'o':
			outfile = opt_arg;
			has_i_o = 1;
			break;

		case 'h':
			usage(h5tools_getprogname());
			h5tools_setstatus(EXIT_SUCCESS);
			ret_value = -1;
			goto done;

		case 'V':
			print_version(h5tools_getprogname());
			h5tools_setstatus(EXIT_SUCCESS);
			ret_value = -1;
			goto done;

		case 'v':
			options->verbose = 1;
			break;

		case 'f':
			/* parse the -f filter option */
			if (h5repack_addfilter(opt_arg, options) < 0) {
				error_msg("in parsing filter\n");
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = -1;
				goto done;
			}
			break;

		case 'l':
			/* parse the -l layout option */
			if (h5repack_addlayout(opt_arg, options) < 0) {
				error_msg("in parsing layout\n");
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = -1;
				goto done;
			}
			break;

		case 'm':
			options->min_comp = HDatoi( opt_arg );
			if ((int) options->min_comp <= 0) {
				error_msg("invalid minimum compress size <%s>\n", opt_arg);
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = -1;
				goto done;
			}
			break;

		case 'e':
			ret_value = read_info(opt_arg, options);
			if (ret_value < 0)
				goto done;
			break;

		case 'n':
			options->use_native = 1;
			break;

		case 'L':
			options->latest = 1;
			break;

		case 'c':
			options->grp_compact = HDatoi( opt_arg );
			if (options->grp_compact > 0)
				options->latest = 1; /* must use latest format */
			break;

		case 'd':
			options->grp_indexed = HDatoi( opt_arg );
			if (options->grp_indexed > 0)
				options->latest = 1; /* must use latest format */
			break;

		case 's':
			{
				int idx = 0;
				int ssize = 0;
				char *msgPtr = HDstrchr( opt_arg, ':');
				options->latest = 1; /* must use latest format */
				if (msgPtr == NULL) {
					ssize = HDatoi( opt_arg );
					for (idx = 0; idx < 5; idx++)
						options->msg_size[idx] = ssize;
				}
				else {
					char msgType[10];
					HDstrcpy(msgType, msgPtr + 1);
					msgPtr[0] = '\0';
					ssize = HDatoi( opt_arg );
					if (HDstrncmp(msgType, "dspace",6) == 0) {
						options->msg_size[0] = ssize;
					}
					else if (HDstrncmp(msgType, "dtype", 5) == 0) {
						options->msg_size[1] = ssize;
					}
					else if (HDstrncmp(msgType, "fill", 4) == 0) {
						options->msg_size[2] = ssize;
					}
					else if (HDstrncmp(msgType, "pline", 5) == 0) {
						options->msg_size[3] = ssize;
					}
					else if (HDstrncmp(msgType, "attr", 4) == 0) {
						options->msg_size[4] = ssize;
					}
				}
			}
			break;

		case 'u':
			options->ublock_filename = opt_arg;
			break;

		case 'b':
			options->ublock_size = (hsize_t) HDatol( opt_arg );
			break;

		case 'M':
			options->meta_block_size = (hsize_t) HDatol( opt_arg );
			break;

		case 't':
			options->threshold = (hsize_t) HDatol( opt_arg );
			break;

		case 'a':
			options->alignment = HDatol( opt_arg );
			if (options->alignment < 1) {
				error_msg("invalid alignment size\n", opt_arg);
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = -1;
				goto done;
			}
			break;

		case 'S':
			{
				char strategy[MAX_NC_NAME];

				HDstrcpy(strategy, opt_arg);
				if (!HDstrcmp(strategy, "ALL_PERSIST"))
					options->fs_strategy = H5F_FILE_SPACE_ALL_PERSIST;
				else if (!HDstrcmp(strategy, "ALL"))
					options->fs_strategy = H5F_FILE_SPACE_ALL;
				else if (!HDstrcmp(strategy, "AGGR_VFD"))
					options->fs_strategy = H5F_FILE_SPACE_AGGR_VFD;
				else if (!HDstrcmp(strategy, "VFD"))
					options->fs_strategy = H5F_FILE_SPACE_VFD;
				else {
					error_msg("invalid file space management strategy\n", opt_arg);
					h5tools_setstatus(EXIT_FAILURE);
					ret_value = -1;
					goto done;
				}
			}
			break;

		case 'T':
			options->fs_threshold = (hsize_t) HDatol( opt_arg );
			break;

		default:
			break;
		} /* switch */

	} /* while */

	if (has_i_o == 0) {
		/* check for file names to be processed */
		if (argc <= opt_ind || argv[opt_ind + 1] == NULL) {
			error_msg("missing file names\n");
			usage(h5tools_getprogname());
			h5tools_setstatus(EXIT_FAILURE);
			ret_value = -1;
		}
	}

done:
	return ret_value;
}
void
CommandLine::parse (int argc, char** argv)
{
  // FIXME: Replace this with getopt_long() or argp()
  for (int i = 1; i < argc; ++i) // Skip Programm name
    {
      //std::cout << "Arg: " << argv[i] << std::endl;

      if (argv[i][0] == '-') // Argument is an option
        {
          if (strcmp(argv[i], "--fullscreen") == 0
              || strcmp(argv[i], "-f") == 0)
            {
              settings.fullscreen = true;
            }
          else if (strcmp(argv[i], "--version") == 0
                   || strcmp(argv[i], "-v") == 0)
            {
              print_version ();
              exit (EXIT_SUCCESS);              
            }
          else if (strcmp(argv[i], "--help") == 0
              || strcmp(argv[i], "-h") == 0)
            {
              print_help ();
              exit (EXIT_SUCCESS);
            }
          else if (strcmp(argv[i], "--disable-alphablending") == 0)
            {
              settings.alphablending = false;
            }
          else if (strcmp(argv[i], "--disable-antialiasing") == 0
                   || strcmp(argv[i], "-d") == 0)
            {
              settings.antialiasing = false;
            }
          else if (strcmp(argv[i], "--disable-thicklines") == 0
                   || strcmp(argv[i], "-l") == 0)
            {
              settings.thick_lines = false;
            }
          else if (strcmp(argv[i], "--disable-doublebuffer") == 0)
            {
              settings.doublebuffer = false;
            }
          else if (strcmp(argv[i], "--datadir") == 0)
            {
              settings.datadir = argv[++i];
            }
          else if (strcmp(argv[i], "-g") == 0
                   || strcmp(argv[i], "--geometry") == 0)
            {
              if (++i < argc)
                {
                  char c;
                  if (sscanf(argv[i], "%d%c%d", 
                             &settings.screen_width, &c, &settings.screen_height) != 3 && c != 'x')
                    {
                      error ("geometry string must WIDTHxHEIGHT");
                    }                
                }
              else
                {
                  error ("-g/--geometry is missing an argument");
                }
            }
          else
            {
              error (std::string("Unknown option: ") + argv[i]);
            }
        }
      else
        {
          if (!settings.startup_file.empty())
            {
              error ("Only one filename can be given");
            }
          else
            {
              settings.startup_file = argv[i];
            }
        }
    }
}
Exemple #4
0
int main(int argc, char **argv)  {
	int optval = 1;
	int print_help = 0;
	int send_packets = 5;
	int fastmode = 0;
	int c;
	struct sockaddr_in si_me;
	struct mt_packet packet;
	int i;

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);

	while (1) {
		c = getopt(argc, argv, "fs:c:hv?");

		if (c == -1) {
			break;
		}

		switch (c) {
			case 'f':
				fastmode = 1;
				break;

			case 's':
				ping_size = atoi(optarg) - 18;
				break;

			case 'v':
				print_version();
				exit(0);
				break;

			case 'c':
				send_packets = atoi(optarg);
				break;

			case 'h':
			case '?':
				print_help = 1;
				break;

		}
	}

	/* We don't want people to use this for the wrong reasons */
	if (fastmode && (send_packets <= 0 || send_packets > 100)) {
		fprintf(stderr, _("Number of packets to send must be more than 0 and up to 100 in fast mode.\n"));
		return 1;
	}

	if (argc - optind < 1 || print_help) {
		print_version();
		fprintf(stderr, _("Usage: %s <MAC> [-h] [-f] [-c <count>] [-s <packet size>]\n"), argv[0]);

		if (print_help) {
			fprintf(stderr, _("\nParameters:\n"
			"  MAC       MAC-Address of the RouterOS/mactelnetd device.\n"
			"  -f        Fast mode, do not wait before sending next ping request.\n"
			"  -s        Specify size of ping packet.\n"
			"  -c        Number of packets to send. (0 = unlimited)\n"
			"  -h        This help.\n"
			"\n"));
		}
		return 1;
	}

	if (ping_size > ETH_FRAME_LEN - 42) {
		fprintf(stderr, _("Packet size must be between 18 and %d\n"), ETH_FRAME_LEN - 42 + 18);
		exit(1);
	}

	/* Mikrotik RouterOS does not answer unless the packet has the correct recipient mac-address in
	 * the ethernet frame. Unlike real MacTelnet connections where the OS is ok with it being a
	 * broadcast mac address.
	 */
	if (geteuid() != 0) {
		fprintf(stderr, _("You need to have root privileges to use %s.\n"), argv[0]);
		return 1;
	}

	/* Get mac-address from string, or check for hostname via mndp */
	if (!query_mndp_or_mac(argv[optind], dstmac, 1)) {
		/* No valid mac address found, abort */
		return 1;
	}

	sockfd = net_init_raw_socket();

	insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (insockfd < 0) {
		perror("insockfd");
		return 1;
	}

	/* Set initialize address/port */
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(MT_MACTELNET_PORT);
	si_me.sin_addr.s_addr = htonl(INADDR_ANY);

	setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));

	/* Bind to specified address/port */
	if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me))==-1) {
		fprintf(stderr, _("Error binding to %s:%d\n"), inet_ntoa(si_me.sin_addr), MT_MNDP_PORT);
		return 1;
	}

	/* Listen address*/
	inet_pton(AF_INET, (char *)"0.0.0.0", &sourceip);

	/* Set up global info about the connection */
	inet_pton(AF_INET, (char *)"255.255.255.255", &destip);

	srand(time(NULL));

	/* Enumerate available interfaces */
	net_get_interfaces(&interfaces);

	if (ping_size < sizeof(struct timeval)) {
		ping_size = sizeof(struct timeval);
	}

	signal(SIGINT, display_results);

	for (i = 0; i < send_packets || send_packets <= 0; ++i) {
		fd_set read_fds;
		static struct timeval lasttimestamp;
		int reads, result;
		struct timeval timeout;
		int ii;
		int sent = 0;
		int waitforpacket;
		struct timeval timestamp;
		unsigned char pingdata[MT_PACKET_LEN];
		struct net_interface *interface;

		gettimeofday(&timestamp, NULL);
		memcpy(pingdata, &timestamp, sizeof(timestamp));
		for (ii = sizeof(timestamp); ii < ping_size; ++ii) {
			pingdata[ii] = rand() % 256;
		}

		LL_FOREACH(interfaces, interface) {
			if (!interface->has_mac) {
				continue;
			}

			init_pingpacket(&packet, interface->mac_addr, dstmac);
			add_packetdata(&packet, pingdata, ping_size);
			result = net_send_udp(sockfd, interface, interface->mac_addr, dstmac, &sourceip, MT_MACTELNET_PORT, &destip, MT_MACTELNET_PORT, packet.data, packet.size);

			if (result > 0) {
				sent++;
			}

		}
		if (sent == 0) {
			fprintf(stderr, _("Error sending packet.\n"));
			continue;
		}
		ping_sent++;

		FD_ZERO(&read_fds);
		FD_SET(insockfd, &read_fds);

		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		waitforpacket = 1;

		while (waitforpacket) {
			/* Wait for data or timeout */
			reads = select(insockfd+1, &read_fds, NULL, NULL, &timeout);
			if (reads <= 0) {
				waitforpacket = 0;
				fprintf(stderr, _("%s ping timeout\n"), ether_ntoa((struct ether_addr *)&dstmac));
				break;
			}

			unsigned char buff[MT_PACKET_LEN];
			struct sockaddr_in saddress;
			unsigned int slen = sizeof(saddress);
			struct mt_mactelnet_hdr pkthdr;

			result = recvfrom(insockfd, buff, sizeof(buff), 0, (struct sockaddr *)&saddress, &slen);
			/* Check for exact size */
			if (result != 18 + ping_size) {
				continue;
			}
			parse_packet(buff, &pkthdr);

			/* TODO: Check that we are the receiving host */
			if (pkthdr.ptype != MT_PTYPE_PONG) {
				/* Wait for the correct packet */
				continue;
			}
			
			struct timeval pongtimestamp;
			struct timeval nowtimestamp;

			waitforpacket = 0;
			gettimeofday(&nowtimestamp, NULL);

			memcpy(&pongtimestamp, pkthdr.data - 4, sizeof(pongtimestamp));
			if (memcmp(pkthdr.data - 4, pingdata, ping_size) == 0) {
				float diff = toddiff(&nowtimestamp, &pongtimestamp) / 1000.0f;

				if (diff < min_ms) {
					min_ms = diff;
				}

				if (diff > max_ms) {
					max_ms = diff;
				}

				avg_ms += diff;

				printf(_("%s %d byte, ping time %.2f ms%s\n"), ether_ntoa((struct ether_addr *)&(pkthdr.srcaddr)), result, diff, (char *)(memcmp(&pongtimestamp,&lasttimestamp,sizeof(lasttimestamp)) == 0 ? " DUP" : ""));
			} else {
				printf(_("%s Reply of %d bytes of unequal data\n"), ether_ntoa((struct ether_addr *)&(pkthdr.srcaddr)), result);
			}
			pong_received++;
			memcpy(&lasttimestamp, &pongtimestamp, sizeof(pongtimestamp));
			if (!fastmode) {
				sleep(1);
			}
		}
	}

	/* Display statistics and exit */
	display_results();

	return 0;
}
Exemple #5
0
int
main(int argc, char **argv)
{
    gss_OID_set oidset = GSS_C_NULL_OID_SET; 
    gss_OID mechoid = GSS_C_NO_OID;
    OM_uint32 maj_stat, min_stat;
    gss_cred_id_t cred;
    gss_name_t target = GSS_C_NO_NAME;
    int i, optidx = 0;
    OM_uint32 flag;
    gss_OID type;

    setprogname(argv[0]);
    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage (0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (argc != 0)
	usage(1);

    if (acquire_type) {
	if (strcasecmp(acquire_type, "both") == 0)
	    flag = GSS_C_BOTH;
	else if (strcasecmp(acquire_type, "accept") == 0)
	    flag = GSS_C_ACCEPT;
	else if (strcasecmp(acquire_type, "initiate") == 0)
	    flag = GSS_C_INITIATE;
	else
	    errx(1, "unknown type %s", acquire_type);
    } else
	flag = GSS_C_ACCEPT;
	
    if (name_type) {
	if (strcasecmp("hostbased-service", name_type) == 0)
	    type = GSS_C_NT_HOSTBASED_SERVICE;
	else if (strcasecmp("user-name", name_type) == 0)
	    type = GSS_C_NT_USER_NAME;
	else
	    errx(1, "unknown name type %s", name_type);
    } else
	type = GSS_C_NT_HOSTBASED_SERVICE;

    if (ccache) {
	maj_stat = gss_krb5_ccache_name(&min_stat, ccache, NULL);
	if (GSS_ERROR(maj_stat))
	    errx(1, "gss_krb5_ccache_name %s",
		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
    }

    if (kerberos_flag) {
	mechoid = GSS_KRB5_MECHANISM;
	
	maj_stat = gss_create_empty_oid_set(&min_stat, &oidset); 
	if (maj_stat != GSS_S_COMPLETE)
	    errx(1, "gss_create_empty_oid_set: %s",
		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
	
	maj_stat = gss_add_oid_set_member(&min_stat, GSS_KRB5_MECHANISM, &oidset); 
	if (maj_stat != GSS_S_COMPLETE)
	    errx(1, "gss_add_oid_set_member: %s",
		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
    }

    if (target_name) {
	gss_buffer_desc name;

	name.value = target_name; 
	name.length = strlen(target_name); 
	maj_stat = gss_import_name(&min_stat, &name,
				   GSS_C_NT_HOSTBASED_SERVICE, &target); 
	if (maj_stat != GSS_S_COMPLETE)
	    errx(1, "gss_import_name: %s",
		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
    }

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

	cred = acquire_cred_service(acquire_name, type, oidset, flag);

	if (enctype) {
	    int32_t enctypelist = enctype;
	    
	    maj_stat = gss_krb5_set_allowable_enctypes(&min_stat, cred, 
						       1, &enctypelist); 
	    if (maj_stat)
		errx(1, "gss_krb5_set_allowable_enctypes: %s",
		     gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
	}
	
	if (target) {
	    gss_ctx_id_t context = GSS_C_NO_CONTEXT;
	    gss_buffer_desc out;

	    out.length = 0;
	    out.value = NULL;

	    maj_stat = gss_init_sec_context(&min_stat, 
					    cred, &context, 
					    target, mechoid, 
					    GSS_C_MUTUAL_FLAG, 0, NULL,
					    GSS_C_NO_BUFFER, NULL, 
					    &out, NULL, NULL); 
	    if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
		errx(1, "init_sec_context failed: %s",
		     gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));

	    gss_release_buffer(&min_stat, &out);
	    gss_delete_sec_context(&min_stat, &context, NULL);
	}
	gss_release_cred(&min_stat, &cred);
    }


    return 0;
}
Exemple #6
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    char **files;
    int optidx = 0;
    int i;
    krb5_log_facility *logfacility;
    krb5_keytab keytab;
    krb5_socket_t sfd = rk_INVALID_SOCKET;

    setprogname(argv[0]);

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    if (getarg(args, num_args, argc, argv, &optidx)) {
	warnx("error at argument `%s'", argv[optidx]);
	usage(1);
    }

    if (help_flag)
	usage (0);

    if (version_flag) {
	print_version(NULL);
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (config_file == NULL) {
	asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context));
	if (config_file == NULL)
	    errx(1, "out of memory");
    }

    ret = krb5_prepend_config_files_default(config_file, &files);
    if (ret)
	krb5_err(context, 1, ret, "getting configuration files");

    ret = krb5_set_config_files(context, files);
    krb5_free_config_files(files);
    if(ret)
	krb5_err(context, 1, ret, "reading configuration files");

    ret = krb5_openlog(context, "kadmind", &logfacility);
    if (ret)
	krb5_err(context, 1, ret, "krb5_openlog");
    ret = krb5_set_warn_dest(context, logfacility);
    if (ret)
	krb5_err(context, 1, ret, "krb5_set_warn_dest");

    ret = krb5_kt_register(context, &hdb_kt_ops);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_register");

    ret = krb5_kt_resolve(context, keytab_str, &keytab);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_resolve");

    kadm5_setup_passwd_quality_check (context, check_library, check_function);

    for (i = 0; i < policy_libraries.num_strings; i++) {
	ret = kadm5_add_passwd_quality_verifier(context,
						policy_libraries.strings[i]);
	if (ret)
	    krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");
    }
    ret = kadm5_add_passwd_quality_verifier(context, NULL);
    if (ret)
	krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");

    if(debug_flag) {
	int debug_port;

	if(port_str == NULL)
	    debug_port = krb5_getportbyname (context, "kerberos-adm",
					     "tcp", 749);
	else
	    debug_port = htons(atoi(port_str));
	mini_inetd(debug_port, &sfd);
    } else {
#ifdef _WIN32
	pidfile(NULL);
	start_server(context, port_str);
#else
	struct sockaddr_storage __ss;
	struct sockaddr *sa = (struct sockaddr *)&__ss;
	socklen_t sa_size = sizeof(__ss);

	/*
	 * Check if we are running inside inetd or not, if not, start
	 * our own server.
	 */

	if(roken_getsockname(STDIN_FILENO, sa, &sa_size) < 0 &&
	   rk_SOCK_ERRNO == ENOTSOCK) {
	    pidfile(NULL);
	    start_server(context, port_str);
	}
#endif /* _WIN32 */
	sfd = STDIN_FILENO;
    }

    if(realm)
	krb5_set_default_realm(context, realm); /* XXX */

    kadmind_loop(context, keytab, sfd);

    return 0;
}
Exemple #7
0
int
main (int argc,
      char **argv)
{
  GOptionContext *context;
  GError *error = NULL;
  int ret;

  static gboolean opt_packages = FALSE;
  static gboolean opt_version = FALSE;
  static gchar *opt_interactive = NULL;

  static GOptionEntry entries[] = {
    { "interact", 0, 0, G_OPTION_ARG_STRING, &opt_interactive, "Interact with the raw protocol", "boundary" },
    { "packages", 0, 0, G_OPTION_ARG_NONE, &opt_packages, "Show Cockpit package information", NULL },
    { "version", 0, 0, G_OPTION_ARG_NONE, &opt_version, "Show Cockpit version information", NULL },
    { NULL }
  };

  signal (SIGPIPE, SIG_IGN);

  /* Debugging issues during testing */
#if WITH_DEBUG
  signal (SIGABRT, cockpit_test_signal_backtrace);
  signal (SIGSEGV, cockpit_test_signal_backtrace);
#endif

  g_setenv ("GSETTINGS_BACKEND", "memory", TRUE);
  g_setenv ("GIO_USE_PROXY_RESOLVER", "dummy", TRUE);
  g_setenv ("GIO_USE_VFS", "local", TRUE);

  /*
   * All channels that are added here should
   * not rely on running as a real user, however
   * they may lookup paths, such as run dir or
   * home directory. Glib has problems if
   * g_get_user_database_entry is called without
   * a real user, which it's path functions
   * do as a last resort when no environment vars
   * are set. So set HOME if it isn't set..
   */
  g_setenv("HOME", "/", FALSE);


  context = g_option_context_new (NULL);
  g_option_context_add_main_entries (context, entries, NULL);
  g_option_context_set_description (context,
                                    "cockpit-stub provides a limited number of channels and is meant to be"
                                    "used in place of cockpit-bridge in non-system setting. When\n"
                                    "run from the command line one of the options above must be specified.\n");

  g_option_context_parse (context, &argc, &argv, &error);
  g_option_context_free (context);

  if (error)
    {
      g_printerr ("cockpit-stub: %s\n", error->message);
      g_error_free (error);
      return 1;
    }

  if (opt_packages)
    {
      cockpit_packages_dump ();
      return 0;
    }
  else if (opt_version)
    {
      print_version ();
      return 0;
    }

  if (!opt_interactive && isatty (1))
    {
      g_printerr ("cockpit-stub: no option specified\n");
      return 2;
    }

  ret = run_bridge (opt_interactive);

  g_free (opt_interactive);
  return ret;
}
Exemple #8
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;
}
Exemple #9
0
int main(int argc, char **argv)
{
    int test_config = 0;
    int c = 0;
    char *ut_str = NULL;
    const char *dir = DEFAULTDIR;
    const char *cfg = DEFAULTCPATH;
    const char *user = USER;
    const char *group = GROUPGLOBAL;
    uid_t uid;
    gid_t gid;
    int quiet = 0;

    /* Set the name */
    OS_SetName(ARGV0);

    thishour = 0;
    today = 0;
    prev_year = 0;
    full_output = 0;
    alert_only = 0;

    active_responses = NULL;
    memset(prev_month, '\0', 4);

#ifdef LIBGEOIP_ENABLED
    geoipdb = NULL;
#endif

    while ((c = getopt(argc, argv, "VatvdhU:D:c:q")) != -1) {
        switch (c) {
            case 'V':
                print_version();
                break;
            case 't':
                test_config = 1;
                break;
            case 'h':
                help_logtest();
                break;
            case 'd':
                nowDebug();
                break;
            case 'U':
                if (!optarg) {
                    ErrorExit("%s: -U needs an argument", ARGV0);
                }
                ut_str = optarg;
                break;
            case 'D':
                if (!optarg) {
                    ErrorExit("%s: -D needs an argument", ARGV0);
                }
                dir = optarg;
                break;
            case 'c':
                if (!optarg) {
                    ErrorExit("%s: -c needs an argument", ARGV0);
                }
                cfg = optarg;
                break;
            case 'a':
                alert_only = 1;
                break;
            case 'q':
                quiet = 1;
                break;
            case 'v':
                full_output = 1;
                break;
            default:
                help_logtest();
                break;
        }
    }

    /* Read configuration file */
    if (GlobalConf(cfg) < 0) {
        ErrorExit(CONFIG_ERROR, ARGV0, cfg);
    }

    debug1(READ_CONFIG, ARGV0);

#ifdef LIBGEOIP_ENABLED
    Config.geoip_jsonout = getDefine_Int("analysisd", "geoip_jsonout", 0, 1);

    /* Opening GeoIP DB */
    if(Config.geoipdb_file) {
        geoipdb = GeoIP_open(Config.geoipdb_file, GEOIP_INDEX_CACHE);
        if (geoipdb == NULL)
        {
            merror("%s: Unable to open GeoIP database from: %s (disabling GeoIP).", ARGV0, Config.geoipdb_file);
        }
    }
#endif

    /* Get server hostname */
    memset(__shost, '\0', 512);
    if (gethostname(__shost, 512 - 1) != 0) {
        strncpy(__shost, OSSEC_SERVER, 512 - 1);
    } else {
        char *_ltmp;

        /* Remove domain part if available */
        _ltmp = strchr(__shost, '.');
        if (_ltmp) {
            *_ltmp = '\0';
        }
    }

    /* Check if the user/group given are valid */
    uid = Privsep_GetUser(user);
    gid = Privsep_GetGroup(group);
    if (uid == (uid_t) - 1 || gid == (gid_t) - 1) {
        ErrorExit(USER_ERROR, ARGV0, user, group);
    }

    /* Set the group */
    if (Privsep_SetGroup(gid) < 0) {
        ErrorExit(SETGID_ERROR, ARGV0, group, errno, strerror(errno));
    }

    /* Chroot */
    if (Privsep_Chroot(dir) < 0) {
        ErrorExit(CHROOT_ERROR, ARGV0, dir, errno, strerror(errno));
    }
    nowChroot();

    Config.decoder_order_size = (size_t)getDefine_Int("analysisd", "decoder_order_size", 8, MAX_DECODER_ORDER_SIZE);


    /*
     * Anonymous Section: Load rules, decoders, and lists
     *
     * As lists require two pass loading of rules that make use of list lookups
     * are created with blank database structs, and need to be filled in after
     * completion of all rules and lists.
     */
    {
        {
            /* Load decoders */
            /* Initialize the decoders list */
            OS_CreateOSDecoderList();

            if (!Config.decoders) {
                /* Legacy loading */
                /* Read decoders */
                if (!ReadDecodeXML("etc/decoder.xml")) {
                    ErrorExit(CONFIG_ERROR, ARGV0,  XML_DECODER);
                }

                /* Read local ones */
                c = ReadDecodeXML("etc/local_decoder.xml");
                if (!c) {
                    if ((c != -2)) {
                        ErrorExit(CONFIG_ERROR, ARGV0,  XML_LDECODER);
                    }
                } else {
                    verbose("%s: INFO: Reading local decoder file.", ARGV0);
                }
            } else {
                /* New loaded based on file specified in ossec.conf */
                char **decodersfiles;
                decodersfiles = Config.decoders;
                while ( decodersfiles && *decodersfiles) {

                    if(!quiet) {
                        verbose("%s: INFO: Reading decoder file %s.", ARGV0, *decodersfiles);
                    }
                    if (!ReadDecodeXML(*decodersfiles)) {
                        ErrorExit(CONFIG_ERROR, ARGV0, *decodersfiles);
                    }

                    free(*decodersfiles);
                    decodersfiles++;
                }
            }

            /* Load decoders */
            SetDecodeXML();
        }
        {
            /* Load Lists */
            /* Initialize the lists of list struct */
            Lists_OP_CreateLists();
            /* Load each list into list struct */
            {
                char **listfiles;
                listfiles = Config.lists;
                while (listfiles && *listfiles) {
                    verbose("%s: INFO: Reading the lists file: '%s'", ARGV0, *listfiles);
                    if (Lists_OP_LoadList(*listfiles) < 0) {
                        ErrorExit(LISTS_ERROR, ARGV0, *listfiles);
                    }
                    free(*listfiles);
                    listfiles++;
                }
                free(Config.lists);
                Config.lists = NULL;
            }
        }
        {
            /* Load Rules */
            /* Create the rules list */
            Rules_OP_CreateRules();

            /* Read the rules */
            {
                char **rulesfiles;
                rulesfiles = Config.includes;
                while (rulesfiles && *rulesfiles) {
                    debug1("%s: INFO: Reading rules file: '%s'", ARGV0, *rulesfiles);
                    if (Rules_OP_ReadRules(*rulesfiles) < 0) {
                        ErrorExit(RULES_ERROR, ARGV0, *rulesfiles);
                    }

                    free(*rulesfiles);
                    rulesfiles++;
                }

                free(Config.includes);
                Config.includes = NULL;
            }

            /* Find all rules with that require list lookups and attache the
             * the correct list struct to the rule.  This keeps rules from
             * having to search thought the list of lists for the correct file
             * during rule evaluation.
             */
            OS_ListLoadRules();
        }
    }

    /* Fix the levels/accuracy */
    {
        int total_rules;
        RuleNode *tmp_node = OS_GetFirstRule();

        total_rules = _setlevels(tmp_node, 0);
        debug1("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules);
    }

    /* Creating a rules hash (for reading alerts from other servers) */
    {
        RuleNode *tmp_node = OS_GetFirstRule();
        Config.g_rules_hash = OSHash_Create();
        if (!Config.g_rules_hash) {
            ErrorExit(MEM_ERROR, ARGV0, errno, strerror(errno));
        }
        AddHash_Rule(tmp_node);
    }

    if (test_config == 1) {
        exit(0);
    }

    /* Set the user */
    if (Privsep_SetUser(uid) < 0) {
        ErrorExit(SETUID_ERROR, ARGV0, user, errno, strerror(errno));
    }

    /* Start up message */
    verbose(STARTUP_MSG, ARGV0, getpid());

    /* Going to main loop */
    OS_ReadMSG(ut_str);

    exit(0);
}
Exemple #10
0
  int main(int argc, char *argv[])
  {
    int i, j;
    struct rlimit rlb;
    char *arg;
    pthread_t tid;
    pthread_attr_t pab;
    
    int yu_tmp_len;
    int depth = 0;
    argv0 = argv[0];

    //setlocale(LC_CTYPE, "");

    getrlimit(RLIMIT_NOFILE, &rlb);
    rlb.rlim_cur = rlb.rlim_max;
    setrlimit(RLIMIT_NOFILE, &rlb);

    signal(SIGPIPE, SIG_IGN);

    nworkers = 2;

    pthread_mutex_init(&print_lock, NULL);
    pthread_mutex_init(&aworker_lock, NULL);
    pthread_mutex_init(&matches_lock, NULL);
    
    pthread_cond_init(&aworker_cv, NULL);

    for (i = 1; i < argc && argv[i][0] == '-'; i++)
      for (j = 1; j > 0 && argv[i][j]; ++j)
        switch (argv[i][j])
      {
        case '-':  ++i; goto EndOptions;

        case 'V': print_version(stdout);  break;
        case 'd':   ++debug;    break;
        case 'i':   ignore_case = 1;    break;

        case 'v':
        ++verbose;
        break;

        case 'h':
        usage(stdout);
        exit(0);

        case 'l':
        ++line_f;
        break;

        case 'L':
        if (argv[i][2])  arg = argv[i]+2;
        else  arg = argv[++i];

        if (!arg || sscanf(arg, "%u", &maxlen) != 1){
          fprintf(stderr, "%s: Invalid length specification: %s\n", argv[0], arg ? arg : "<null>");
          exit(1);
        }
        j = -2;
        break;

        case 'n':
        if (argv[i][2])  arg = argv[i]+2;  else   arg = argv[++i];    
        if (!arg || sscanf(arg, "%u", &nworkers) != 1){
          fprintf(stderr,"%s: Invalid workers specification: %s\n",  argv[0], arg ? arg : "<null>");
          exit(1);
        }
        j = -2;
        break;

        default:
        fprintf(stderr, "%s: unknown command line switch: -%c\n",
          argv[0], argv[i][j]);
        exit(1);
      }

      EndOptions:

      yu_tmp_len = strlen(argv[i]) + 1;
      rstr = (unsigned char*) malloc( yu_tmp_len * sizeof(unsigned char));


    strcpy(rstr, argv[i]); //, yu_tmp_len);    
i++;

rlen = deslash(rstr);

if (bm_init(&bmb, rstr, rlen, ignore_case) < 0)
{
  fprintf(stderr, "%s: Failed search string setup: %s\n",
    argv[0], rstr);
  exit(1);
}

max_depth = rlb.rlim_max - nworkers - 16;

if (debug)
  fprintf(stderr, "max_depth = %d, nworkers = %d\n", max_depth,
    nworkers);

pqueue_init(&pqb, nworkers + 8);

pthread_attr_init(&pab);
pthread_attr_setscope(&pab, PTHREAD_SCOPE_SYSTEM);

aworkers = nworkers;

for (j = 0; j < nworkers; ++j)
  if (pthread_create(&tid, &pab, worker, NULL) != 0)
  {
    fprintf(stderr, "%s: pthread_create: failed to create worker thread\n",
      argv[0]);
    exit(1);
  }

    //while (i < argc && do_ftw(argv[i++]) == 0)
  //;
  for (; i < argc; i++) {
    scan_root(argv[i], argv[i], &depth, max_depth);
  }
  pqueue_close(&pqb);

  if (debug)
    fprintf(stderr, "Waiting for workers to finish...\n");

  pthread_mutex_lock(&aworker_lock);
  while (aworkers > 0)
    pthread_cond_wait(&aworker_cv, &aworker_lock);
  pthread_mutex_unlock(&aworker_lock);

  if (debug)
    fprintf(stderr, "n_files = %d, n_matches = %d, n_workers = %d, n_Mbytes = %d\n",
      n_files, n_matches, nworkers,
      (int) (n_bytes / 1000000));

    //pthread_exit(0);
  return n_matches;
}
Exemple #11
0
int main(int argc, char **argv)
{
	const struct optstruct *opt;
#ifndef	C_WINDOWS
        struct passwd *user = NULL;
#endif
	time_t currtime;
	const char *dbdir, *cfgfile;
	char *pua_cats = NULL, *pt;
	int ret, tcpsock = 0, localsock = 0, i, min_port, max_port;
	unsigned int sigs = 0;
	int lsockets[2], nlsockets = 0;
	unsigned int dboptions = 0;
#ifdef C_LINUX
	struct stat sb;
#endif

#ifdef C_WINDOWS
    if(!pthread_win32_process_attach_np()) {
	mprintf("!Can't start the win32 pthreads layer\n");
        return 1;
    }
#endif

    if((opts = optparse(NULL, argc, argv, 1, OPT_CLAMD, 0, NULL)) == NULL) {
	mprintf("!Can't parse command line options\n");
	return 1;
    }

    if(optget(opts, "help")->enabled) {
    	help();
	optfree(opts);
	return 0;
    }

    if(optget(opts, "debug")->enabled) {
#if defined(C_LINUX)
	    /* [email protected]: create a dump if needed */
	    struct rlimit rlim;

	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
	if(setrlimit(RLIMIT_CORE, &rlim) < 0)
	    perror("setrlimit");
#endif
	debug_mode = 1;
    }

    /* parse the config file */
    cfgfile = optget(opts, "config-file")->strarg;
    pt = strdup(cfgfile);
    if((opts = optparse(cfgfile, 0, NULL, 1, OPT_CLAMD, 0, opts)) == NULL) {
	fprintf(stderr, "ERROR: Can't open/parse the config file %s\n", pt);
	free(pt);
	return 1;
    }
    free(pt);

    if(optget(opts, "version")->enabled) {
	print_version(optget(opts, "DatabaseDirectory")->strarg);
	optfree(opts);
	return 0;
    }

    umask(0);

    /* drop privileges */
#if (!defined(C_OS2)) && (!defined(C_WINDOWS))
    if(geteuid() == 0 && (opt = optget(opts, "User"))->enabled) {
	if((user = getpwnam(opt->strarg)) == NULL) {
	    fprintf(stderr, "ERROR: Can't get information about user %s.\n", opt->strarg);
	    optfree(opts);
	    return 1;
	}

	if(optget(opts, "AllowSupplementaryGroups")->enabled) {
#ifdef HAVE_INITGROUPS
	    if(initgroups(opt->strarg, user->pw_gid)) {
		fprintf(stderr, "ERROR: initgroups() failed.\n");
		optfree(opts);
		return 1;
	    }
#else
	    mprintf("!AllowSupplementaryGroups: initgroups() is not available, please disable AllowSupplementaryGroups in %s\n", cfgfile);
	    optfree(opts);
	    return 1;
#endif
	} else {
#ifdef HAVE_SETGROUPS
	    if(setgroups(1, &user->pw_gid)) {
		fprintf(stderr, "ERROR: setgroups() failed.\n");
		optfree(opts);
		return 1;
	    }
#endif
	}

	if(setgid(user->pw_gid)) {
	    fprintf(stderr, "ERROR: setgid(%d) failed.\n", (int) user->pw_gid);
	    optfree(opts);
	    return 1;
	}

	if(setuid(user->pw_uid)) {
	    fprintf(stderr, "ERROR: setuid(%d) failed.\n", (int) user->pw_uid);
	    optfree(opts);
	    return 1;
	}
    }
#endif

    /* initialize logger */
    logg_lock = !optget(opts, "LogFileUnlock")->enabled;
    logg_time = optget(opts, "LogTime")->enabled;
    logok = optget(opts, "LogClean")->enabled;
    logg_size = optget(opts, "LogFileMaxSize")->numarg;
    logg_verbose = mprintf_verbose = optget(opts, "LogVerbose")->enabled;
    mprintf_send_timeout = optget(opts, "SendBufTimeout")->numarg;

    do { /* logger initialized */

    if((opt = optget(opts, "LogFile"))->enabled) {
	char timestr[32];
	logg_file = opt->strarg;
	if(strlen(logg_file) < 2 || (logg_file[0] != '/' && logg_file[0] != '\\' && logg_file[1] != ':')) {
	    fprintf(stderr, "ERROR: LogFile requires full path.\n");
	    ret = 1;
	    break;
	}
	time(&currtime);
	if(logg("#+++ Started at %s", cli_ctime(&currtime, timestr, sizeof(timestr)))) {
	    fprintf(stderr, "ERROR: Can't initialize the internal logger\n");
	    ret = 1;
	    break;
	}
    } else
	logg_file = NULL;

    if((ret = cl_init(CL_INIT_DEFAULT))) {
	logg("!Can't initialize libclamav: %s\n", cl_strerror(ret));
	ret = 1;
	break;
    }

    if(optget(opts, "Debug")->enabled) /* enable debug messages in libclamav */ {
	cl_debug();
	logg_verbose = 2;
    }

#if defined(USE_SYSLOG) && !defined(C_AIX)
    if(optget(opts, "LogSyslog")->enabled) {
	    int fac = LOG_LOCAL6;

	opt = optget(opts, "LogFacility");
	if((fac = logg_facility(opt->strarg)) == -1) {
	    logg("!LogFacility: %s: No such facility.\n", opt->strarg);
	    ret = 1;
	    break;
	}

	openlog("clamd", LOG_PID, fac);
	logg_syslog = 1;
    }
#endif

#ifdef C_LINUX
    procdev = 0;
    if(stat("/proc", &sb) != -1 && !sb.st_size)
	procdev = sb.st_dev;
#endif

    /* check socket type */

    if(optget(opts, "TCPSocket")->enabled)
	tcpsock = 1;

    if(optget(opts, "LocalSocket")->enabled)
	localsock = 1;

    if(!tcpsock && !localsock) {
	logg("!Please define server type (local and/or TCP).\n");
	ret = 1;
	break;
    }

    logg("#clamd daemon %s (OS: "TARGET_OS_TYPE", ARCH: "TARGET_ARCH_TYPE", CPU: "TARGET_CPU_TYPE")\n", get_version());

#ifndef C_WINDOWS
    if(user)
	logg("#Running as user %s (UID %u, GID %u)\n", user->pw_name, user->pw_uid, user->pw_gid);
#endif

    if(logg_size)
	logg("#Log file size limited to %d bytes.\n", logg_size);
    else
	logg("#Log file size limit disabled.\n");

    min_port = optget(opts, "StreamMinPort")->numarg;
    max_port = optget(opts, "StreamMaxPort")->numarg;
    if (min_port < 1024 || min_port > max_port || max_port > 65535) {
	logg("!Invalid StreamMinPort/StreamMaxPort: %d, %d\n", min_port, max_port);
	ret = 1;
	break;
    }

    if(!(engine = cl_engine_new())) {
	logg("!Can't initialize antivirus engine\n");
	ret = 1;
	break;
    }

    /* load the database(s) */
    dbdir = optget(opts, "DatabaseDirectory")->strarg;
    logg("#Reading databases from %s\n", dbdir);

    if(optget(opts, "DetectPUA")->enabled) {
	dboptions |= CL_DB_PUA;

	if((opt = optget(opts, "ExcludePUA"))->enabled) {
	    dboptions |= CL_DB_PUA_EXCLUDE;
	    i = 0;
	    logg("#Excluded PUA categories:");
	    while(opt) {
		if(!(pua_cats = realloc(pua_cats, i + strlen(opt->strarg) + 3))) {
		    logg("!Can't allocate memory for pua_cats\n");
		    cl_engine_free(engine);
		    ret = 1;
		    break;
		}
		logg("# %s", opt->strarg);
		sprintf(pua_cats + i, ".%s", opt->strarg);
		i += strlen(opt->strarg) + 1;
		pua_cats[i] = 0;
		opt = opt->nextarg;
	    }
	    if (ret)
		break;
	    logg("#\n");
	    pua_cats[i] = '.';
	    pua_cats[i + 1] = 0;
	}

	if((opt = optget(opts, "IncludePUA"))->enabled) {
	    if(pua_cats) {
		logg("!ExcludePUA and IncludePUA cannot be used at the same time\n");
		free(pua_cats);
		ret = 1;
		break;
	    }
	    dboptions |= CL_DB_PUA_INCLUDE;
	    i = 0;
	    logg("#Included PUA categories:");
	    while(opt) {
		if(!(pua_cats = realloc(pua_cats, i + strlen(opt->strarg) + 3))) {
		    logg("!Can't allocate memory for pua_cats\n");
		    ret = 1;
		    break;
		}
		logg("# %s", opt->strarg);
		sprintf(pua_cats + i, ".%s", opt->strarg);
		i += strlen(opt->strarg) + 1;
		pua_cats[i] = 0;
		opt = opt->nextarg;
	    }
	    if (ret)
		break;
	    logg("#\n");
	    pua_cats[i] = '.';
	    pua_cats[i + 1] = 0;
	}

	if(pua_cats) {
	    if((ret = cl_engine_set_str(engine, CL_ENGINE_PUA_CATEGORIES, pua_cats))) {
		logg("!cli_engine_set_str(CL_ENGINE_PUA_CATEGORIES) failed: %s\n", cl_strerror(ret));
		free(pua_cats);
		ret = 1;
		break;
	    }
	    free(pua_cats);
	}
    } else {
	logg("#Not loading PUA signatures.\n");
    }

    /* set the temporary dir */
    if((opt = optget(opts, "TemporaryDirectory"))->enabled) {
	if((ret = cl_engine_set_str(engine, CL_ENGINE_TMPDIR, opt->strarg))) {
	    logg("!cli_engine_set_str(CL_ENGINE_TMPDIR) failed: %s\n", cl_strerror(ret));
	    ret = 1;
	    break;
	}
    }

    if(optget(opts, "LeaveTemporaryFiles")->enabled)
	cl_engine_set_num(engine, CL_ENGINE_KEEPTMP, 1);

    if(optget(opts, "PhishingSignatures")->enabled)
	dboptions |= CL_DB_PHISHING;
    else
	logg("#Not loading phishing signatures.\n");

    if(optget(opts,"PhishingScanURLs")->enabled)
	dboptions |= CL_DB_PHISHING_URLS;
    else
	logg("#Disabling URL based phishing detection.\n");

    if(optget(opts,"DevACOnly")->enabled) {
	logg("#Only using the A-C matcher.\n");
	cl_engine_set_num(engine, CL_ENGINE_AC_ONLY, 1);
    }

    if((opt = optget(opts, "DevACDepth"))->enabled) {
        cl_engine_set_num(engine, CL_ENGINE_AC_MAXDEPTH, opt->numarg);
	logg("#Max A-C depth set to %u\n", (unsigned int) opt->numarg);
    }

    if((ret = cl_load(dbdir, engine, &sigs, dboptions))) {
	logg("!%s\n", cl_strerror(ret));
	ret = 1;
	break;
    }

    logg("#Loaded %u signatures.\n", sigs);
    if((ret = cl_engine_compile(engine)) != 0) {
	logg("!Database initialization error: %s\n", cl_strerror(ret));
	ret = 1;
	break;
    }

    if(tcpsock) {
#ifdef C_WINDOWS
	    WSADATA wsaData;

	if(WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) {
	    logg("!Error at WSAStartup(): %d\n", WSAGetLastError());
	    ret = 1;
	    break;
	}
#endif
	if ((lsockets[nlsockets] = tcpserver(opts)) == -1) {
	    ret = 1;
	    break;
	}
	nlsockets++;
    }

    if(localsock) {
	if ((lsockets[nlsockets] = localserver(opts)) == -1) {
	    ret = 1;
	    break;
	}
	nlsockets++;
    }

    /* fork into background */
    if(!optget(opts, "Foreground")->enabled) {
#ifdef C_BSD	    
	/* workaround for OpenBSD bug, see https://wwws.clamav.net/bugzilla/show_bug.cgi?id=885 */
	for(ret=0;ret<nlsockets;ret++) {
		fcntl(lsockets[ret], F_SETFL, fcntl(lsockets[ret], F_GETFL) | O_NONBLOCK);
	}
#endif
	if(daemonize() == -1) {
	    logg("!daemonize() failed\n");
	    ret = 1;
	    break;
	}
#ifdef C_BSD
	for(ret=0;ret<nlsockets;ret++) {
		fcntl(lsockets[ret], F_SETFL, fcntl(lsockets[ret], F_GETFL) & ~O_NONBLOCK);
	}
#endif
	if(!debug_mode)
	    if(chdir("/") == -1)
		logg("^Can't change current working directory to root\n");

    } else
        foreground = 1;

    ret = recvloop_th(lsockets, nlsockets, engine, dboptions, opts);

    } while (0);

    logg("*Closing the main socket%s.\n", (nlsockets > 1) ? "s" : "");

    for (i = 0; i < nlsockets; i++) {
	closesocket(lsockets[i]);
    }

#ifndef C_OS2
    if(nlsockets && localsock) {
	opt = optget(opts, "LocalSocket");
	if(unlink(opt->strarg) == -1)
	    logg("!Can't unlink the socket file %s\n", opt->strarg);
	else
	    logg("Socket file removed.\n");
    }
#endif

#ifdef C_WINDOWS
    if(tcpsock)
	WSACleanup();

    if(!pthread_win32_process_detach_np()) {
	logg("!Can't stop the win32 pthreads layer\n");
	logg_close();
	optfree(opts);
	return 1;
    }
#endif

    logg_close();
    optfree(opts);

    return ret;
}
int
main (int argc, char **argv)
{
  extern int chdir (char *);
  char *srcdir = NULL;
  int c;
  FILE *table;

  program_name = *argv;
  xmalloc_set_program_name (program_name);

  while ((c = getopt_long (argc, argv, "vVdh", long_options, 0)) != EOF)
    switch (c)
      {
      case OPTION_SRCDIR:
	srcdir = optarg;
	break;
      case 'V':
      case 'v':
	print_version ();
	break;
      case 'd':
	debug = 1;
	break;
      case 'h':
      case '?':
	usage (stderr, 0);
      default:
      case 0:
	break;
      }

  if (optind != argc)
    usage (stdout, 1);

  if (srcdir != NULL)
    if (chdir (srcdir) != 0)
      fail (_("unable to change directory to \"%s\", errno = %s\n"),
	    srcdir, xstrerror (errno));

  /* Check the unused bitfield in i386_cpu_flags.  */
#ifndef CpuUnused
  c = CpuNumOfBits - CpuMax - 1;
  if (c)
    fail (_("%d unused bits in i386_cpu_flags.\n"), c);
#endif

  /* Check the unused bitfield in i386_operand_type.  */
#ifndef OTUnused
  c = OTNumOfBits - OTMax - 1;
  if (c)
    fail (_("%d unused bits in i386_operand_type.\n"), c);
#endif

  qsort (cpu_flags, ARRAY_SIZE (cpu_flags), sizeof (cpu_flags [0]),
	 compare);

  qsort (opcode_modifiers, ARRAY_SIZE (opcode_modifiers),
	 sizeof (opcode_modifiers [0]), compare);

  qsort (operand_types, ARRAY_SIZE (operand_types),
	 sizeof (operand_types [0]), compare);

  table = fopen ("i386-tbl.h", "w");
  if (table == NULL)
    fail (_("can't create i386-tbl.h, errno = %s\n"),
	  xstrerror (errno));

  process_copyright (table);

  process_i386_opcodes (table);
  process_i386_registers (table);
  process_i386_initializers ();

  fclose (table);

  exit (0);
}
Exemple #13
0
void svr_getopts(int argc, char ** argv) {

	unsigned int i;
	char ** next = 0;
	int nextisport = 0;
	char* recv_window_arg = NULL;
	char* keepalive_arg = NULL;
	char* idle_timeout_arg = NULL;
	char* keyfile = NULL;


	/* see printhelp() for options */
	svr_opts.bannerfile = NULL;
	svr_opts.banner = NULL;
	svr_opts.forkbg = 1;
	svr_opts.norootlogin = 0;
	svr_opts.noauthpass = 0;
	svr_opts.norootpass = 0;
	svr_opts.allowblankpass = 0;
	svr_opts.inetdmode = 0;
	svr_opts.portcount = 0;
	svr_opts.hostkey = NULL;
	svr_opts.delay_hostkey = 0;
	svr_opts.pidfile = DROPBEAR_PIDFILE;
#ifdef ENABLE_SVR_LOCALTCPFWD
	svr_opts.nolocaltcp = 0;
#endif
#ifdef ENABLE_SVR_REMOTETCPFWD
	svr_opts.noremotetcp = 0;
#endif

#ifndef DISABLE_ZLIB
#if DROPBEAR_SERVER_DELAY_ZLIB
	opts.compress_mode = DROPBEAR_COMPRESS_DELAYED;
#else
	opts.compress_mode = DROPBEAR_COMPRESS_ON;
#endif
#endif 

	/* not yet
	opts.ipv4 = 1;
	opts.ipv6 = 1;
	*/
#ifdef DO_MOTD
	svr_opts.domotd = 1;
#endif
#ifndef DISABLE_SYSLOG
	svr_opts.usingsyslog = 1;
#endif
	opts.recv_window = DEFAULT_RECV_WINDOW;
	opts.keepalive_secs = DEFAULT_KEEPALIVE;
	opts.idle_timeout_secs = DEFAULT_IDLE_TIMEOUT;
	
#ifdef ENABLE_SVR_REMOTETCPFWD
	opts.listen_fwd_all = 0;
#endif

	for (i = 1; i < (unsigned int)argc; i++) {
		if (nextisport) {
			addportandaddress(argv[i]);
			nextisport = 0;
			continue;
		}
	  
		if (next) {
			*next = argv[i];
			if (*next == NULL) {
				dropbear_exit("Invalid null argument");
			}
			next = 0x00;

			if (keyfile) {
				addhostkey(keyfile);
				keyfile = NULL;
			}
			continue;
		}

		if (argv[i][0] == '-') {
			char c = argv[i][1];
			if (strlen(argv[i]) != 2) {
				/* We only handle one flag per hyphen */
				fprintf(stderr, "Warning, trailing '%s' of '%s' is ignored.\n",
					&argv[i][2], argv[i]);
			}
			switch (c) {
				case 'b':
					next = &svr_opts.bannerfile;
					break;
				case 'd':
				case 'r':
					next = &keyfile;
					break;
				case 'R':
					svr_opts.delay_hostkey = 1;
					break;
				case 'F':
					svr_opts.forkbg = 0;
					break;
#ifndef DISABLE_SYSLOG
				case 'E':
					svr_opts.usingsyslog = 0;
					break;
#endif
#ifdef ENABLE_SVR_LOCALTCPFWD
				case 'j':
					svr_opts.nolocaltcp = 1;
					break;
#endif
#ifdef ENABLE_SVR_REMOTETCPFWD
				case 'k':
					svr_opts.noremotetcp = 1;
					break;
				case 'a':
					opts.listen_fwd_all = 1;
					break;
#endif
#ifdef INETD_MODE
				case 'i':
					svr_opts.inetdmode = 1;
					break;
#endif
				case 'p':
				  nextisport = 1;
				  break;
				case 'P':
					next = &svr_opts.pidfile;
					break;
#ifdef DO_MOTD
				/* motd is displayed by default, -m turns it off */
				case 'm':
					svr_opts.domotd = 0;
					break;
#endif
				case 'w':
					svr_opts.norootlogin = 1;
					break;
				case 'W':
					next = &recv_window_arg;
					break;
				case 'K':
					next = &keepalive_arg;
					break;
				case 'I':
					next = &idle_timeout_arg;
					break;
#if defined(ENABLE_SVR_PASSWORD_AUTH) || defined(ENABLE_SVR_PAM_AUTH)
				case 's':
					svr_opts.noauthpass = 1;
					break;
				case 'g':
					svr_opts.norootpass = 1;
					break;
				case 'B':
					svr_opts.allowblankpass = 1;
					break;
#endif
				case 'h':
					printhelp(argv[0]);
					exit(EXIT_SUCCESS);
					break;
				case 'u':
					/* backwards compatibility with old urandom option */
					break;
#ifdef DEBUG_TRACE
				case 'v':
					debug_trace = 1;
					break;
#endif
				case 'V':
					print_version();
					exit(EXIT_SUCCESS);
					break;
				default:
					fprintf(stderr, "Unknown argument %s\n", argv[i]);
					printhelp(argv[0]);
					exit(EXIT_FAILURE);
					break;
			}
		}
	}

	/* Set up listening ports */
	if (svr_opts.portcount == 0) {
		svr_opts.ports[0] = m_strdup(DROPBEAR_DEFPORT);
		svr_opts.addresses[0] = m_strdup(DROPBEAR_DEFADDRESS);
		svr_opts.portcount = 1;
	}

	if (svr_opts.bannerfile) {
		struct stat buf;
		if (stat(svr_opts.bannerfile, &buf) != 0) {
			dropbear_exit("Error opening banner file '%s'",
					svr_opts.bannerfile);
		}
		
		if (buf.st_size > MAX_BANNER_SIZE) {
			dropbear_exit("Banner file too large, max is %d bytes",
					MAX_BANNER_SIZE);
		}

		svr_opts.banner = buf_new(buf.st_size);
		if (buf_readfile(svr_opts.banner, svr_opts.bannerfile)!=DROPBEAR_SUCCESS) {
			dropbear_exit("Error reading banner file '%s'",
					svr_opts.bannerfile);
		}
		buf_setpos(svr_opts.banner, 0);
	}
	
	if (recv_window_arg) {
		opts.recv_window = atol(recv_window_arg);
		if (opts.recv_window == 0 || opts.recv_window > MAX_RECV_WINDOW) {
			dropbear_exit("Bad recv window '%s'", recv_window_arg);
		}
	}
	
	if (keepalive_arg) {
		unsigned int val;
		if (m_str_to_uint(keepalive_arg, &val) == DROPBEAR_FAILURE) {
			dropbear_exit("Bad keepalive '%s'", keepalive_arg);
		}
		opts.keepalive_secs = val;
	}

	if (idle_timeout_arg) {
		unsigned int val;
		if (m_str_to_uint(idle_timeout_arg, &val) == DROPBEAR_FAILURE) {
			dropbear_exit("Bad idle_timeout '%s'", idle_timeout_arg);
		}
		opts.idle_timeout_secs = val;
	}
}
Exemple #14
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;
}
Exemple #15
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;
}
Exemple #16
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;
}
Exemple #17
0
void
kcm_configure(int argc, char **argv)
{
    krb5_error_code ret;
    int optind = 0;
    const char *p;

    while(getarg(args, num_args, argc, argv, &optind))
	warnx("error at argument `%s'", argv[optind]);

    if(help_flag)
	usage (0);

    if (version_flag) {
	print_version(NULL);
	exit(0);
    }

    argc -= optind;
    argv += optind;

    if (argc != 0)
	usage(1);

    {
	char **files;

	if(config_file == NULL)
	    config_file = _PATH_KCM_CONF;

	ret = krb5_prepend_config_files_default(config_file, &files);
	if (ret)
	    krb5_err(kcm_context, 1, ret, "getting configuration files");

	ret = krb5_set_config_files(kcm_context, files);
	krb5_free_config_files(files);
	if(ret)
	    krb5_err(kcm_context, 1, ret, "reading configuration files");
    }

    if(max_request_str)
	max_request = parse_bytes(max_request_str, NULL);

    if(max_request == 0){
	p = krb5_config_get_string (kcm_context,
				    NULL,
				    "kcm",
				    "max-request",
				    NULL);
	if(p)
	    max_request = parse_bytes(p, NULL);
    }

    if (system_principal == NULL) {
	system_principal = kcm_system_config_get_string("principal");
    }

    if (system_principal != NULL) {
	ret = ccache_init_system();
	if (ret)
	    krb5_err(kcm_context, 1, ret, "initializing system ccache");
    }

#ifdef SUPPORT_DETACH
    if(detach_from_console == -1)
	detach_from_console = krb5_config_get_bool_default(kcm_context, NULL,
							   DETACH_IS_DEFAULT,
							   "kcm",
							   "detach", NULL);
#endif
    kcm_openlog();
    if(max_request == 0)
	max_request = 64 * 1024;
}
Exemple #18
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);
}
Exemple #19
0
int
main(int ac, char **av)
{
  bfd *abfd;
  struct coff_ofile *tree;
  char **matching;
  char *input_file = NULL;
  int opt;
  static struct option long_options[] =
    {
      { "help", no_argument, 0, 'h' },
      { "version", no_argument, 0, 'V' },
      { NULL, no_argument, 0, 0 }
    };

#if defined(HAVE_SETLOCALE) && defined(HAVE_LC_MESSAGES)
  setlocale(LC_MESSAGES, "");
#endif /* HAVE_SETLOCALE && HAVE_LC_MESSAGES */
#if defined(HAVE_SETLOCALE)
  setlocale(LC_CTYPE, "");
#endif /* HAVE_SETLOCALE */
  bindtextdomain(PACKAGE, LOCALEDIR);
  textdomain(PACKAGE);

  program_name = av[0];
  xmalloc_set_program_name (program_name);

  while ((opt = getopt_long(ac, av, "HhVv", long_options,
                            (int *)NULL)) != EOF)
    {
      switch (opt)
	{
	case 'H':
	case 'h':
	  show_usage(stdout, 0);
	  break;
	case 'v':
	case 'V':
	  print_version("coffdump");
	  xexit(0);
	case 0:
	  break;
	default:
	  show_usage(stderr, 1);
	  break;
	}
    }

  if (optind < ac)
    {
      input_file = av[optind];
    }

  if (!input_file)
    fatal(_("no input file specified"));

  abfd = bfd_openr(input_file, 0);

  if (!abfd)
    bfd_fatal(input_file);

  if (! bfd_check_format_matches(abfd, bfd_object, &matching))
    {
      bfd_nonfatal(input_file);

      if (bfd_get_error() == bfd_error_file_ambiguously_recognized)
	{
	  list_matching_formats(matching);
	  free(matching);
	}
      xexit(1);
    }

  tree = coff_grok(abfd);

  coff_dump(tree);
  printf("\n");

  return 0;
}
Exemple #20
0
int main(int argc, char **argv)
{
	int c;			/* for getopt */
	int start = 0;
	size_t length = 0;

	static const struct option longopts[] = {
		{"verbose",   no_argument,       NULL, 'v'},
		{"version",   no_argument,       NULL, 'V'},
		{"help",      no_argument,       NULL, 'h'},
		{"blocksize", required_argument, NULL, 'b'},
		{"extract",   optional_argument, NULL, 'x'},
		{NULL, 0, NULL, 0},
	};

	setlocale(LC_MESSAGES, "");
	setlocale(LC_CTYPE, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	close_stdout_atexit();

	strutils_set_exitcode(FSCK_EX_USAGE);

	/* command line options */
	while ((c = getopt_long(argc, argv, "ayvVhb:", longopts, NULL)) != EOF)
		switch (c) {
		case 'a':		/* ignore */
		case 'y':
			break;
		case 'h':
			usage();
			break;
		case 'V':
			print_version(FSCK_EX_OK);
		case 'x':
			opt_extract = 1;
			if(optarg)
				extract_dir = optarg;
			break;
		case 'v':
			opt_verbose++;
			break;
		case 'b':
			blksize = strtou32_or_err(optarg, _("invalid blocksize argument"));
			break;
		default:
			errtryhelp(FSCK_EX_USAGE);
		}

	if ((argc - optind) != 1){
		warnx(_("bad usage"));
		errtryhelp(FSCK_EX_USAGE);
	}
	filename = argv[optind];

	test_super(&start, &length);
	test_crc(start);

	if(opt_extract) {
		if (blksize == 0)
			blksize = getpagesize();
		outbuffer = xmalloc(blksize * 2);
		test_fs(start);
	}

	if (opt_verbose)
		printf(_("%s: OK\n"), filename);

	exit(FSCK_EX_OK);
}
Exemple #21
0
int main(int argc, char **argv)
{
	blkid_cache cache = NULL;
	char *devices[128] = { NULL, };
	char *show[128] = { NULL, };
	char *search_type = NULL, *search_value = NULL;
	char *read = NULL;
	char *write = NULL;
	unsigned int numdev = 0, numtag = 0;
	int version = 0;
	int err = 4;
	unsigned int i;
	int output_format = 0;
	int lookup = 0;
	int c;

	while ((c = getopt (argc, argv, "c:f:hlo:s:t:w:v")) != EOF)
		switch (c) {
		case 'c':
			if (optarg && !*optarg)
				read = NULL;
			else
				read = optarg;
			if (!write)
				write = read;
			break;
		case 'l':
			lookup++;
			break;
		case 'o':
			if (!strcmp(optarg, "value"))
				output_format = OUTPUT_VALUE_ONLY;
			else if (!strcmp(optarg, "device"))
				output_format = OUTPUT_DEVICE_ONLY;
			else if (!strcmp(optarg, "full"))
				output_format = 0;
			else {
				fprintf(stderr, "Invalid output format %s.  Chose from value, device, or full\n", optarg);
				exit(1);
			}
			break;
		case 's':
			if (numtag >= sizeof(show) / sizeof(*show)) {
				fprintf(stderr, "Too many tags specified\n");
				usage(err);
			}
			show[numtag++] = optarg;
			break;
		case 't':
			if (search_type) {
				fprintf(stderr, "Can only search for "
						"one NAME=value pair\n");
				usage(err);
			}
			if (blkid_parse_tag_string(optarg,
						   &search_type,
						   &search_value)) {
				fprintf(stderr, "-t needs NAME=value pair\n");
				usage(err);
			}
			break;
		case 'v':
			version = 1;
			break;
		case 'w':
			if (optarg && !*optarg)
				write = NULL;
			else
				write = optarg;
			break;
		case 'h':
			err = 0;
		default:
			usage(err);
		}

	while (optind < argc)
		devices[numdev++] = argv[optind++];

	if (version) {
		print_version(stdout);
		goto exit;
	}

	if (blkid_get_cache(&cache, read) < 0)
		goto exit;

	err = 2;
	if (lookup) {
		blkid_dev dev;

		if (!search_type) {
			fprintf(stderr, "The lookup option requires a "
				"search type specified using -t\n");
			exit(1);
		}
		/* Load any additional devices not in the cache */
		for (i = 0; i < numdev; i++)
			blkid_get_dev(cache, devices[i], BLKID_DEV_NORMAL);

		if ((dev = blkid_find_dev_with_tag(cache, search_type,
						   search_value))) {
			print_tags(dev, show, numtag, output_format);
			err = 0;
		}
	/* If we didn't specify a single device, show all available devices */
	} else if (!numdev) {
		blkid_dev_iterate	iter;
		blkid_dev		dev;

		blkid_probe_all(cache);

		iter = blkid_dev_iterate_begin(cache);
		blkid_dev_set_search(iter, search_type, search_value);
		while (blkid_dev_next(iter, &dev) == 0) {
			dev = blkid_verify(cache, dev);
			if (!dev)
				continue;
			print_tags(dev, show, numtag, output_format);
			err = 0;
		}
		blkid_dev_iterate_end(iter);
	/* Add all specified devices to cache (optionally display tags) */
	} else for (i = 0; i < numdev; i++) {
		blkid_dev dev = blkid_get_dev(cache, devices[i],
						  BLKID_DEV_NORMAL);

		if (dev) {
			if (search_type && 
			    !blkid_dev_has_tag(dev, search_type, 
					       search_value))
				continue;
			print_tags(dev, show, numtag, output_format);
			err = 0;
		}
	}

exit:
	if (search_type)
		free(search_type);
	if (search_value)
		free(search_value);
	blkid_put_cache(cache);
	return err;
}
Exemple #22
0
int
main (int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_principal principal;
    krb5_get_init_creds_opt *opt;
    krb5_ccache id = NULL;
    int exit_value;
    int optidx = 0;

    setprogname(argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1, args, sizeof(args) / sizeof(args[0]));
    if (help_flag)
	usage(0, args, sizeof(args) / sizeof(args[0]));
    if (version_flag) {
	print_version(NULL);
	return 0;
    }
    argc -= optidx;
    argv += optidx;

    ret = krb5_init_context (&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    ret = krb5_get_init_creds_opt_alloc (context, &opt);
    if (ret)
	krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc");

    krb5_get_init_creds_opt_set_tkt_life (opt, 300);
    krb5_get_init_creds_opt_set_forwardable (opt, FALSE);
    krb5_get_init_creds_opt_set_proxiable (opt, FALSE);

    if (cred_cache_str) {
	ret = krb5_cc_resolve(context, cred_cache_str, &id);
	if (ret)
	    krb5_err (context, 1, ret, "krb5_cc_resolve");
    } else {
	ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
	if (ret)
	    krb5_err (context, 1, ret, "krb5_cc_new_unique");
    }

    if (cred_cache_str == NULL) {
	krb5_principal admin_principal = NULL;
	krb5_creds cred;

	if (admin_principal_str) {
	    ret = krb5_parse_name (context, admin_principal_str,
				   &admin_principal);
	    if (ret)
		krb5_err (context, 1, ret, "krb5_parse_name");
	} else if (argc == 1) {
	    ret = krb5_parse_name (context, argv[0], &admin_principal);
	    if (ret)
		krb5_err (context, 1, ret, "krb5_parse_name");
	} else {
	    ret = krb5_get_default_principal (context, &admin_principal);
	    if (ret)
		krb5_err (context, 1, ret, "krb5_get_default_principal");
	}

	ret = krb5_get_init_creds_password (context,
					    &cred,
					    admin_principal,
					    NULL,
					    krb5_prompter_posix,
					    NULL,
					    0,
					    "kadmin/changepw",
					    opt);
	switch (ret) {
	case 0:
	    break;
	case KRB5_LIBOS_PWDINTR :
	    return 1;
	case KRB5KRB_AP_ERR_BAD_INTEGRITY :
	case KRB5KRB_AP_ERR_MODIFIED :
	    krb5_errx(context, 1, "Password incorrect");
	    break;
	default:
	    krb5_err(context, 1, ret, "krb5_get_init_creds");
	}

	krb5_get_init_creds_opt_free(context, opt);

	ret = krb5_cc_initialize(context, id, admin_principal);
	krb5_free_principal(context, admin_principal);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_cc_initialize");

	ret = krb5_cc_store_cred(context, id, &cred);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_cc_store_cred");

	krb5_free_cred_contents (context, &cred);
    }

    if (argc == 0) {
	exit_value = change_password(context, NULL, id);
    } else {
	exit_value = 0;

	while (argc-- > 0) {

	    ret = krb5_parse_name (context, argv[0], &principal);
	    if (ret)
		krb5_err (context, 1, ret, "krb5_parse_name");

	    ret = change_password(context, principal, id);
	    if (ret)
		exit_value = 1;
	    krb5_free_principal(context, principal);
	    argv++;
	}
    }

    if (cred_cache_str == NULL) {
	ret = krb5_cc_destroy(context, id);
	if (ret)
	    krb5_err (context, 1, ret, "krb5_cc_destroy");
    } else {
	ret = krb5_cc_close(context, id);
	if (ret)
	    krb5_err (context, 1, ret, "krb5_cc_close");
    }

    krb5_free_context (context);
    return exit_value;
}
Exemple #23
0
int main(int argc, char *argv[])
{
	int retval;

	debug_set_exception_handler();

	g_logger.registerThread("Main");
	g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);

	Settings cmd_args;
	bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
	if (!cmd_args_ok
			|| cmd_args.getFlag("help")
			|| cmd_args.exists("nonopt1")) {
		print_help(allowed_options);
		return cmd_args_ok ? 0 : 1;
	}

	if (cmd_args.getFlag("version")) {
		print_version();
		return 0;
	}

	setup_log_params(cmd_args);

	porting::signal_handler_init();

#ifdef __ANDROID__
	porting::initAndroid();
	porting::initializePathsAndroid();
#else
	porting::initializePaths();
#endif

	if (!create_userdata_path()) {
		errorstream << "Cannot create user data directory" << std::endl;
		return 1;
	}

	// Initialize debug stacks
	DSTACK(FUNCTION_NAME);

	// Debug handler
	BEGIN_DEBUG_EXCEPTION_HANDLER

	// List gameids if requested
	if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
		list_game_ids();
		return 0;
	}

	// List worlds if requested
	if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
		list_worlds();
		return 0;
	}

	if (!init_common(cmd_args, argc, argv))
		return 1;

#ifndef __ANDROID__
	// Run unit tests
	if (cmd_args.getFlag("run-unittests")) {
		return run_tests();
	}
#endif

	GameParams game_params;
#ifdef SERVER
	game_params.is_dedicated_server = true;
#else
	game_params.is_dedicated_server = cmd_args.getFlag("server");
#endif

	if (!game_configure(&game_params, cmd_args))
		return 1;

	sanity_check(!game_params.world_path.empty());

	infostream << "Using commanded world path ["
	           << game_params.world_path << "]" << std::endl;

	//Run dedicated server if asked to or no other option
	g_settings->set("server_dedicated",
			game_params.is_dedicated_server ? "true" : "false");

	if (game_params.is_dedicated_server)
		return run_dedicated_server(game_params, cmd_args) ? 0 : 1;

#ifndef SERVER
	ClientLauncher launcher;
	retval = launcher.run(game_params, cmd_args) ? 0 : 1;
#else
	retval = 0;
#endif

	// Update configuration file
	if (g_settings_path != "")
		g_settings->updateConfigFile(g_settings_path.c_str());

	print_modified_quicktune_values();

	// Stop httpfetch thread (if started)
	httpfetch_cleanup();

	END_DEBUG_EXCEPTION_HANDLER

	return retval;
}
Exemple #24
0
int
main(int argc, char **argv)
{
    char buf[1024];
    krb5_error_code ret;

    krb5_enctype enctype;

    hdb_master_key mkey;

    krb5_program_setup(&context, argc, argv, args, num_args, NULL);

    if(help_flag)
	krb5_std_usage(0, args, num_args);
    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    if (master_key_fd != -1 && random_key_flag)
	krb5_errx(context, 1, "random-key and master-key-fd "
		  "is mutual exclusive");

    if (keyfile == NULL)
	asprintf(&keyfile, "%s/m-key", hdb_db_dir(context));

    ret = krb5_string_to_enctype(context, enctype_str, &enctype);
    if(ret)
	krb5_err(context, 1, ret, "krb5_string_to_enctype");

    ret = hdb_read_master_key(context, keyfile, &mkey);
    if(ret && ret != ENOENT)
	krb5_err(context, 1, ret, "reading master key from %s", keyfile);

    if (convert_flag) {
	if (ret)
	    krb5_err(context, 1, ret, "reading master key from %s", keyfile);
    } else {
	krb5_keyblock key;
	krb5_salt salt;
	salt.salttype = KRB5_PW_SALT;
	/* XXX better value? */
	salt.saltvalue.data = NULL;
	salt.saltvalue.length = 0;
	if (random_key_flag) {
	    ret = krb5_generate_random_keyblock(context, enctype, &key);
	    if (ret)
		krb5_err(context, 1, ret, "krb5_generate_random_keyblock");

	} else {
	    if(master_key_fd != -1) {
		ssize_t n;
		n = read(master_key_fd, buf, sizeof(buf));
		if(n <= 0)
		    krb5_err(context, 1, errno, "failed to read passphrase");
		buf[n] = '\0';
		buf[strcspn(buf, "\r\n")] = '\0';
		
	    } else {
		if(UI_UTIL_read_pw_string(buf, sizeof(buf), "Master key: ", 1))
		    exit(1);
	    }
	    krb5_string_to_key_salt(context, enctype, buf, salt, &key);
	}
	ret = hdb_add_master_key(context, &key, &mkey);
	
	krb5_free_keyblock_contents(context, &key);

    }

    {
	char *new, *old;
	asprintf(&old, "%s.old", keyfile);
	asprintf(&new, "%s.new", keyfile);
	if(unlink(new) < 0 && errno != ENOENT) {
	    ret = errno;
	    goto out;
	}
	krb5_warnx(context, "writing key to `%s'", keyfile);
	ret = hdb_write_master_key(context, new, mkey);
	if(ret)
	    unlink(new);
	else {
#ifndef NO_POSIX_LINKS
	    unlink(old);
	    if(link(keyfile, old) < 0 && errno != ENOENT) {
		ret = errno;
		unlink(new);
	    } else {
#endif
		if(rename(new, keyfile) < 0) {
Exemple #25
0
int main(int argc, char **argv)
{
	blkid_cache cache = NULL;
	char **devices = NULL;
	char *show[128] = { NULL, };
	char *search_type = NULL, *search_value = NULL;
	char *read = NULL;
	int fltr_usage = 0;
	char **fltr_type = NULL;
	int fltr_flag = BLKID_FLTR_ONLYIN;
	unsigned int numdev = 0, numtag = 0;
	int version = 0;
	int err = BLKID_EXIT_OTHER;
	unsigned int i;
	int output_format = 0;
	int lookup = 0, gc = 0, lowprobe = 0, eval = 0;
	int c;
	uintmax_t offset = 0, size = 0;

	static const ul_excl_t excl[] = {       /* rows and cols in in ASCII order */
		{ 'n','u' },
		{ 0 }
	};
	int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;

	show[0] = NULL;
	atexit(close_stdout);

	while ((c = getopt (argc, argv,
			    "c:df:ghilL:n:ko:O:ps:S:t:u:U:w:Vv")) != EOF) {

		err_exclusive_options(c, NULL, excl, excl_st);

		switch (c) {
		case 'c':
			if (optarg && !*optarg)
				read = NULL;
			else
				read = optarg;
			break;
		case 'd':
			raw_chars = 1;
			break;
		case 'L':
			eval++;
			search_value = xstrdup(optarg);
			search_type = xstrdup("LABEL");
			break;
		case 'n':
			fltr_type = list_to_types(optarg, &fltr_flag);
			break;
		case 'u':
			fltr_usage = list_to_usage(optarg, &fltr_flag);
			break;
		case 'U':
			eval++;
			search_value = xstrdup(optarg);
			search_type = xstrdup("UUID");
			break;
		case 'i':
			lowprobe |= LOWPROBE_TOPOLOGY;
			break;
		case 'l':
			lookup++;
			break;
		case 'g':
			gc = 1;
			break;
		case 'k':
		{
			size_t idx = 0;
			const char *name = NULL;

			while (blkid_superblocks_get_name(idx++, &name, NULL) == 0)
				printf("%s\n", name);
			exit(EXIT_SUCCESS);
		}
		case 'o':
			if (!strcmp(optarg, "value"))
				output_format = OUTPUT_VALUE_ONLY;
			else if (!strcmp(optarg, "device"))
				output_format = OUTPUT_DEVICE_ONLY;
			else if (!strcmp(optarg, "list"))
				output_format = OUTPUT_PRETTY_LIST;	/* deprecated */
			else if (!strcmp(optarg, "udev"))
				output_format = OUTPUT_UDEV_LIST;
			else if (!strcmp(optarg, "export"))
				output_format = OUTPUT_EXPORT_LIST;
			else if (!strcmp(optarg, "full"))
				output_format = 0;
			else {
				fprintf(stderr, "Invalid output format %s. "
					"Choose from value,\n\t"
					"device, list, udev or full\n", optarg);
				exit(BLKID_EXIT_OTHER);
			}
			break;
		case 'O':
			offset = strtosize_or_err(optarg, "invalid offset argument");
			break;
		case 'p':
			lowprobe |= LOWPROBE_SUPERBLOCKS;
			break;
		case 's':
			if (numtag + 1 >= sizeof(show) / sizeof(*show)) {
				fprintf(stderr, "Too many tags specified\n");
				usage(err);
			}
			show[numtag++] = optarg;
			show[numtag] = NULL;
			break;
		case 'S':
			size = strtosize_or_err(optarg, "invalid size argument");
			break;
		case 't':
			if (search_type) {
				fprintf(stderr, "Can only search for "
						"one NAME=value pair\n");
				usage(err);
			}
			if (blkid_parse_tag_string(optarg,
						   &search_type,
						   &search_value)) {
				fprintf(stderr, "-t needs NAME=value pair\n");
				usage(err);
			}
			break;
		case 'V':
		case 'v':
			version = 1;
			break;
		case 'w':
			/* ignore - backward compatibility */
			break;
		case 'h':
			err = 0;
			/* fallthrough */
		default:
			usage(err);
		}
	}


	/* The rest of the args are device names */
	if (optind < argc) {
		devices = xcalloc(argc - optind, sizeof(char *));
		while (optind < argc)
			devices[numdev++] = argv[optind++];
	}

	if (version) {
		print_version(stdout);
		goto exit;
	}

	/* convert LABEL/UUID lookup to evaluate request */
	if (lookup && output_format == OUTPUT_DEVICE_ONLY && search_type &&
	    (!strcmp(search_type, "LABEL") || !strcmp(search_type, "UUID"))) {
		eval++;
		lookup = 0;
	}

	if (!lowprobe && !eval && blkid_get_cache(&cache, read) < 0)
		goto exit;

	if (gc) {
		blkid_gc_cache(cache);
		err = 0;
		goto exit;
	}
	err = BLKID_EXIT_NOTFOUND;

	if (eval == 0 && (output_format & OUTPUT_PRETTY_LIST)) {
		if (lowprobe) {
			fprintf(stderr, "The low-level probing mode does not "
					"support 'list' output format\n");
			exit(BLKID_EXIT_OTHER);
		}
		pretty_print_dev(NULL);
	}

	if (lowprobe) {
		/*
		 * Low-level API
		 */
		blkid_probe pr;

		if (!numdev) {
			fprintf(stderr, "The low-level probing mode "
					"requires a device\n");
			exit(BLKID_EXIT_OTHER);
		}

		/* automatically enable 'export' format for I/O Limits */
		if (!output_format  && (lowprobe & LOWPROBE_TOPOLOGY))
			output_format = OUTPUT_EXPORT_LIST;

		pr = blkid_new_probe();
		if (!pr)
			goto exit;

		if (lowprobe & LOWPROBE_SUPERBLOCKS) {
			blkid_probe_set_superblocks_flags(pr,
				BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID |
				BLKID_SUBLKS_TYPE | BLKID_SUBLKS_SECTYPE |
				BLKID_SUBLKS_USAGE | BLKID_SUBLKS_VERSION);

			if (fltr_usage && blkid_probe_filter_superblocks_usage(
						pr, fltr_flag, fltr_usage))
				goto exit;

			else if (fltr_type && blkid_probe_filter_superblocks_type(
						pr, fltr_flag, fltr_type))
				goto exit;
		}

		for (i = 0; i < numdev; i++) {
			err = lowprobe_device(pr, devices[i], lowprobe, show,
					output_format,
					(blkid_loff_t) offset,
					(blkid_loff_t) size);
			if (err)
				break;
		}
		blkid_free_probe(pr);
	} else if (eval) {
		/*
		 * Evaluate API
		 */
		char *res = blkid_evaluate_tag(search_type, search_value, NULL);
		if (res) {
			err = 0;
			printf("%s\n", res);
		}
	} else if (lookup) {
		/*
		 * Classic (cache based) API
		 */
		blkid_dev dev;

		if (!search_type) {
			fprintf(stderr, "The lookup option requires a "
				"search type specified using -t\n");
			exit(BLKID_EXIT_OTHER);
		}
		/* Load any additional devices not in the cache */
		for (i = 0; i < numdev; i++)
			blkid_get_dev(cache, devices[i], BLKID_DEV_NORMAL);

		if ((dev = blkid_find_dev_with_tag(cache, search_type,
						   search_value))) {
			print_tags(dev, show, output_format);
			err = 0;
		}
	/* If we didn't specify a single device, show all available devices */
	} else if (!numdev) {
		blkid_dev_iterate	iter;
		blkid_dev		dev;

		blkid_probe_all(cache);

		iter = blkid_dev_iterate_begin(cache);
		blkid_dev_set_search(iter, search_type, search_value);
		while (blkid_dev_next(iter, &dev) == 0) {
			dev = blkid_verify(cache, dev);
			if (!dev)
				continue;
			print_tags(dev, show, output_format);
			err = 0;
		}
		blkid_dev_iterate_end(iter);
	/* Add all specified devices to cache (optionally display tags) */
	} else for (i = 0; i < numdev; i++) {
		blkid_dev dev = blkid_get_dev(cache, devices[i],
						  BLKID_DEV_NORMAL);

		if (dev) {
			if (search_type &&
			    !blkid_dev_has_tag(dev, search_type,
					       search_value))
				continue;
			print_tags(dev, show, output_format);
			err = 0;
		}
	}

exit:
	free(search_type);
	free(search_value);
	free_types_list(fltr_type);
	if (!lowprobe && !eval)
		blkid_put_cache(cache);
	free(devices);
	return err;
}
Exemple #26
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;
}
Exemple #27
0
/*
 ***************************************************************************
 * Main entry to the sadf program
 ***************************************************************************
 */
int main(int argc, char **argv)
{
	int opt = 1, sar_options = 0;
	int day_offset = 0;
	int i, rc;
	char dfile[MAX_FILE_LEN];

	/* Get HZ */
	get_HZ();

	/* Compute page shift in kB */
	get_kb_shift();

	dfile[0] = '\0';

#ifdef USE_NLS
	/* Init National Language Support */
	init_nls();
#endif

	tm_start.use = tm_end.use = FALSE;

	/* Allocate and init activity bitmaps */
	allocate_bitmaps(act);

	/* Init some structures */
	init_structures();

	/* Process options */
	while (opt < argc) {

		if (!strcmp(argv[opt], "-I")) {
			if (argv[++opt] && sar_options) {
				if (parse_sar_I_opt(argv, &opt, act)) {
					usage(argv[0]);
				}
			}
			else {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-P")) {
			if (parse_sa_P_opt(argv, &opt, &flags, act)) {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-s")) {
			/* Get time start */
			if (parse_timestamp(argv, &opt, &tm_start, DEF_TMSTART)) {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-e")) {
			/* Get time end */
			if (parse_timestamp(argv, &opt, &tm_end, DEF_TMEND)) {
				usage(argv[0]);
			}
		}

		else if ((strlen(argv[opt]) > 1) &&
			 (strlen(argv[opt]) < 4) &&
			 !strncmp(argv[opt], "-", 1) &&
			 (strspn(argv[opt] + 1, DIGITS) == (strlen(argv[opt]) - 1))) {
			if (dfile[0] || day_offset) {
				/* File already specified */
				usage(argv[0]);
			}
			day_offset = atoi(argv[opt++] + 1);
		}

		else if (!strcmp(argv[opt], "--")) {
			sar_options = 1;
			opt++;
		}

		else if (!strcmp(argv[opt], "-m")) {
			if (argv[++opt] && sar_options) {
				/* Parse sar's option -m */
				if (parse_sar_m_opt(argv, &opt, act)) {
					usage(argv[0]);
				}
			}
			else {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-n")) {
			if (argv[++opt] && sar_options) {
				/* Parse sar's option -n */
				if (parse_sar_n_opt(argv, &opt, act)) {
					usage(argv[0]);
				}
			}
			else {
				usage(argv[0]);
			}
		}

		else if (!strncmp(argv[opt], "-", 1)) {
			/* Other options not previously tested */
			if (sar_options) {
				if ((rc = parse_sar_opt(argv, &opt, act, &flags, C_SADF)) != 0) {
					if (rc == 1) {
						usage(argv[0]);
					}
					exit(1);
				}
			}
			else {

				for (i = 1; *(argv[opt] + i); i++) {

					switch (*(argv[opt] + i)) {

					case 'C':
						flags |= S_F_COMMENT;
						break;

					case 'c':
						if (format) {
							usage(argv[0]);
						}
						format = F_CONV_OUTPUT;
						break;

					case 'd':
						if (format) {
							usage(argv[0]);
						}
						format = F_DB_OUTPUT;
						break;

					case 'h':
						flags |= S_F_HORIZONTALLY;
						break;

					case 'H':
						flags |= S_F_HDR_ONLY;
						break;

					case 'j':
						if (format) {
							usage(argv[0]);
						}
						format = F_JSON_OUTPUT;
						break;

					case 'p':
						if (format) {
							usage(argv[0]);
						}
						format = F_PPC_OUTPUT;
						break;

					case 'T':
						flags |= S_F_LOCAL_TIME;
						break;

					case 't':
						flags |= S_F_TRUE_TIME;
						break;

					case 'U':
						flags |= S_F_SEC_EPOCH;
						break;

					case 'x':
						if (format) {
							usage(argv[0]);
						}
						format = F_XML_OUTPUT;
						break;

					case 'V':
						print_version();
						break;

					default:
						usage(argv[0]);
					}
				}
			}
			opt++;
		}

		/* Get data file name */
		else if (strspn(argv[opt], DIGITS) != strlen(argv[opt])) {
			if (dfile[0] || day_offset) {
				/* File already specified */
				usage(argv[0]);
			}
			if (!strcmp(argv[opt], "-")) {
				/* File name set to '-' */
				set_default_file(dfile, 0, -1);
				opt++;
			}
			else if (!strncmp(argv[opt], "-", 1)) {
				/* Bad option */
				usage(argv[0]);
			}
			else {
				/* Write data to file */
				strncpy(dfile, argv[opt++], MAX_FILE_LEN);
				dfile[MAX_FILE_LEN - 1] = '\0';
				/* Check if this is an alternate directory for sa files */
				check_alt_sa_dir(dfile, 0, -1);
			}
		}

		else if (interval < 0) {
			/* Get interval */
			if (strspn(argv[opt], DIGITS) != strlen(argv[opt])) {
				usage(argv[0]);
			}
			interval = atol(argv[opt++]);
			if (interval <= 0) {
				usage(argv[0]);
			}
		}

		else {
			/* Get count value */
			if (strspn(argv[opt], DIGITS) != strlen(argv[opt])) {
				usage(argv[0]);
			}
			if (count) {
				/* Count parameter already set */
				usage(argv[0]);
			}
			count = atol(argv[opt++]);
			if (count < 0) {
				usage(argv[0]);
			}
			else if (!count) {
				count = -1;	/* To generate a report continuously */
			}
		}
	}

	/* sadf reads current daily data file by default */
	if (!dfile[0]) {
		set_default_file(dfile, day_offset, -1);
	}

	if (tm_start.use && tm_end.use && (tm_end.tm_hour < tm_start.tm_hour)) {
		tm_end.tm_hour += 24;
	}

	if (USE_PRETTY_OPTION(flags)) {
		dm_major = get_devmap_major();
	}

	/* Options -T, -t and -U are mutually exclusive */
	if ((PRINT_LOCAL_TIME(flags) + PRINT_TRUE_TIME(flags) +
	    PRINT_SEC_EPOCH(flags)) > 1) {
		usage(argv[0]);
	}

	/*
	 * Display all the contents of the daily data file if the count parameter
	 * was not set on the command line.
	 */
	if (!count) {
		count = -1;
	}

	/* Default is CPU activity */
	select_default_activity(act);

	/* Check options consistency with selected output format. Default is PPC display */
	check_format_options();

	if (interval < 0) {
		interval = 1;
	}

	if (format == F_CONV_OUTPUT) {
		/* Convert file to current format */
		convert_file(dfile, act);
	}
	else {
		/* Read stats from file */
		read_stats_from_file(dfile);
	}

	/* Free bitmaps */
	free_bitmaps(act);

	return 0;
}
Exemple #28
0
int
main(int argc, char **argv)
{
    MM_INFO *mm;
    char *mmtype = NULL;
    int ch;
    SSIZE_T imgoff = 0;
    char *imgtype = NULL;
    IMG_INFO *img;

    progname = argv[0];

    while ((ch = getopt(argc, argv, "i:o:t:vV")) > 0) {
	switch (ch) {
	case 'i':
	    imgtype = optarg;
	    break;

	case 'o':
	    if ((imgoff = parse_offset(optarg)) == -1) {
		tsk_error_print(stderr);
		exit(1);
	    }

	    break;
	case 't':
	    mmtype = optarg;
	    break;
	case 'v':
	    verbose++;
	    break;
	case 'V':
	    print_version(stdout);
	    exit(0);
	case '?':
	default:
	    fprintf(stderr, "Unknown argument\n");
	    usage();
	}
    }

    /* We need at least one more argument */
    if (optind >= argc) {
	fprintf(stderr, "Missing image name\n");
	usage();
    }

    /* open the image */
    if ((img =
	    img_open(imgtype, argc - optind,
		(const char **) &argv[optind])) == NULL) {
	tsk_error_print(stderr);
	exit(1);
    }


    /* process the partition tables */
    if ((mm = mm_open(img, imgoff, mmtype)) == NULL) {
	tsk_error_print(stderr);
	if (tsk_errno == TSK_ERR_MM_UNSUPTYPE)
	    mm_print_types(stderr);

	exit(1);
    }

    print_stats(mm);

    mm->close(mm);
    img->close(img);
    exit(0);
}
Exemple #29
0
int
qdpll_main (int argc, char **argv)
{
  QDPLLResult result = QDPLL_RESULT_UNKNOWN;
  QDPLLApp app;
  memset (&app, 0, sizeof (QDPLLApp));
  set_default_options (&app);

  qdpll = qdpll_create ();

  parse_cmd_line_options (&app, qdpll, argc, argv);
  check_options (&app);
  set_signal_handlers (&app);

  if (app.options.print_usage)
    {
      print_usage ();
      cleanup (qdpll, &app);
      return result;
    }
  if (app.options.print_version)
    {
      print_version ();
      cleanup (qdpll, &app);
      return result;
    }

  if (app.options.max_time)
    alarm (app.options.max_time);

  parse (&app, qdpll, app.options.in, app.options.trace);

  if (app.options.pretty_print)
    {
      /* Call 'qdpll_gc' to clean up the formula by removing variables
         which have no occurrences and removing empty quantifier
         blocks. */
      qdpll_gc (qdpll);
      qdpll_print (qdpll, stdout);
    }
  else if (app.options.deps_only)
    {
      qdpll_init_deps (qdpll);
      if (app.options.print_deps)
        print_deps (&app, qdpll);
      if (app.options.dump_dep_graph)
        qdpll_dump_dep_graph (qdpll);
    }
  else
    {
        result = qdpll_sat (qdpll);
#if (COMPUTE_STATS || COMPUTE_TIMES)
        qdpll_print_stats (qdpll);
#endif
    }

  if (app.options.trace == TRACE_QRP)
    fprintf (stdout, "r ");
  else if (app.options.trace == TRACE_BQRP)
    fprintf (stdout, "%cr ", 0);

  print_result_message (&app, qdpll, result, stdout);

  cleanup (qdpll, &app);

  return result;
}
Exemple #30
0
/* --------------------------------------------- */
static int parse_commandline(int argc, char **argv) {
    int  nargc , nargsused;
    char **pargv, *option ;

    if (argc < 1) usage_exit();

    nargc   = argc;
    pargv = argv;
    while (nargc > 0) {

        option = pargv[0];
        if (debug) printf("%d %s\n",nargc,option);
        nargc -= 1;
        pargv += 1;

        nargsused = 0;

        if (!strcasecmp(option, "--help"))  print_help() ;
        else if (!strcasecmp(option, "--version")) print_version() ;
        else if (!strcasecmp(option, "--debug"))   debug = 1;
        else if (!strcasecmp(option, "--checkopts"))   checkoptsonly = 1;
        else if (!strcasecmp(option, "--nocheckopts")) checkoptsonly = 0;
        else if (!strcasecmp(option, "--no-log10")) log10flag = 0;
        else if (!strcasecmp(option, "--no-strip4")) DoStrip4 = 0;

        else if (!strcasecmp(option, "--stat")) {
            if (nargc < 1) CMDargNErr(option,1);
            statfile = pargv[0];
            DoDavid = 1;
            nargsused = 1;
        } else if (!strcasecmp(option, "--sue")) {
            if (nargc < 2) CMDargNErr(option,2);
            statfile = pargv[0];
            sscanf(pargv[1],"%d",&datcol1);
            log10flag = 1;
            DoSue = 1;
            nargsused = 2;
        } else if (!strcasecmp(option, "--seg")) {
            if (nargc < 1) CMDargNErr(option,1);
            segfile = pargv[0];
            nargsused = 1;
        } else if (!strcasecmp(option, "--annot")) {
            if (nargc < 3) CMDargNErr(option,3);
            annot   = pargv[0];
            subject = pargv[1];
            hemi    = pargv[2];
            nargsused = 3;
        } else if (!strcasecmp(option, "--o")) {
            if (nargc < 1) CMDargNErr(option,1);
            outfile = pargv[0];
            nargsused = 1;
        } else {
            fprintf(stderr,"ERROR: Option %s unknown\n",option);
            if (CMDsingleDash(option))
                fprintf(stderr,"       Did you really mean -%s ?\n",option);
            exit(-1);
        }
        nargc -= nargsused;
        pargv += nargsused;
    }
    return(0);
}