Example #1
0
int do_liandan()
{       int kar;
        string str;
        object me = this_player();
        
        // 变量说明:yxld==允许炼丹
        //          nlcs==能炼次数
        //          ldcs==能炼次数
        //          ldwp==炼丹物品参数,目前分2000 4000
        
        if(!me->query_temp("yxld"))
                    return notify_fail("你原料都没给道童,怎么炼?\n");
        if(me->is_busy()) 
                   return notify_fail("你现在正忙着呢!\n");
        if(me->query("kee")<200||me->query("sen")<200)
                   return notify_fail("你还是先休息一下吧,炼丹很耗气血和精神的哦。\n");
                
         kar = me->query("kar")*2;
        if (!me->query_temp("nlcs")) me->set_temp("nlcs",random(kar)/5);
                
        me->start_busy(3+random(10));
        message_vision(MAG"$N鼓动真气,把自己毕生的道行化做一团真火喷向丹炉。\n"NOR, me);
       
        me->receive_damage("kee",random(100));
        me->receive_damage("sen",random(100));
       
        if (random(kar)>3)
            {
            if( me->query_temp("ldcs")>=me->query_temp("nlcs"))
                {
		
		kar=random(7);// 节省变量, 不提倡这样 :P
me->set_temp("ldcs",(int)me->query_temp("ldcs")/2);
		if(kar==0)
		    {
			message_vision(HIR"炉里的火猛的一跳,$N终于炼好了一个香气四溢的潜能丹。\n"NOR,me);
 	                message_vision(CYN"$N喜出望外,一口吞下这颗潜能丹。\n"NOR,me);
kar=(int)me->query_temp("ldwp")/4+random(500)+(int)me->query_temp("ldcs")*40+(int)me->query_temp("nlcs")*20;
 	                tell_object(me,"你获得了"+kar+"的潜能!\n");
        	        str=me->query("name")+"成功地炼出了颗潜能丹,获得了"+kar+"的潜能奖励!";
                	CHANNEL_D->do_channel(me,"rumor",str);
        	        kar=(int)me->query_temp("ldwp")+random(2000);
                	me->add("potential",kar);
                    }
    		else if(kar==1)
    		    {
    		        message_vision(HIR"炉里的火猛的一跳,$N终于炼好了一个香气四溢的武学丹。\n"NOR,me);
 	                message_vision(CYN"$N喜出望外,一口吞下这颗武学丹。\n"NOR,me);
kar=(int)me->query_temp("ldwp")+random(1000)+(int)me->query_temp("ldcs")*200+(int)me->query_temp("nlcs")*100;
        	        tell_object(me,"你获得了"+kar+"的武学经验!\n");
        	        str=me->query("name")+"成功地炼出了颗武学丹,获得了"+kar+"的武学奖励!";
                	CHANNEL_D->do_channel(me,"rumor",str);
                	me->add("combat_exp",kar);
                   }
                else if(kar==2) 
                   {    
                        message_vision(HIR"炉里的火猛的一跳,$N终于炼好了一个香气四溢的道行丹。\n"NOR,me);
 	                message_vision(CYN"$N喜出望外,一口吞下这颗道行丹。\n"NOR,me);
kar=(int)me->query_temp("ldwp")+random(500)+(int)me->query_temp("ldcs")*400+(int)me->query_temp("nlcs")*400;
        	        tell_object(me,"你获得了"+COMBAT_D->chinese_daoxing(kar)+"的道行!\n");
        	        str=me->query("name")+"成功地炼出了颗道行丹,获得了"+COMBAT_D->chinese_daoxing(kar)+"的道行奖励!";
                	CHANNEL_D->do_channel(me,"rumor",str);
                	me->add("daoxing",kar);
                   
                   }   
    		else 
    		   {   
                        message_vision(HIR"炉里的火猛的一跳,炼出来的竟然是黄金!\n"NOR,me);
 	                message_vision(CYN"$N喜出望外,赶紧把这些钱存在银行里。\n"NOR,me);
kar=(int)me->query_temp("ldwp")*20+random(50000)+(int)me->query_temp("ldcs")*8000+(int)me->query_temp("nlcs")*4000;
        	        tell_object(me,"你获得了"+chinese_number(kar/10000)+"两黄金!\n");
        	        str=me->query("name")+"误打误撞,竟然炼出了"+chinese_number(kar/10000)+"两黄金!";
                	CHANNEL_D->do_channel(me,"rumor",str);
                	me->add("balance",kar);
                   }
    	        me->delete_temp("yxld");
		me->delete_temp("ldcs");
		me->delete_temp("nlcs");
		me->delete_temp("ldwp");
                      log_file("liandan",sprintf("%s(%s)(%s)\n",
				geteuid(me),str,ctime(time()) ) );
    	        return 1;
    	       }
    	    else {
    	        message_vision(HIR"只见炉里的火更旺了。。。\n"NOR,me);
    	        me->add_temp("ldcs",1);
    	        return 1;
    	         }
    	  }
        else 
           	{
                me->receive_wound("kee", random(100));  
                me->receive_wound("sen",random(50));
                message_vision(RED"$N行功时突然走火入魔,口喷鲜血栽倒在地。\n"NOR,me );
                me->add_temp("ldcs",1);
     		me->unconcious();
     		 return 1;
     		}
}
Example #2
0
static void PRS(int argc, char **argv)
{
	int     i, j;
	char    *arg, *dev, *tmp = 0;
	char    options[128];
	int     opt = 0;
	int     opts_for_fsck = 0;
	struct sigaction        sa;

	/*
	 * Set up signal action
	 */
	memset(&sa, 0, sizeof(struct sigaction));
	sa.sa_handler = signal_cancel;
	sigaction(SIGINT, &sa, 0);
	sigaction(SIGTERM, &sa, 0);

	num_devices = 0;
	num_args = 0;
	instance_list = 0;

	for (i=1; i < argc; i++) {
		arg = argv[i];
		if (!arg)
			continue;
		if ((arg[0] == '/' && !opts_for_fsck) || strchr(arg, '=')) {
			if (num_devices >= MAX_DEVICES) {
				bb_error_msg_and_die("too many devices");
			}
			dev = blkid_get_devname(cache, arg, NULL);
			if (!dev && strchr(arg, '=')) {
				/*
				 * Check to see if we failed because
				 * /proc/partitions isn't found.
				 */
				if (access("/proc/partitions", R_OK) < 0) {
					bb_perror_msg_and_die("cannot open /proc/partitions "
							"(is /proc mounted?)");
				}
				/*
				 * Check to see if this is because
				 * we're not running as root
				 */
				if (geteuid())
					bb_error_msg_and_die(
		"must be root to scan for matching filesystems: %s\n", arg);
				else
					bb_error_msg_and_die(
		"cannot find matching filesystem: %s", arg);
			}
			devices[num_devices++] = dev ? dev : string_copy(arg);
			continue;
		}
		if (arg[0] != '-' || opts_for_fsck) {
			if (num_args >= MAX_ARGS) {
				bb_error_msg_and_die("too many arguments");
			}
			args[num_args++] = string_copy(arg);
			continue;
		}
		for (j=1; arg[j]; j++) {
			if (opts_for_fsck) {
				options[++opt] = arg[j];
				continue;
			}
			switch (arg[j]) {
			case 'A':
				doall++;
				break;
			case 'C':
				progress++;
				if (arg[j+1]) {
					progress_fd = string_to_int(arg+j+1);
					if (progress_fd < 0)
						progress_fd = 0;
					else
						goto next_arg;
				} else if ((i+1) < argc
				 && argv[i+1][0] != '-') {
					progress_fd = string_to_int(argv[i]);
					if (progress_fd < 0)
						progress_fd = 0;
					else {
						goto next_arg;
						i++;
					}
				}
				break;
			case 'V':
				verbose++;
				break;
			case 'N':
				noexecute++;
				break;
			case 'R':
				skip_root++;
				break;
			case 'T':
				notitle++;
				break;
			case 'M':
				like_mount++;
				break;
			case 'P':
				parallel_root++;
				break;
			case 's':
				serialize++;
				break;
			case 't':
				tmp = 0;
				if (fstype)
					bb_show_usage();
				if (arg[j+1])
					tmp = arg+j+1;
				else if ((i+1) < argc)
					tmp = argv[++i];
				else
					bb_show_usage();
				fstype = string_copy(tmp);
				compile_fs_type(fstype, &fs_type_compiled);
				goto next_arg;
			case '-':
				opts_for_fsck++;
				break;
			case '?':
				bb_show_usage();
				break;
			default:
				options[++opt] = arg[j];
				break;
			}
		}
	next_arg:
		if (opt) {
			options[0] = '-';
			options[++opt] = '\0';
			if (num_args >= MAX_ARGS) {
				bb_error_msg("too many arguments");
			}
			args[num_args++] = string_copy(options);
			opt = 0;
		}
	}
	if (getenv("FSCK_FORCE_ALL_PARALLEL"))
		force_all_parallel++;
	if ((tmp = getenv("FSCK_MAX_INST")))
	    max_running = atoi(tmp);
}
Example #3
0
/* We need this */
int main(int argc, char *argv[]) {
  int optc, show_help, show_version, show_usage;
  char *local_file, *cmd_listen_port, *cmd_pid_file;
  int inetd_mode, no_daemon;

  /* Set up some globals */
  progname = argv[0];
  listen_port = x_strdup(DEFAULT_LISTEN_PORT);
  pid_file = (DEFAULT_PID_FILE ? x_strdup(DEFAULT_PID_FILE) : 0);

#ifndef DEBUG
  no_daemon = 0;
#else /* DEBUG */
  no_daemon = 1;
#endif /* DEBUG */
  local_file = cmd_listen_port = cmd_pid_file = 0;
  show_help = show_version = show_usage = inetd_mode = 0;
  while ((optc = getopt_long(argc, argv, GETOPTIONS, long_opts, NULL)) != -1) {
    switch (optc) {
      case 'h':
        show_help = 1;
        break;
      case 'v':
        show_version = 1;
        break;
      case 'D':
#ifndef DEBUG
        no_daemon = 1;
#else /* DEBUG */
        no_daemon = 0;
#endif /* DEBUG */
        break;
      case 'I':
        inetd_mode = 1;
        break;
      case 'P':
        free(cmd_listen_port);
        cmd_listen_port = x_strdup(optarg);
        break;
      case 'p':
        free(cmd_pid_file);
        cmd_pid_file = x_strdup(optarg);
        break;
      case 'f':
        free(local_file);
        local_file = x_strdup(optarg);
        break;
      default:
        show_usage = 1;
        break;
    }
  }

  if (show_usage || (optind < argc)) {
    _print_usage();
    return 1;
  }

  if (show_version) {
    _print_version();
    if (!show_help)
      return 0;
  }

  if (show_help) {
    _print_help();
    return 0;
  }

  /* If no -f was specified use the home directory */
  if (!local_file && !inetd_mode) {
    struct stat statinfo;
    struct passwd *pw;

    pw = getpwuid(geteuid());
    if (pw && pw->pw_dir) {
      local_file = x_sprintf("%s/%s", pw->pw_dir, USER_CONFIG_FILENAME);
      debug("Local config file: %s", local_file);
      if (!stat(local_file, &statinfo) && (statinfo.st_mode & 0077)) {
        fprintf(stderr, "%s: Permissions of %s must be 0700 or "
                        "more restrictive\n", progname, local_file);
        free(local_file);
        return 2;
      }
      if (cfg_read(local_file, &listen_port, &pid_file, &g)) {
        /* If the local one didn't exist, set to 0 so we open
           global one */
        free(local_file);
        local_file = 0;
      } else {
        config_file = x_strdup(local_file);
      }
    }
  } else if (local_file) {
    if (cfg_read(local_file, &listen_port, &pid_file, &g)) {
      /* This is fatal! */
      fprintf(stderr, "%s: Couldn't read configuration from %s: %s\n",
              progname, local_file, strerror(errno));
      free(local_file);
      return 2;
    } else {
      config_file = x_strdup(local_file);
    }
  }

  /* Read global config file if local one not found */
  if (!local_file) {
    char *global_file;

    /* Not fatal if it doesn't exist */
    global_file = x_sprintf("%s/%s", SYSCONFDIR, GLOBAL_CONFIG_FILENAME);
    debug("Global config file: %s", global_file);
    cfg_read(global_file, &listen_port, &pid_file, &g);
    config_file = x_strdup(global_file);
    free(global_file);
  } else {
    free(local_file);
  }

  /* Check we got some connection classes */
  if (!connclasses) {
    fprintf(stderr, "%s: No connection classes have been defined.\n", progname);
    return 2;
  }

  /* -P overrides config file */
  if (cmd_listen_port) {
    free(listen_port);
    listen_port = cmd_listen_port;
  }

  /* -p overrides pid file */
  if (cmd_pid_file) {
    free(pid_file);
    pid_file = cmd_pid_file;
  }

  /* Set signal handlers */
  signal(SIGTERM, _sig_term);
  signal(SIGINT, _sig_term);
  signal(SIGHUP, _sig_hup);
  signal(SIGCHLD, _sig_child);
#ifdef DEBUG_MEMORY
  signal(SIGUSR1, _sig_usr);
  signal(SIGUSR2, _sig_usr);
#endif /* DEBUG_MEMORY */

  /* Broken Pipe?  This means that someone disconnected while we were
     sending stuff.  Naughty! */
  signal(SIGPIPE, SIG_IGN);

  if (!inetd_mode) {
    debug("Ordinary console dodge-monkey mode");

    /* Make listening socket before we fork */
    if (ircnet_listen(listen_port)) {
      fprintf(stderr, "%s: Unable to establish listen port\n", progname);
      return 3;
    }

    /* go daemon here */
    if (!no_daemon) {
      switch (go_daemon()) {
        case -1:
          return -1;
        case 0:
          break;
        default:
          return 0;
      }
    }

  } else {
    /* running under inetd means we are backgrounded right *now* */
    in_background = 1;

    debug("Inetd SuperTed mode!");

    /* Hook STDIN into a new proxy */
    ircnet_hooksocket(STDIN_FILENO);
  }
 
  /* Open a connection to syslog if we're in the background */
  if (in_background)
    openlog(PACKAGE, LOG_PID, LOG_USER);

  if (pid_file) {
    FILE *pidfile;

    pidfile = fopen(pid_file, "w");
    if (pidfile) {
      fchmod(fileno(pidfile), 0600);
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    } else {
      syscall_fail("fopen", pid_file, 0);
    }
  }
  
  /* Main loop! */
  while (!stop_poll) {
    int ns, nt, status;
    pid_t pid;

    ircnet_expunge_proxies();
    dccnet_expunge_proxies();
    ns = net_poll();
    nt = timer_poll();

    /* Reap any children */
    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
      debug("Reaped process %d, exit status %d", pid, status);
      
      /* Handle any DNS children */
      dns_endrequest(pid, status);
    }

    /* Reload the configuration file? */
    if (reload_config) {
      _reload_config();
      reload_config = 0;
    }

    if (!ns && !nt)
      break;
  }

  if (pid_file) {
    unlink(pid_file);
  }

  /* Free up stuff */
  ircnet_flush();
  dccnet_flush();
  dns_flush();
  timer_flush();

  /* Do a lingering close on all sockets */
  net_closeall();
  net_flush();

  /* Close down and free up memory */
  if (!inetd_mode && !no_daemon)
    closelog();
  free(listen_port);
  free(pid_file);
  free(config_file);

#ifdef DEBUG_MEMORY
  mem_report("termination");
#endif /* DEBUG_MEMORY */

  return 0;
}
Example #4
0
static void
silcpurple_add_buddy_save(bool success, void *context)
{
	SilcPurpleBuddyRes r = context;
	PurpleBuddy *b = r->b;
	SilcClient client = r->client;
	SilcClientEntry client_entry;
	SilcAttributePayload attr;
	SilcAttribute attribute;
	SilcVCardStruct vcard;
	SilcAttributeObjMime message, extension;
#ifdef SILC_ATTRIBUTE_USER_ICON
	SilcAttributeObjMime usericon;
#endif
	SilcAttributeObjPk serverpk, usersign, serversign;
	gboolean usign_success = TRUE, ssign_success = TRUE;
	char filename[512], filename2[512], *fingerprint = NULL, *tmp;
	SilcUInt32 len;
	int i;

	if (!success) {
		/* The user did not trust the public key. */
		silcpurple_add_buddy_pk_no(r);
		silc_free(r);
		return;
	}

	if (r->offline) {
		/* User is offline.  Associate the imported public key with
		   this user. */
		fingerprint = silc_hash_fingerprint(NULL, r->offline_pk,
						    r->offline_pk_len);
		for (i = 0; i < strlen(fingerprint); i++)
			if (fingerprint[i] == ' ')
				fingerprint[i] = '_';
		g_snprintf(filename, sizeof(filename) - 1,
			   "%s" G_DIR_SEPARATOR_S "clientkeys" G_DIR_SEPARATOR_S "clientkey_%s.pub",
			   silcpurple_silcdir(), fingerprint);
		purple_blist_node_set_string((PurpleBlistNode *)b, "public-key", filename);
		purple_prpl_got_user_status(purple_buddy_get_account(r->b), purple_buddy_get_name(r->b), SILCPURPLE_STATUS_ID_OFFLINE, NULL);
		silc_free(fingerprint);
		silc_free(r->offline_pk);
		silc_free(r);
		return;
	}

	/* Get the client entry. */
	client_entry = silc_client_get_client_by_id(r->client, r->conn,
						    &r->client_id);
	if (!client_entry) {
		silc_free(r);
		return;
	}

	memset(&vcard, 0, sizeof(vcard));
	memset(&message, 0, sizeof(message));
	memset(&extension, 0, sizeof(extension));
#ifdef SILC_ATTRIBUTE_USER_ICON
	memset(&usericon, 0, sizeof(usericon));
#endif
	memset(&serverpk, 0, sizeof(serverpk));
	memset(&usersign, 0, sizeof(usersign));
	memset(&serversign, 0, sizeof(serversign));

	/* Now that we have the public key and we trust it now we
	   save the attributes of the buddy and update its status. */

	if (client_entry->attrs) {
		silc_dlist_start(client_entry->attrs);
		while ((attr = silc_dlist_get(client_entry->attrs))
		       != SILC_LIST_END) {
			attribute = silc_attribute_get_attribute(attr);

			switch (attribute) {
			case SILC_ATTRIBUTE_USER_INFO:
				if (!silc_attribute_get_object(attr, (void *)&vcard,
							       sizeof(vcard)))
					continue;
				break;

			case SILC_ATTRIBUTE_STATUS_MESSAGE:
				if (!silc_attribute_get_object(attr, (void *)&message,
							       sizeof(message)))
					continue;
				break;

			case SILC_ATTRIBUTE_EXTENSION:
				if (!silc_attribute_get_object(attr, (void *)&extension,
							       sizeof(extension)))
					continue;
				break;

#ifdef SILC_ATTRIBUTE_USER_ICON
			case SILC_ATTRIBUTE_USER_ICON:
				if (!silc_attribute_get_object(attr, (void *)&usericon,
							       sizeof(usericon)))
					continue;
				break;
#endif

			case SILC_ATTRIBUTE_SERVER_PUBLIC_KEY:
				if (serverpk.type)
					continue;
				if (!silc_attribute_get_object(attr, (void *)&serverpk,
							       sizeof(serverpk)))
					continue;
				break;

			case SILC_ATTRIBUTE_USER_DIGITAL_SIGNATURE:
				if (usersign.data)
					continue;
				if (!silc_attribute_get_object(attr, (void *)&usersign,
							       sizeof(usersign)))
					continue;
				break;

			case SILC_ATTRIBUTE_SERVER_DIGITAL_SIGNATURE:
				if (serversign.data)
					continue;
				if (!silc_attribute_get_object(attr, (void *)&serversign,
							       sizeof(serversign)))
					continue;
				break;

			default:
				break;
			}
		}
	}

	/* Verify the attribute signatures */

	if (usersign.data) {
		SilcPKCS pkcs;
		unsigned char *verifyd;
		SilcUInt32 verify_len;

		silc_pkcs_alloc((unsigned char*)"rsa", &pkcs);
		verifyd = silc_attribute_get_verify_data(client_entry->attrs,
							 FALSE, &verify_len);
		if (verifyd && silc_pkcs_public_key_set(pkcs, client_entry->public_key)){
			if (!silc_pkcs_verify_with_hash(pkcs, client->sha1hash,
							usersign.data,
							usersign.data_len,
							verifyd, verify_len))
				usign_success = FALSE;
		}
		silc_free(verifyd);
	}

	if (serversign.data && !strcmp(serverpk.type, "silc-rsa")) {
		SilcPublicKey public_key;
		SilcPKCS pkcs;
		unsigned char *verifyd;
		SilcUInt32 verify_len;

		if (silc_pkcs_public_key_decode(serverpk.data, serverpk.data_len,
						&public_key)) {
			silc_pkcs_alloc((unsigned char *)"rsa", &pkcs);
			verifyd = silc_attribute_get_verify_data(client_entry->attrs,
								 TRUE, &verify_len);
			if (verifyd && silc_pkcs_public_key_set(pkcs, public_key)) {
				if (!silc_pkcs_verify_with_hash(pkcs, client->sha1hash,
							       serversign.data,
							       serversign.data_len,
							       verifyd, verify_len))
					ssign_success = FALSE;
			}
			silc_pkcs_public_key_free(public_key);
			silc_free(verifyd);
		}
	}

	fingerprint = silc_fingerprint(client_entry->fingerprint,
				       client_entry->fingerprint_len);
	for (i = 0; i < strlen(fingerprint); i++)
		if (fingerprint[i] == ' ')
			fingerprint[i] = '_';

	if (usign_success || ssign_success) {
		struct passwd *pw;
		struct stat st;

		memset(filename2, 0, sizeof(filename2));

		/* Filename for dir */
		tmp = fingerprint + strlen(fingerprint) - 9;
		g_snprintf(filename, sizeof(filename) - 1,
			   "%s" G_DIR_SEPARATOR_S "friends" G_DIR_SEPARATOR_S "%s",
			   silcpurple_silcdir(), tmp);

		pw = getpwuid(getuid());
		if (!pw)
			return;

		/* Create dir if it doesn't exist */
		if ((g_stat(filename, &st)) == -1) {
			if (errno == ENOENT) {
				if (pw->pw_uid == geteuid()) {
					int ret = g_mkdir(filename, 0755);
					if (ret < 0)
						return;
				}
			}
		}

		/* Save VCard */
		g_snprintf(filename2, sizeof(filename2) - 1,
			   "%s" G_DIR_SEPARATOR_S "vcard", filename);
		if (vcard.full_name) {
			tmp = (char *)silc_vcard_encode(&vcard, &len);
			silc_file_writefile(filename2, tmp, len);
			silc_free(tmp);
		}

		/* Save status message */
		if (message.mime) {
			memset(filename2, 0, sizeof(filename2));
			g_snprintf(filename2, sizeof(filename2) - 1,
				   "%s" G_DIR_SEPARATOR_S "status_message.mime",
				   filename);
			silc_file_writefile(filename2, (char *)message.mime,
					    message.mime_len);
		}

		/* Save extension data */
		if (extension.mime) {
			memset(filename2, 0, sizeof(filename2));
			g_snprintf(filename2, sizeof(filename2) - 1,
				   "%s" G_DIR_SEPARATOR_S "extension.mime",
				   filename);
			silc_file_writefile(filename2, (char *)extension.mime,
					    extension.mime_len);
		}

#ifdef SILC_ATTRIBUTE_USER_ICON
		/* Save user icon */
		if (usericon.mime) {
			SilcMime m = silc_mime_decode(usericon.mime,
						      usericon.mime_len);
			if (m) {
				const char *type = silc_mime_get_field(m, "Content-Type");
				if (!strcmp(type, "image/jpeg") ||
				    !strcmp(type, "image/gif") ||
				    !strcmp(type, "image/bmp") ||
				    !strcmp(type, "image/png")) {
					const unsigned char *data;
					SilcUInt32 data_len;
					data = silc_mime_get_data(m, &data_len);
					if (data) {
						/* TODO: Check if SILC gives us something to use as the checksum instead */
						purple_buddy_icons_set_for_user(purple_buddy_get_account(r->b), purple_buddy_get_name(r->b), g_memdup(data, data_len), data_len, NULL);
					}
				}
				silc_mime_free(m);
			}
		}
#endif
	}

	/* Save the public key path to buddy properties, as it is used
	   to identify the buddy in the network (and not the nickname). */
	memset(filename, 0, sizeof(filename));
	g_snprintf(filename, sizeof(filename) - 1,
		   "%s" G_DIR_SEPARATOR_S "clientkeys" G_DIR_SEPARATOR_S "clientkey_%s.pub",
		   silcpurple_silcdir(), fingerprint);
	purple_blist_node_set_string((PurpleBlistNode *)b, "public-key", filename);

	/* Update online status */
	purple_prpl_got_user_status(purple_buddy_get_account(r->b), purple_buddy_get_name(r->b), SILCPURPLE_STATUS_ID_AVAILABLE, NULL);

	/* Finally, start watching this user so we receive its status
	   changes from the server */
	g_snprintf(filename2, sizeof(filename2) - 1, "+%s", filename);
	silc_client_command_call(r->client, r->conn, NULL, "WATCH", "-pubkey",
				 filename2, NULL);

	silc_free(fingerprint);
	silc_free(r);
}
Example #5
0
static char *makemsg(char *fname, char **mvec, int mvecsz,
		     size_t *mbufsize, int print_banner)
{
	register int ch, cnt;
	struct stat sbuf;
	FILE *fp;
	char *p, *lbuf, *tmpname, *mbuf;
	long line_max;

	line_max = sysconf(_SC_LINE_MAX);
	lbuf = xmalloc(line_max);

	if ((fp = xfmkstemp(&tmpname, NULL)) == NULL)
		err(EXIT_FAILURE, _("can't open temporary file"));
	unlink(tmpname);
	free(tmpname);

	if (print_banner == TRUE) {
		char *hostname = xgethostname();
		char *whom, *where, *date;
		struct passwd *pw;
		time_t now;

		if (!(whom = getlogin()) || !*whom)
			whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
		if (!whom) {
			whom = "someone";
			warn(_("cannot get passwd uid"));
		}
		where = ttyname(STDOUT_FILENO);
		if (!where) {
			where = "somewhere";
			warn(_("cannot get tty name"));
		} else if (strncmp(where, "/dev/", 5) == 0)
			where += 5;

		time(&now);
		date = xstrdup(ctime(&now));
		date[strlen(date) - 1] = '\0';

		/*
		 * all this stuff is to blank out a square for the message;
		 * we wrap message lines at column 79, not 80, because some
		 * terminals wrap after 79, some do not, and we can't tell.
		 * Which means that we may leave a non-blank character
		 * in column 80, but that can't be helped.
		 */
		/* snprintf is not always available, but the sprintf's here
		   will not overflow as long as %d takes at most 100 chars */
		fprintf(fp, "\r%79s\r\n", " ");
		sprintf(lbuf, _("Broadcast message from %s@%s (%s) (%s):"),
			      whom, hostname, where, date);
		fprintf(fp, "%-79.79s\007\007\r\n", lbuf);
		free(hostname);
		free(date);
	}
	fprintf(fp, "%79s\r\n", " ");

	 if (mvec) {
		/*
		 * Read message from argv[]
		 */
		int i;

		for (i = 0; i < mvecsz; i++) {
			fputs(mvec[i], fp);
			if (i < mvecsz - 1)
				fputc(' ', fp);
		}
		fputc('\r', fp);
		fputc('\n', fp);

	} else {
		/*
		 * read message from <file>
		 */
		if (fname) {
			/*
			 * When we are not root, but suid or sgid, refuse to read files
			 * (e.g. device files) that the user may not have access to.
			 * After all, our invoker can easily do "wall < file"
			 * instead of "wall file".
			 */
			uid_t uid = getuid();
			if (uid && (uid != geteuid() || getgid() != getegid()))
				errx(EXIT_FAILURE, _("will not read %s - use stdin."),
				     fname);

			if (!freopen(fname, "r", stdin))
				err(EXIT_FAILURE, _("cannot open %s"), fname);

		}

		/*
		 * Read message from stdin.
		 */
		while (fgets(lbuf, line_max, stdin)) {
			for (cnt = 0, p = lbuf; (ch = *p) != '\0'; ++p, ++cnt) {
				if (cnt == 79 || ch == '\n') {
					for (; cnt < 79; ++cnt)
						putc(' ', fp);
					putc('\r', fp);
					putc('\n', fp);
					cnt = 0;
				}
				if (ch == '\t')
					cnt += (7 - (cnt % 8));
				if (ch != '\n')
					fputc_careful(ch, fp, '^');
			}
		}
	}
	fprintf(fp, "%79s\r\n", " ");

	free(lbuf);
	rewind(fp);

	if (fstat(fileno(fp), &sbuf))
		err(EXIT_FAILURE, _("stat failed"));

	*mbufsize = (size_t) sbuf.st_size;
	mbuf = xmalloc(*mbufsize);

	if (fread(mbuf, 1, *mbufsize, fp) != *mbufsize)
		err(EXIT_FAILURE, _("fread failed"));

	if (close_stream(fp) != 0)
		errx(EXIT_FAILURE, _("write error"));
	return mbuf;
}
Example #6
0
File: ctx.c Project: 2asoft/freebsd
/*
 * Prescan command line for [-U user] argument
 * and fill context with defaults
 */
int
smb_ctx_init(struct smb_ctx *ctx, int argc, char *argv[],
	int minlevel, int maxlevel, int sharetype)
{
	int  opt, error = 0;
	uid_t euid;
	const char *arg, *cp;
	struct passwd *pwd;

	bzero(ctx,sizeof(*ctx));
	error = nb_ctx_create(&ctx->ct_nb);
	if (error)
		return error;
	ctx->ct_fd = -1;
	ctx->ct_parsedlevel = SMBL_NONE;
	ctx->ct_minlevel = minlevel;
	ctx->ct_maxlevel = maxlevel;
	ctx->ct_smbtcpport = SMB_TCP_PORT;

	ctx->ct_ssn.ioc_opt = SMBVOPT_CREATE;
	ctx->ct_ssn.ioc_timeout = 15;
	ctx->ct_ssn.ioc_retrycount = 4;
	ctx->ct_ssn.ioc_owner = SMBM_ANY_OWNER;
	ctx->ct_ssn.ioc_group = SMBM_ANY_GROUP;
	ctx->ct_ssn.ioc_mode = SMBM_EXEC;
	ctx->ct_ssn.ioc_rights = SMBM_DEFAULT;

	ctx->ct_sh.ioc_opt = SMBVOPT_CREATE;
	ctx->ct_sh.ioc_owner = SMBM_ANY_OWNER;
	ctx->ct_sh.ioc_group = SMBM_ANY_GROUP;
	ctx->ct_sh.ioc_mode = SMBM_EXEC;
	ctx->ct_sh.ioc_rights = SMBM_DEFAULT;
	ctx->ct_sh.ioc_owner = SMBM_ANY_OWNER;
	ctx->ct_sh.ioc_group = SMBM_ANY_GROUP;

	nb_ctx_setscope(ctx->ct_nb, "");
	euid = geteuid();
	if ((pwd = getpwuid(euid)) != NULL) {
		smb_ctx_setuser(ctx, pwd->pw_name);
		endpwent();
	} else if (euid == 0)
		smb_ctx_setuser(ctx, "root");
	else
		return 0;
	if (argv == NULL)
		return 0;
	for (opt = 1; opt < argc; opt++) {
		cp = argv[opt];
		if (strncmp(cp, "//", 2) != 0)
			continue;
		error = smb_ctx_parseunc(ctx, cp, sharetype, (const char**)&cp);
		if (error)
			return error;
		ctx->ct_uncnext = cp;
		break;
	}
	while (error == 0 && (opt = cf_getopt(argc, argv, ":E:L:U:")) != -1) {
		arg = cf_optarg;
		switch (opt) {
		    case 'E':
			error = smb_ctx_setcharset(ctx, arg);
			if (error)
				return error;
			break;
		    case 'L':
			error = nls_setlocale(arg);
			if (error)
				break;
			break;
		    case 'U':
			error = smb_ctx_setuser(ctx, arg);
			break;
		}
	}
	cf_optind = cf_optreset = 1;
	return error;
}
Example #7
0
void CapsH_drop() {
    CapsH_ruid = getuid();
    CapsH_euid = geteuid();
    seteuid(CapsH_ruid);
}
Example #8
0
int main(int argc, char **argv)
{
	sigset_t sigset;
	int signum = SIGALRM;
	int mode;
	struct thread_param *par;
	struct thread_stat *stat;
	pthread_attr_t thattr;
	int i, ret = -1;

#ifndef __XENO__
	if (geteuid()) {
		printf("need to run as root!\n");
		exit(-1);
	}
#endif

	mlockall(MCL_CURRENT | MCL_FUTURE);

	if (CONFIG_XENO_DEFAULT_PERIOD > 1000000)
		interval = CONFIG_XENO_DEFAULT_PERIOD;
	else
		interval = 1000000;
	distance = interval / 2;

	process_options(argc, argv);

	mode = use_nanosleep + use_system;

       	sigemptyset(&sigset);
       	sigaddset(&sigset, signum);
   	sigprocmask (SIG_BLOCK, &sigset, NULL);

	signal(SIGINT, sighand);
	signal(SIGTERM, sighand);

	par = calloc(num_threads, sizeof(struct thread_param));
	if (!par)
		goto out;
	stat = calloc(num_threads, sizeof(struct thread_stat));
	if (!stat)
		goto outpar;

	clock_gettime(clocksources[clocksel], &start);

	for (i = 0; i < num_threads; i++) {
		if (verbose) {
			stat[i].values = calloc(VALBUF_SIZE, sizeof(long));
			if (!stat[i].values)
				goto outall;
			par[i].bufmsk = VALBUF_SIZE - 1;
		}

		par[i].prio = priority;
		if (priority)
			priority--;
		par[i].clock = clocksources[clocksel];
		par[i].mode = mode;
		par[i].timermode = timermode;
		par[i].signal = signum;
		par[i].interval = interval;
		interval += distance;
		par[i].max_cycles = max_cycles;
		par[i].stats = &stat[i];
		stat[i].min = 1000000;
		stat[i].max = -1000000;
		stat[i].avg = 0.0;
		pthread_attr_init(&thattr);
		pthread_attr_setstacksize(&thattr, 131072);
		pthread_create(&stat[i].thread, &thattr, timerthread, &par[i]);
		stat[i].threadstarted = 1;
		stat[i].traced = (i == 0 && IPIPE_TRACE > 0);
	}

	while (!test_shutdown) {
		char lavg[256];
		int fd, len, allstopped;

		if (!verbose && !quiet) {
			fd = open("/proc/loadavg", O_RDONLY, 0666);
			len = read(fd, &lavg, 255);
			close(fd);
			lavg[len-1] = 0x0;
			printf("%s          \n\n", lavg);
		}

		allstopped = max_cycles ? 1 : 0;

		for (i = 0; i < num_threads; i++) {
			print_stat(&par[i], i, verbose);
			if (stat[i].cycles < max_cycles)
				allstopped = 0;
		}
		usleep(10000);
		if (test_shutdown || allstopped == num_threads)
			break;
		if (!verbose && !quiet)
			printf("\033[%dA", num_threads + 2);
	}
	if (quiet) {
		quiet = 0; /* Now we want to output the statistics */
		for (i = 0; i < num_threads; i++) {
			print_stat(&par[i], i, verbose);
		}
	}
	ret = 0;
 outall:
	test_shutdown = 1;
	for (i = 0; i < num_threads; i++) {
		if (stat[i].threadstarted > 0)
			pthread_kill(stat[i].thread, SIGTERM);
		if (stat[i].threadstarted)
			pthread_join(stat[i].thread, NULL);
		if (stat[i].values)
			free(stat[i].values);
	}
	free(stat);
 outpar:
	free(par);
 out:
	exit(ret);
}
Example #9
0
/*ARGSUSED*/
cfga_err_t
cfga_change_state(
    cfga_cmd_t state_change_cmd,
    const char *ap_id,
    const char *options,
    struct cfga_confirm *confp,
    struct cfga_msg *msgp,
    char **errstring,
    cfga_flags_t flags)
{
	int		ret;
	int 		len;
	char		*msg;
	char		*devpath;
	nvlist_t	*nvl = NULL;
	ap_rstate_t	rstate;
	ap_ostate_t	ostate;
	devctl_hdl_t	hdl = NULL;
	cfga_sata_ret_t	rv = CFGA_SATA_OK;
	char		*pdyn;
	char		*str_type;
	size_t		size;
	boolean_t	pmult = B_FALSE;

	/*
	 * All sub-commands which can change state of device require
	 * root privileges.
	 */
	if (geteuid() != 0) {
		rv = CFGA_SATA_PRIV;
		goto bailout;
	}

	if ((rv = verify_params(ap_id, options, errstring)) != CFGA_SATA_OK) {
		(void) cfga_help(msgp, options, flags);
		goto bailout;
	}

	if ((rv = setup_for_devctl_cmd(ap_id, &hdl, &nvl,
	    DC_RDONLY)) != CFGA_SATA_OK) {
		goto bailout;
	}

	/*
	 * Checking device type. A port multiplier is not configurable - it is
	 * already configured as soon as it is connected.
	 */
	if ((rv = do_control_ioctl(ap_id, SATA_CFGA_GET_AP_TYPE, NULL,
	    (void **)&str_type, &size)) != CFGA_SATA_OK) {
		/* no such deivce */
		goto bailout;
	}
	if (strncmp(str_type, "sata-pmult", sizeof ("sata-pmult")) == 0) {
		pmult = B_TRUE;
	}

	switch (state_change_cmd) {
	case CFGA_CMD_CONFIGURE:
		if (pmult == B_TRUE) {
			rv = CFGA_SATA_HWOPNOTSUPP;
			goto bailout;
		}

		if ((rv = port_state(hdl, nvl, &rstate, &ostate)) !=
		    CFGA_SATA_OK)
			goto bailout;

		if (ostate == AP_OSTATE_CONFIGURED) {
			rv = CFGA_SATA_ALREADY_CONFIGURED;
			goto bailout;
		}
		/* Disallow dynamic AP name component */
		if (GET_DYN(ap_id) != NULL) {
			rv = CFGA_SATA_INVALID_DEVNAME;
			goto bailout;
		}

		if (rstate == AP_RSTATE_EMPTY) {
			rv = CFGA_SATA_NOT_CONNECTED;
			goto bailout;
		}
		rv = CFGA_SATA_OK;

		if (devctl_ap_configure(hdl, nvl) != 0) {
			rv = CFGA_SATA_DEV_CONFIGURE;
			goto bailout;
		}

		devpath = sata_get_devicepath(ap_id);
		if (devpath == NULL) {
			int i;
			/*
			 * Try for some time as SATA hotplug thread
			 * takes a while to create the path then
			 * eventually give up.
			 */
			for (i = 0; i < 12 && (devpath == NULL); i++) {
				(void) sleep(6);
				devpath = sata_get_devicepath(ap_id);
			}

			if (devpath == NULL) {
				rv = CFGA_SATA_DEV_CONFIGURE;
				break;
			}
		}

		S_FREE(devpath);
		break;

	case CFGA_CMD_UNCONFIGURE:
		if (pmult == B_TRUE) {
			rv = CFGA_SATA_HWOPNOTSUPP;
			goto bailout;
		}

		if ((rv = port_state(hdl, nvl, &rstate, &ostate)) !=
		    CFGA_SATA_OK)
			goto bailout;

		if (rstate != AP_RSTATE_CONNECTED) {
			rv = CFGA_SATA_NOT_CONNECTED;
			goto bailout;
		}

		if (ostate != AP_OSTATE_CONFIGURED) {
			rv = CFGA_SATA_NOT_CONFIGURED;
			goto bailout;
		}
		/* Strip off AP name dynamic component, if present */
		if ((pdyn = GET_DYN(ap_id)) != NULL) {
			*pdyn = '\0';
		}

		rv = CFGA_SATA_OK;

		len = strlen(SATA_CONFIRM_DEVICE) +
		    strlen(SATA_CONFIRM_DEVICE_SUSPEND) +
		    strlen("Unconfigure") + strlen(ap_id);
		if ((msg = (char *)calloc(len +3, 1)) != NULL) {
			(void) snprintf(msg, len + 3, "Unconfigure"
			    " %s%s\n%s",
			    SATA_CONFIRM_DEVICE, ap_id,
			    SATA_CONFIRM_DEVICE_SUSPEND);
		}

		if (!sata_confirm(confp, msg)) {
			free(msg);
			rv = CFGA_SATA_NACK;
			break;
		}
		free(msg);

		devpath = sata_get_devicepath(ap_id);
		if (devpath == NULL) {
			(void) printf(
			    "cfga_change_state: get device path failed\n");
			rv = CFGA_SATA_DEV_UNCONFIGURE;
			break;
		}

		if ((rv = sata_rcm_offline(ap_id, errstring, devpath, flags))
		    != CFGA_SATA_OK) {
			break;
		}

		ret = devctl_ap_unconfigure(hdl, nvl);

		if (ret != 0) {
			rv = CFGA_SATA_DEV_UNCONFIGURE;
			if (errno == EBUSY) {
				rv = CFGA_SATA_BUSY;
			}
			(void) sata_rcm_online(ap_id, errstring, devpath,
			    flags);
		} else {
			(void) sata_rcm_remove(ap_id, errstring, devpath,
			    flags);

		}
		S_FREE(devpath);

		break;

	case CFGA_CMD_DISCONNECT:
		if ((rv = port_state(hdl, nvl, &rstate, &ostate)) !=
		    CFGA_SATA_OK)
			goto bailout;

		if (rstate == AP_RSTATE_DISCONNECTED) {
			rv = CFGA_SATA_DISCONNECTED;
			goto bailout;
		}

		/* Strip off AP name dynamic component, if present */
		if ((pdyn = GET_DYN(ap_id)) != NULL) {
			*pdyn = '\0';
		}


		rv = CFGA_SATA_OK; /* other statuses don't matter */

		/*
		 * If the port originally with device attached and was
		 * unconfigured already, the devicepath for the sd will be
		 * removed. sata_get_devicepath in this case is not necessary.
		 */
		/* only call rcm_offline if the state was CONFIGURED */
		if (ostate == AP_OSTATE_CONFIGURED &&
		    pmult == B_FALSE) {
			devpath = sata_get_devicepath(ap_id);
			if (devpath == NULL) {
				(void) printf(
				    "cfga_change_state: get path failed\n");
				rv = CFGA_SATA_DEV_UNCONFIGURE;
				break;
			}

			len = strlen(SATA_CONFIRM_DEVICE) +
			    strlen(SATA_CONFIRM_DEVICE_SUSPEND) +
			    strlen("Disconnect") + strlen(ap_id);
			if ((msg = (char *)calloc(len +3, 1)) != NULL) {
				(void) snprintf(msg, len + 3,
				    "Disconnect"
				    " %s%s\n%s",
				    SATA_CONFIRM_DEVICE, ap_id,
				    SATA_CONFIRM_DEVICE_SUSPEND);
			}
			if (!sata_confirm(confp, msg)) {
				free(msg);
				rv = CFGA_SATA_NACK;
				break;
			}
			free(msg);

			if ((rv = sata_rcm_offline(ap_id, errstring,
			    devpath, flags)) != CFGA_SATA_OK) {
				break;
			}

			ret = devctl_ap_unconfigure(hdl, nvl);
			if (ret != 0) {
				(void) printf(
				    "devctl_ap_unconfigure failed\n");
				rv = CFGA_SATA_DEV_UNCONFIGURE;
				if (errno == EBUSY)
					rv = CFGA_SATA_BUSY;
				(void) sata_rcm_online(ap_id, errstring,
				    devpath, flags);
				S_FREE(devpath);

				/*
				 * The current policy is that if unconfigure
				 * failed, do not continue with disconnect.
				 * If the port needs to be forced into the
				 * disconnect (shutdown) state,
				 * the -x sata_port_poweroff command should be
				 * used instead of -c disconnect
				 */
				break;
			} else {
				(void) printf("%s\n",
				    ERR_STR(CFGA_SATA_DEVICE_UNCONFIGURED));
				(void) sata_rcm_remove(ap_id, errstring,
				    devpath, flags);
			}
			S_FREE(devpath);
		} else if (rstate == AP_RSTATE_CONNECTED ||
		    rstate == AP_RSTATE_EMPTY) {
			len = strlen(SATA_CONFIRM_PORT) +
			    strlen(SATA_CONFIRM_PORT_DISABLE) +
			    strlen("Deactivate Port") + strlen(ap_id);
			if ((msg = (char *)calloc(len +3, 1)) != NULL) {
				(void) snprintf(msg, len +3,
				    "Disconnect"
				    " %s%s\n%s",
				    SATA_CONFIRM_PORT, ap_id,
				    SATA_CONFIRM_PORT_DISABLE);
			}
			if (!sata_confirm(confp, msg)) {
				free(msg);
				rv = CFGA_SATA_NACK;
				break;
			}
		}
		ret = devctl_ap_disconnect(hdl, nvl);
		if (ret != 0) {
			rv = CFGA_SATA_IOCTL;
			if (errno == EBUSY) {
				rv = CFGA_SATA_BUSY;
			}
		}
		break;

	case CFGA_CMD_CONNECT:
		if ((rv = port_state(hdl, nvl, &rstate, &ostate)) !=
		    CFGA_SATA_OK)
			goto bailout;

		if (rstate == AP_RSTATE_CONNECTED) {
			rv = CFGA_SATA_ALREADY_CONNECTED;
			goto bailout;
		}

		len = strlen(SATA_CONFIRM_PORT) +
		    strlen(SATA_CONFIRM_PORT_ENABLE) +
		    strlen("Activate Port") + strlen(ap_id);
		if ((msg = (char *)calloc(len +3, 1)) != NULL) {
			(void) snprintf(msg, len +3, "Activate"
			    " %s%s\n%s",
			    SATA_CONFIRM_PORT, ap_id,
			    SATA_CONFIRM_PORT_ENABLE);
		}
		if (!sata_confirm(confp, msg)) {
			rv = CFGA_SATA_NACK;
			break;
		}

		/* Disallow dynamic AP name component */
		if (GET_DYN(ap_id) != NULL) {
			rv = CFGA_SATA_INVALID_DEVNAME;
			goto bailout;
		}

		ret = devctl_ap_connect(hdl, nvl);
		if (ret != 0) {
			rv = CFGA_SATA_IOCTL;
		} else {
			rv = CFGA_SATA_OK;
		}

		break;

	case CFGA_CMD_LOAD:
	case CFGA_CMD_UNLOAD:
		(void) cfga_help(msgp, options, flags);
		rv = CFGA_SATA_OPNOTSUPP;
		break;

	case CFGA_CMD_NONE:
	default:
		(void) cfga_help(msgp, options, flags);
		rv = CFGA_SATA_INTERNAL_ERROR;
	}

bailout:
	cleanup_after_devctl_cmd(hdl, nvl);

	return (sata_err_msg(errstring, rv, ap_id, errno));
}
Example #10
0
/**
 * @brief
 *	The main function in C - entry point
 *
 * @param[in]  argc - argument count
 * @param[in]  argv - pointer to argument array
 *
 * @return  int
 * @retval  0 - success
 * @retval  !0 - error
 */
int
main(int argc, char *argv[])
{
	int i, rc;
	char passwd[MAX_PASSWORD_LEN + 1] = {'\0'};
	char passwd2[MAX_PASSWORD_LEN + 1];
	char *pquoted;
	char pwd_file[MAXPATHLEN + 1];
	char userid[LOGIN_NAME_MAX + 1];
	int fd, errflg = 0;
	int gen_pwd = 0;
	char sqlbuff[1024];
	int db_conn_error=0;
	char *db_errmsg = NULL;
	int pmode;
	int change_user = 0;
	char *olduser;
	int update_db = 0;
	char getopt_format[5];
	char prog[]="pbs_ds_password";
	char errmsg[PBS_MAX_DB_CONN_INIT_ERR + 1];

	conn = NULL;
	pwd_file_new[0]=0;

	/*test for real deal or just version and exit*/
	PRINT_VERSION_AND_EXIT(argc, argv);

	/* read configuration file */
	if (pbs_loadconf(0) == 0) {
		fprintf(stderr, "%s: Could not load pbs configuration\n", prog);
		return (-1);
	}

	/* backup old user name */
	if ((olduser = pbs_get_dataservice_usr(errmsg, PBS_MAX_DB_CONN_INIT_ERR)) == NULL) {
		fprintf(stderr, "%s: Could not retrieve current data service user\n", prog);
		if (strlen(errmsg) > 0)
			fprintf(stderr, "%s\n", errmsg);
		return (-1);
	}

	if (pbs_conf.pbs_data_service_host == NULL)
		update_db = 1;

	userid[0]=0; /* empty user id */

	strcpy(getopt_format, "rC:");

	while ((i = getopt(argc, argv, getopt_format)) != EOF) {
		switch (i) {
			case 'r':
				gen_pwd = 1;
				break;
			case 'C':
				strcpy(userid, optarg);
				break;
			case '?':
			default:
				errflg++;
		}
	}

	if (errflg) {
		fprintf(stderr, "\nusage:\t%s [-r] [-C username]\n", prog);
		fprintf(stderr, "      \t%s --version\n", prog);
		return (-1);
	}

    /* NOTE : This functionality is added just for the automation testing purpose.
     * Usage: pbs_ds_password <password>
     */
	if (argv[optind] != NULL) {
		gen_pwd = 0;
		strncpy(passwd, argv[optind], sizeof(passwd));
		passwd[sizeof(passwd) - 1] = '\0';
	}

	/* check admin privileges */
#ifdef WIN32
	if (!isAdminPrivilege(getlogin())) {
		fprintf(stderr, "pbs_ds_password: Must be run by Admin\n");
		return (1);
	}
#else
	if ((getuid() != 0) || (geteuid() != 0)) {
		fprintf(stderr, "%s: Must be run by root\n", prog);
		return (1);
	}
#endif	/* WIN32 */

	change_user = 0;
	/* if the -C option was specified read the user from pbs.conf */
	if (userid[0] != 0) {
		if (strcmp(olduser, userid) != 0) {
			change_user = 1;
		}
	}

	if (change_user == 1) {
		/* check that the supplied user-id exists (and is non-root on unix) */
		if (check_user(userid) != 0) {
#ifdef WIN32
			fprintf(stderr, "\n%s: User-id %s does not exist\n", prog, userid);
#else
			fprintf(stderr, "\n%s: User-id %s does not exist/is root user/home dir is not accessible\n", prog, userid);
#endif
			return (-1);
		}
	}

	atexit(cleanup);

	if (update_db == 1) {
		/* then connect to database */
		conn = pbs_db_init_connection(NULL, PBS_DB_CNT_TIMEOUT_NORMAL, 1, &db_conn_error, errmsg, PBS_MAX_DB_CONN_INIT_ERR);
		if (!conn) {
			get_db_errmsg(db_conn_error, &db_errmsg);
			fprintf(stderr, "%s: %s\n", prog, db_errmsg);
			if (strlen(errmsg) > 0)
				fprintf(stderr, "%s\n", errmsg);
			return -1;
		}
		db_conn_error = pbs_db_connect(conn);
		if (db_conn_error == PBS_DB_SUCCESS && change_user == 1) {
			/* able to connect ? Thats bad, PBS or dataservice is running */
			fprintf(stderr, "%s: PBS Services and/or PBS Data Service is running\n", prog);
			fprintf(stderr, "                 Stop PBS and Data Services before changing Data Service user\n");
			return (-1);
		}

		if (db_conn_error != PBS_DB_SUCCESS) {
			if (db_conn_error == PBS_DB_CONNREFUSED) {
				/* start db only if it was not already running */
				if (pbs_startup_db(&db_errmsg) != 0) {
					if (db_errmsg)
						fprintf(stderr, "%s: Failed to start PBS dataservice:[%s]\n", prog, db_errmsg);
					else
						fprintf(stderr, "%s: Failed to start PBS dataservice\n", prog);
					return (-1);
				}
				started_db = 1;
			}
			db_conn_error = pbs_db_connect(conn);
			if (db_conn_error != PBS_DB_SUCCESS) {
				get_db_errmsg(db_conn_error, &db_errmsg);
				if (conn->conn_db_err)
					fprintf(stderr, "%s: Could not connect to PBS data service:%s:[%s]\n", prog,
						db_errmsg, (char*)conn->conn_db_err);
				else
					fprintf(stderr, "%s: Could not connect to PBS data service:%s\n", prog, db_errmsg);
				return (-1);
			}
		}
	}

	if (gen_pwd == 0 && passwd[0] == '\0') {
		/* ask user to enter password twice */
		printf("Enter the password:"******"\nRe-enter the password:"******"\n\n");
		if (strcmp(passwd, passwd2) != 0) {
			fprintf(stderr, "Entered passwords do not match\n");
			return (-2);
		}
		if (strlen(passwd) == 0) {
			fprintf(stderr, "Blank password is not allowed\n");
			return (-2);
		}
	} else if (gen_pwd == 1) {
		gen_password(passwd, 16);
	}

	rc = pbs_encrypt_pwd(passwd, &cred_type, &cred_buf, &cred_len);
	if (rc != 0) {
		fprintf(stderr, "%s: Failed to encrypt password\n", prog);
		return (-1);
	}

	/* escape password to use in sql strings later */
	if ((pquoted = pbs_db_escape_str(conn, passwd)) == NULL) {
		fprintf(stderr, "%s: Out of memory\n", prog);
		return -1;
	}

#ifdef WIN32
	sprintf(pwd_file_new, "%s\\server_priv\\db_password.new", pbs_conf.pbs_home_path);
	sprintf(pwd_file, "%s\\server_priv\\db_password", pbs_conf.pbs_home_path);
#else
	sprintf(pwd_file_new, "%s/server_priv/db_password.new", pbs_conf.pbs_home_path);
	sprintf(pwd_file, "%s/server_priv/db_password", pbs_conf.pbs_home_path);
#endif

	/* write encrypted password to the password file */
#ifdef WIN32
	pmode = _S_IWRITE | _S_IREAD;
	fix_perms2(pwd_file_new, pwd_file);
	if ((fd = open(pwd_file_new, O_WRONLY | O_TRUNC | O_CREAT | O_Sync | O_BINARY,
		pmode)) == -1)
#else
	pmode = 0600;
	if ((fd = open(pwd_file_new, O_WRONLY | O_TRUNC | O_CREAT | O_Sync,
		pmode)) == -1)
#endif
	{
		perror("open/create failed");
		fprintf(stderr, "%s: Unable to create file %s\n", prog, pwd_file_new);
		return (-1);
	}

#ifdef WIN32
	secure_file(pwd_file_new, "Administrators",
		READS_MASK|WRITES_MASK|STANDARD_RIGHTS_REQUIRED);
	setmode(fd, O_BINARY);
#endif

	if (update_db == 1) {
		/* change password only if this config option is not set */

		if (pbs_db_begin_trx(conn, 0, 0) != 0) {
			fprintf(stderr, "%s: Could not start transaction\n", prog);
			unlink(pwd_file_new);
			return -1;
		}

		if (change_user == 1) {
			/* check whether user exists */
			snprintf(sqlbuff, sizeof(sqlbuff),
				"select usename from pg_user where usename = '%s'",
				userid);
			if (pbs_db_execute_str(conn, sqlbuff) == 1) {
				/* now attempt to create new user & set the database passwd to the un-encrypted password */
				snprintf(sqlbuff, sizeof(sqlbuff),
					"create user \"%s\" SUPERUSER ENCRYPTED PASSWORD '%s'",
					userid, pquoted);
			} else {
				/* attempt to alter new user & set the database passwd to the un-encrypted password */
				snprintf(sqlbuff, sizeof(sqlbuff),
					"alter user \"%s\" SUPERUSER ENCRYPTED PASSWORD '%s'",
					userid, pquoted);
			}
			memset(passwd, 0, sizeof(passwd));
			memset(passwd2, 0, sizeof(passwd2));
			memset(pquoted, 0, (sizeof(char) * strlen(pquoted)));
			if (pbs_db_execute_str(conn, sqlbuff) == -1) {
				fprintf(stderr, "%s: Failed to create/alter user id %s\n", prog, userid);
				(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
				return -1;
			}
		} else {
			/* now attempt to set the database passwd to the un-encrypted password */
			/* alter user ${user} SUPERUSER ENCRYPTED PASSWORD '${passwd}' */
			sprintf(sqlbuff, "alter user \"%s\" SUPERUSER ENCRYPTED PASSWORD '%s'",
				olduser, pquoted);
			memset(passwd, 0, sizeof(passwd));
			memset(passwd2, 0, sizeof(passwd2));
			memset(pquoted, 0, (sizeof(char) * strlen(pquoted)));
			if (pbs_db_execute_str(conn, sqlbuff) == -1) {
				fprintf(stderr, "%s: Failed to create/alter user id %s\n", prog, userid);
				(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
				return -1;
			}
		}
	}

	if (write(fd, cred_buf, cred_len) != cred_len) {
		perror("write failed");
		fprintf(stderr, "%s: Unable to write to file %s\n", prog, pwd_file_new);
		if (update_db == 1) {
			(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
		}
		return -1;
	}
	close(fd);
	free(cred_buf);

#ifdef WIN32
	if (MoveFileEx(pwd_file_new, pwd_file,
		MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) == 0) {
		errno = GetLastError();
		fprintf(stderr, "MoveFileEx(%s, %s) failed!",
			pwd_file_new, pwd_file);
		if (update_db == 1) {
			(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
		}
		return (-1);
	}
#else
	if (rename(pwd_file_new, pwd_file) != 0) {
		if (update_db == 1) {
			(void) pbs_db_end_trx(conn, PBS_DB_ROLLBACK);
		}
		return (-1);
	}
#endif

	if (update_db == 1) {
		/* commit  to database */
		(void) pbs_db_end_trx(conn, PBS_DB_COMMIT);
		cleanup(); /* cleanup will disconnect and delete tmp file too */
	}

	printf("---> Updated user password\n");
	if (update_db == 1 && change_user == 1) {
		printf("---> Updated user in datastore\n");
		printf("---> Stored user password in datastore\n");
	}

	if (change_user == 1) {
		char usr_file[MAXPATHLEN + 1];
#ifdef WIN32
		sprintf(usr_file, "%s\\server_priv\\db_user", pbs_conf.pbs_home_path);
#else
		sprintf(usr_file, "%s/server_priv/db_user", pbs_conf.pbs_home_path);
#endif
		/* update PBS_HOME/server_priv/db_user file with the new user name */
		if (update_db_usr(usr_file, userid) != 0) {
			fprintf(stderr, "Unable to update file %s\n", usr_file);
			return -1;
		}
		printf("---> Updated new user\n");
	}

	if (update_db == 1 && change_user == 1) {
		char datastore[MAXPATHLEN + 1];
#ifndef WIN32
		/* ownership is changed only for Unix users
		 * On windows, these files are allways owned by the user who installed the database
		 * and writable by administrators anyway
		 */
		sprintf(datastore, "%s/datastore", pbs_conf.pbs_home_path);
		/* change ownership of the datastore directories to the new user, so that db can be started again */
		if (change_ownership(datastore, userid) != 0) {
			fprintf(stderr, "%s: Failed to change ownership on path %s\n", prog, datastore);
			return -1;
		}
		printf("---> Changed ownership of %s to user %s\n", datastore, userid);
#endif

		/* reload configuration file */
		if (pbs_loadconf(1) == 0) {
			fprintf(stderr, "%s: Could not load pbs configuration\n", prog);
			return (-1);
		}

		if (pbs_startup_db(&db_errmsg) != 0) {
			if (db_errmsg)
				fprintf(stderr, "%s: Failed to start PBS dataservice as new user:[%s]\n", prog, db_errmsg);
			else
				fprintf(stderr, "%s: Failed to start PBS dataservice as new user\n", prog);
			return (-1);
		}
		started_db = 1;

		/* connect again to drop the old user */
		conn = pbs_db_init_connection(NULL, PBS_DB_CNT_TIMEOUT_NORMAL, 1, &db_conn_error, errmsg, PBS_MAX_DB_CONN_INIT_ERR);
		if (!conn) {
			get_db_errmsg(db_conn_error, &db_errmsg);
			fprintf(stderr, "%s: %s\n", prog, db_errmsg);
			if (strlen(errmsg) > 0)
				fprintf(stderr, "%s\n", errmsg);
			return -1;
		}
		db_conn_error = pbs_db_connect(conn);
		if (db_conn_error != PBS_DB_SUCCESS) {
			get_db_errmsg(db_conn_error, &db_errmsg);
			if (conn->conn_db_err)
				fprintf(stderr, "%s: Could not connect to PBS data service as new user:%s[%s]\n", prog,
					db_errmsg, (char*)conn->conn_db_err);
			else
				fprintf(stderr, "%s: Could not connect to PBS data service as new user:%s\n", prog, db_errmsg);
			return (-1);
		}
		/* delete the old user from the database */
		sprintf(sqlbuff, "drop user \"%s\"", olduser);
		pbs_db_execute_str(conn, sqlbuff);
	}
	printf("---> Success\n");

	return (0);
}
Example #11
0
struct dump_dir *dd_opendir(const char *dir, int flags)
{
    struct dump_dir *dd = dd_init();

    dir = dd->dd_dirname = rm_trailing_slashes(dir);

    struct stat stat_buf;
    stat(dir, &stat_buf);
    /* & 0666 should remove the executable bit */
    dd->mode = (stat_buf.st_mode & 0666);

    errno = 0;
    if (dd_lock(dd, WAIT_FOR_OTHER_PROCESS_USLEEP, flags) < 0)
    {
        if ((flags & DD_OPEN_READONLY) && errno == EACCES)
        {
            /* Directory is not writable. If it seems to be readable,
             * return "read only" dd, not NULL */
            if (stat(dir, &stat_buf) == 0
             && S_ISDIR(stat_buf.st_mode)
             && access(dir, R_OK) == 0
            ) {
                return dd;
            }
        }
        if (errno == EISDIR)
        {
            /* EISDIR: dd_lock can lock the dir, but it sees no time file there,
             * even after it retried many times. It must be an ordinary directory!
             *
             * Without this check, e.g. abrt-action-print happily prints any current
             * directory when run without arguments, because its option -d DIR
             * defaults to "."!
             */
            error_msg("'%s' is not a dump directory", dir);
        }
        else if (errno == ENOENT || errno == ENOTDIR)
        {
            if (!(flags & DD_FAIL_QUIETLY_ENOENT))
                error_msg("'%s' does not exist", dir);
        }
        else
        {
            if (!(flags & DD_FAIL_QUIETLY_EACCES))
                perror_msg("Can't access '%s'", dir);
        }
        dd_close(dd);
        return NULL;
    }

    dd->dd_uid = (uid_t)-1L;
    dd->dd_gid = (gid_t)-1L;
    if (geteuid() == 0)
    {
        /* In case caller would want to create more files, he'll need uid:gid */
        struct stat stat_buf;
        if (stat(dir, &stat_buf) != 0 || !S_ISDIR(stat_buf.st_mode))
        {
            error_msg("Can't stat '%s', or it is not a directory", dir);
            dd_close(dd);
            return NULL;
        }
        dd->dd_uid = stat_buf.st_uid;
        dd->dd_gid = stat_buf.st_gid;
    }

    return dd;
}
Example #12
0
static void do_setup(int argc, char *argv[])
{
	if (!tst_test)
		tst_brk(TBROK, "No tests to run");

	if (tst_test->tconf_msg)
		tst_brk(TCONF, "%s", tst_test->tconf_msg);

	assert_test_fn();

	tid = get_tid(argv);

	if (tst_test->sample)
		tst_test = tst_timer_test_setup(tst_test);

	parse_opts(argc, argv);

	if (tst_test->needs_root && geteuid() != 0)
		tst_brk(TCONF, "Test needs to be run as root");

	if (tst_test->min_kver)
		check_kver();

	if (tst_test->format_device)
		tst_test->needs_device = 1;

	if (tst_test->mount_device) {
		tst_test->needs_device = 1;
		tst_test->format_device = 1;
	}

	if (tst_test->all_filesystems)
		tst_test->needs_device = 1;

	setup_ipc();

	if (needs_tmpdir() && !tst_tmpdir_created())
		tst_tmpdir();

	if (tst_test->mntpoint)
		SAFE_MKDIR(tst_test->mntpoint, 0777);

	if ((tst_test->needs_rofs || tst_test->mount_device ||
	     tst_test->all_filesystems) && !tst_test->mntpoint) {
		tst_brk(TBROK, "tst_test->mntpoint must be set!");
	}

	if (tst_test->needs_rofs) {
		/* If we failed to mount read-only tmpfs. Fallback to
		 * using a device with empty read-only filesystem.
		 */
		if (mount(NULL, tst_test->mntpoint, "tmpfs", MS_RDONLY, NULL)) {
			tst_res(TINFO | TERRNO, "Can't mount tmpfs read-only"
				" at %s, setting up a device instead\n",
				tst_test->mntpoint);
			tst_test->mount_device = 1;
			tst_test->needs_device = 1;
			tst_test->format_device = 1;
			tst_test->mnt_flags = MS_RDONLY;
		} else {
			mntpoint_mounted = 1;
		}
	}

	if (tst_test->needs_device && !mntpoint_mounted) {
		tdev.dev = tst_acquire_device_(NULL, tst_test->dev_min_size);

		if (!tdev.dev)
			tst_brk(TCONF, "Failed to acquire device");

		tst_device = &tdev;

		if (tst_test->dev_fs_type)
			tdev.fs_type = tst_test->dev_fs_type;
		else
			tdev.fs_type = tst_dev_fs_type();

		if (!tst_test->all_filesystems)
			prepare_device();
	}

	if (tst_test->resource_files)
		copy_resources();
}
Example #13
0
//
//  OS_Get_EUID: C
// 
// Return the effective user ID
//
REBINT OS_Get_EUID()
{
    return geteuid();
}
Example #14
0
void initService(struct Service *service, const char *arg) {
  // The first part of the argument is the path where the service should
  // be mounted. Remove any trailing slashes and make sure there is exactly
  // one leading slash before copying it into service->path.
  char *desc;
  check(desc                                = strdup(arg));
  while (*arg == '/') {
    arg++;
  }
  char *ptr;
  if ((ptr = strchr(arg, ':')) == NULL) {
  error:
    fatal("[config] Syntax error in service description \"%s\"!", desc);
  }
  service->id                               = -1;
  check(service->path                       = malloc(ptr - arg + 2));
  ((char *)service->path)[0]                = '/';
  memcpy((char *)service->path + 1, arg, ptr - arg);
  ((char *)service->path)[ptr - arg + 1]    = '\000';
  while (service->path[1] && strrchr(service->path, '\000')[-1] == '/') {
    strrchr(service->path, '\000')[-1]      = '\000';
  }
  arg                                       = ptr + 1;

#ifdef HAVE_BIN_LOGIN
  // The next part of the argument is either the word 'LOGIN' or the
  // application definition.
  if (!strcmp(arg, "LOGIN")) {
    if (geteuid()) {
      fatal("[config] Must be \"root\" to invoke LOGIN service!");
    }
    service->useLogin                       = 1;
    service->useHomeDir                     = 0;
    service->authUser                       = 0;
    service->useDefaultShell                = 0;
    service->uid                            = 0;
    service->gid                            = 0;
    check(service->user                     = strdup("root"));
    check(service->group                    = strdup("root"));
    check(service->cwd                      = strdup("/"));
    check(service->cmdline                  = strdup(
                                                  "/bin/login -p -h ${peer}"));
  } else
#endif
  if (!strcmp(arg, "SSH") || !strncmp(arg, "SSH:", 4)) {
    service->useLogin                       = 0;
    service->useHomeDir                     = 0;
    service->authUser                       = 2;
    service->useDefaultShell                = 0;
    service->uid                            = -1;
    service->gid                            = -1;
    service->user                           = NULL;
    service->group                          = NULL;
    check(service->cwd                      = strdup("/"));
    char *host;
    char *sshPort;
    check(host                              = strdup("localhost"));
    check(sshPort                           = strdup("22"));

    if ((ptr                                = strchr(arg, ':')) != NULL) {
      ptr                                   = ptr + 1;
      if (*ptr) {
        char *tmp                           = strchr(ptr, ':');
        if (tmp == NULL) {
          // If the second ":" is not found, keep as host whatever is after first ":".
          free(host);
          check(host                        = strdup(ptr));
        } else {
          // If we find a second ":", keep as a host whatever is in between first ":"
          // and second ":" and as sshPort whatever is after second ":".
          int size                          = (tmp - ptr + 1);
          free(host);
          free(sshPort);
          check(host                        = malloc(size));
          memset(host, 0, size);
          memcpy(host, ptr, size - 1);
          check(sshPort                     = strdup(tmp + 1));
        }
      }
    }

    // Don't allow manipulation of the SSH command line through "creative" use
    // of the host name.
    for (char *h = host; *h; h++) {
      char ch                               = *h;
      if (!((ch >= '0' && ch <= '9') ||
            (ch >= 'A' && ch <= 'Z') ||
            (ch >= 'a' && ch <= 'z') ||
            ch == '-' || ch == '.')) {
        fatal("[config] Invalid hostname \"%s\" in service definition!", host);
      }
    }

    // Don't allow manipulation of the SSH command line through "creative" use
    // of the port.
    for (char *h = sshPort; *h; h++) {
      char ch                               = *h;
      if (!(ch >= '0' && ch <= '9')) {
        fatal("[config] Invalid port \"%s\" in service definition!", sshPort);
      }
    }

    service->cmdline                        = stringPrintf(NULL,
      "ssh -a -e none -i /dev/null -x -oChallengeResponseAuthentication=no "
          "-oCheckHostIP=no -oClearAllForwardings=yes -oCompression=no "
          "-oControlMaster=no -oGSSAPIAuthentication=no "
          "-oHostbasedAuthentication=no -oIdentitiesOnly=yes "
          "-oKbdInteractiveAuthentication=yes -oPasswordAuthentication=yes "
          "-oPreferredAuthentications=keyboard-interactive,password "
          "-oPubkeyAuthentication=no -oRhostsRSAAuthentication=no "
          "-oRSAAuthentication=no -oStrictHostKeyChecking=no -oTunnel=no "
          "-oUserKnownHostsFile=/dev/null -oVerifyHostKeyDNS=no "
// beewoolie-2012.03.30: while it would be nice to disable this
//          feature, we cannot be sure that it is available on the
//          target server.  Removing it for the sake of Centos.
//          "-oVisualHostKey=no"
          " -oLogLevel=FATAL -p%s %%s@%s",sshPort,  host);
    free(host);
    free(sshPort);
  } else {
    service->useLogin                       = 0;

    // The user definition is either the word 'AUTH' or a valid user and
    // group id.
    if ((ptr                                = strchr(arg, ':')) == NULL) {
      goto error;
    }
    *ptr                                    = '\000';
    if (supportsPAM() && !strcmp(arg, "AUTH")) {
      service->authUser                     = 1;
      service->uid                          = -1;
      service->gid                          = -1;
      service->user                         = NULL;
      service->group                        = NULL;
    } else {
      service->authUser                     = 0;

      // Numeric or symbolic user id
      service->uid                          = parseUserArg(arg,
                                                           &service->user);
      *ptr                                  = ':';
      arg                                   = ptr + 1;

      // Numeric or symbolic group id
      if ((ptr                              = strchr(arg, ':')) == NULL) {
        goto error;
      }
      *ptr                                  = '\000';
      service->gid                          = parseGroupArg(arg,
                                                            &service->group);
    }
    *ptr                                    = ':';
    arg                                     = ptr + 1;

    // The next part of the argument is the starting working directory
    if ((ptr                                = strchr(arg, ':')) == NULL) {
      goto error;
    }
    *ptr                                    = '\000';
    if (!strcmp(arg, "HOME")) {
      service->useHomeDir                   = 1;
      service->cwd                          = NULL;
    } else {
      if (*arg != '/') {
        fatal("[config] Working directories must have absolute paths!");
      }
      service->useHomeDir                   = 0;
      check(service->cwd                    = strdup(arg));
    }
    *ptr                                    = ':';
    arg                                     = ptr + 1;

    // The final argument is the command line
    if (!*arg) {
      goto error;
    }
    if (!strcmp(arg, "SHELL")) {
      service->useDefaultShell              = 1;
      service->cmdline                      = NULL;
    } else {
      service->useDefaultShell              = 0;
      check(service->cmdline                = strdup(arg));
    }
  }
  free(desc);
}
Example #15
0
 int main(int argc,const char *argv[])
{
	/* shall I run as a daemon */
	bool is_daemon = false;
	bool interactive = false;
	bool Fork = true;
	bool no_process_group = false;
	bool log_stdout = false;
	char *ports = NULL;
	char *profile_level = NULL;
	int opt;
	poptContext pc;
	bool print_build_options = False;
        enum {
		OPT_DAEMON = 1000,
		OPT_INTERACTIVE,
		OPT_FORK,
		OPT_NO_PROCESS_GROUP,
		OPT_LOG_STDOUT
	};
	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
	{"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
	{"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
	{"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
	{"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
	{"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
	{"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
	POPT_COMMON_SAMBA
	POPT_COMMON_DYNCONFIG
	POPT_TABLEEND
	};
	struct smbd_parent_context *parent = NULL;
	TALLOC_CTX *frame;
	NTSTATUS status;
	uint64_t unique_id;
	struct tevent_context *ev_ctx;
	struct messaging_context *msg_ctx;
	struct tevent_signal *se;

	/*
	 * Do this before any other talloc operation
	 */
	talloc_enable_null_tracking();
	frame = talloc_stackframe();

	setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);

	load_case_tables();

	smbd_init_globals();

	TimeInit();

#ifdef HAVE_SET_AUTH_PARAMETERS
	set_auth_parameters(argc,argv);
#endif

	pc = poptGetContext("smbd", argc, argv, long_options, 0);
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt)  {
		case OPT_DAEMON:
			is_daemon = true;
			break;
		case OPT_INTERACTIVE:
			interactive = true;
			break;
		case OPT_FORK:
			Fork = false;
			break;
		case OPT_NO_PROCESS_GROUP:
			no_process_group = true;
			break;
		case OPT_LOG_STDOUT:
			log_stdout = true;
			break;
		case 'b':
			print_build_options = True;
			break;
		default:
			d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			exit(1);
		}
	}
	poptFreeContext(pc);

	if (interactive) {
		Fork = False;
		log_stdout = True;
	}

	if (log_stdout) {
		setup_logging(argv[0], DEBUG_STDOUT);
	} else {
		setup_logging(argv[0], DEBUG_FILE);
	}

	if (print_build_options) {
		build_options(True); /* Display output to screen as well as debug */
		exit(0);
	}

#ifdef HAVE_SETLUID
	/* needed for SecureWare on SCO */
	setluid(0);
#endif

	set_remote_machine_name("smbd", False);

	if (interactive && (DEBUGLEVEL >= 9)) {
		talloc_enable_leak_report();
	}

	if (log_stdout && Fork) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}

	/* we want to re-seed early to prevent time delays causing
           client problems at a later date. (tridge) */
	generate_random_buffer(NULL, 0);

	/* get initial effective uid and gid */
	sec_init();

	/* make absolutely sure we run as root - to handle cases where people
	   are crazy enough to have it setuid */
	gain_root_privilege();
	gain_root_group_privilege();

	fault_setup();
	dump_core_setup("smbd", lp_logfile());

	/* we are never interested in SIGPIPE */
	BlockSignals(True,SIGPIPE);

#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

#if defined(SIGUSR2)
	/* We are no longer interested in USR2 */
	BlockSignals(True,SIGUSR2);
#endif

	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't recieve them. */
	BlockSignals(False, SIGHUP);
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);

	/* Ensure we leave no zombies until we
	 * correctly set up child handling below. */

	CatchChild();

	/* we want total control over the permissions on created files,
	   so set our umask to 0 */
	umask(0);

	reopen_logs();

	DEBUG(0,("smbd version %s started.\n", samba_version_string()));
	DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));

	DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
		 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));

	/* Output the build options to the debug log */ 
	build_options(False);

	if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
		exit(1);
	}

	if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
		DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
		exit(1);
	}

	/* Init the security context and global current_user */
	init_sec_ctx();

	/*
	 * Initialize the event context. The event context needs to be
	 * initialized before the messaging context, cause the messaging
	 * context holds an event context.
	 * FIXME: This should be s3_tevent_context_init()
	 */
	ev_ctx = server_event_context();
	if (ev_ctx == NULL) {
		exit(1);
	}

	/*
	 * Init the messaging context
	 * FIXME: This should only call messaging_init()
	 */
	msg_ctx = server_messaging_context();
	if (msg_ctx == NULL) {
		exit(1);
	}

	/*
	 * Reloading of the printers will not work here as we don't have a
	 * server info and rpc services set up. It will be called later.
	 */
	if (!reload_services(NULL, NULL, false)) {
		exit(1);
	}

	/* ...NOTE... Log files are working from this point! */

	DEBUG(3,("loaded services\n"));

	init_structs();

#ifdef WITH_PROFILE
	if (!profile_setup(msg_ctx, False)) {
		DEBUG(0,("ERROR: failed to setup profiling\n"));
		return -1;
	}
	if (profile_level != NULL) {
		int pl = atoi(profile_level);
		struct server_id src;

		DEBUG(1, ("setting profiling level: %s\n",profile_level));
		src.pid = getpid();
		set_profile_level(pl, src);
	}
#endif

	if (!is_daemon && !is_a_socket(0)) {
		if (!interactive)
			DEBUG(0,("standard input is not a socket, assuming -D option\n"));

		/*
		 * Setting is_daemon here prevents us from eventually calling
		 * the open_sockets_inetd()
		 */

		is_daemon = True;
	}

	if (is_daemon && !interactive) {
		DEBUG( 3, ( "Becoming a daemon.\n" ) );
		become_daemon(Fork, no_process_group, log_stdout);
	}

        generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id));
        set_my_unique_id(unique_id);

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for
	 * signal management.
	 */
	if (interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0);
#endif

	if (!directory_exist(lp_lockdir()))
		mkdir(lp_lockdir(), 0755);

	if (is_daemon)
		pidfile_create("smbd");

	status = reinit_after_fork(msg_ctx,
				   ev_ctx,
				   false);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("reinit_after_fork() failed\n"));
		exit(1);
	}

	smbd_server_conn->msg_ctx = msg_ctx;

	parent = talloc_zero(ev_ctx, struct smbd_parent_context);
	if (!parent) {
		exit_server("talloc(struct smbd_parent_context) failed");
	}
	parent->interactive = interactive;
	parent->ev_ctx = ev_ctx;
	parent->msg_ctx = msg_ctx;
	am_parent = parent;

	se = tevent_add_signal(parent->ev_ctx,
			       parent,
			       SIGTERM, 0,
			       smbd_parent_sig_term_handler,
			       parent);
	if (!se) {
		exit_server("failed to setup SIGTERM handler");
	}
	se = tevent_add_signal(parent->ev_ctx,
			       parent,
			       SIGHUP, 0,
			       smbd_parent_sig_hup_handler,
			       parent);
	if (!se) {
		exit_server("failed to setup SIGHUP handler");
	}

	/* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */

	if (smbd_memcache() == NULL) {
		exit(1);
	}

	memcache_set_global(smbd_memcache());

	/* Initialise the password backed before the global_sam_sid
	   to ensure that we fetch from ldap before we make a domain sid up */

	if(!initialize_password_db(false, ev_ctx))
		exit(1);

	if (!secrets_init()) {
		DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
		exit(1);
	}

	if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
		struct loadparm_context *lp_ctx = loadparm_init_s3(NULL, loadparm_s3_context());
		if (!open_schannel_session_store(NULL, lp_ctx)) {
			DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n"));
			exit(1);
		}
		TALLOC_FREE(lp_ctx);
	}

	if(!get_global_sam_sid()) {
		DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
		exit(1);
	}

	if (!sessionid_init()) {
		exit(1);
	}

	if (!connections_init(True))
		exit(1);

	if (!locking_init())
		exit(1);

	if (!messaging_tdb_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!notify_internal_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!serverid_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!W_ERROR_IS_OK(registry_init_full()))
		exit(1);

	/* Open the share_info.tdb here, so we don't have to open
	   after the fork on every single connection.  This is a small
	   performance improvment and reduces the total number of system
	   fds used. */
	if (!share_info_db_init()) {
		DEBUG(0,("ERROR: failed to load share info db.\n"));
		exit(1);
	}

	status = init_system_info();
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
			  nt_errstr(status)));
		return -1;
	}

	if (!init_guest_info()) {
		DEBUG(0,("ERROR: failed to setup guest info.\n"));
		return -1;
	}

	if (!file_init(smbd_server_conn)) {
		DEBUG(0, ("ERROR: file_init failed\n"));
		return -1;
	}

	/* This MUST be done before start_epmd() because otherwise
	 * start_epmd() forks and races against dcesrv_ep_setup() to
	 * call directory_create_or_exist() */
	if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) {
		DEBUG(0, ("Failed to create pipe directory %s - %s\n",
			  lp_ncalrpc_dir(), strerror(errno)));
		return -1;
	}

	if (is_daemon && !interactive) {
		if (rpc_epmapper_daemon() == RPC_DAEMON_FORK) {
			start_epmd(ev_ctx, msg_ctx);
		}
	}

	if (!dcesrv_ep_setup(ev_ctx, msg_ctx)) {
		exit(1);
	}

	/* only start other daemons if we are running as a daemon
	 * -- bad things will happen if smbd is launched via inetd
	 *  and we fork a copy of ourselves here */
	if (is_daemon && !interactive) {

		if (rpc_lsasd_daemon() == RPC_DAEMON_FORK) {
			start_lsasd(ev_ctx, msg_ctx);
		}

		if (!_lp_disable_spoolss() &&
		    (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
			bool bgq = lp_parm_bool(-1, "smbd", "backgroundqueue", true);

			if (!printing_subsystem_init(ev_ctx, msg_ctx, true, bgq)) {
				exit(1);
			}
		}
	} else if (!_lp_disable_spoolss() &&
		   (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
		if (!printing_subsystem_init(ev_ctx, msg_ctx, false, false)) {
			exit(1);
		}
	}

	if (!is_daemon) {
		/* inetd mode */
		TALLOC_FREE(frame);

		/* Started from inetd. fd 0 is the socket. */
		/* We will abort gracefully when the client or remote system
		   goes away */
		smbd_server_conn->sock = dup(0);

		/* close our standard file descriptors */
		if (!debug_get_output_is_stdout()) {
			close_low_fds(False); /* Don't close stderr */
		}

#ifdef HAVE_ATEXIT
		atexit(killkids);
#endif

	        /* Stop zombies */
		smbd_setup_sig_chld_handler(parent);

		smbd_process(ev_ctx, smbd_server_conn);

		exit_server_cleanly(NULL);
		return(0);
	}

	if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports))
		exit_server("open_sockets_smbd() failed");

	/* do a printer update now that all messaging has been set up,
	 * before we allow clients to start connecting */
	printing_subsystem_update(ev_ctx, msg_ctx, false);

	TALLOC_FREE(frame);
	/* make sure we always have a valid stackframe */
	frame = talloc_stackframe();

	smbd_parent_loop(ev_ctx, parent);

	exit_server_cleanly(NULL);
	TALLOC_FREE(frame);
	return(0);
}
Example #16
0
/* cfgadm entry point */
cfga_err_t
cfga_private_func(
    const char *func,
    const char *ap_id,
    const char *options,
    struct cfga_confirm *confp,
    struct cfga_msg *msgp,
    char **errstring,
    cfga_flags_t flags)
{
	int			len;
	char 			*msg;
	nvlist_t		*list = NULL;
	ap_ostate_t		ostate;
	ap_rstate_t		rstate;
	devctl_hdl_t		hdl = NULL;
	cfga_sata_ret_t		rv;
	char			*str_p;
	size_t			size;

	if ((rv = verify_params(ap_id, NULL, errstring)) != CFGA_SATA_OK) {
		(void) cfga_help(msgp, options, flags);
		return (sata_err_msg(errstring, rv, ap_id, errno));
	}

	/*
	 * All subcommands which can change state of device require
	 * root privileges.
	 */
	if (geteuid() != 0) {
		rv = CFGA_SATA_PRIV;
		goto bailout;
	}

	if (func == NULL) {
		(void) printf("No valid option specified\n");
		rv = CFGA_SATA_OPTIONS;
		goto bailout;
	}

	if ((rv = setup_for_devctl_cmd(ap_id, &hdl, &list, 0)) !=
	    CFGA_SATA_OK) {
		goto bailout;
	}

	/* We do not care here about dynamic AP name component */
	if ((str_p = GET_DYN(ap_id)) != NULL) {
		*str_p = '\0';
	}

	rv = CFGA_SATA_OK;

	if (strcmp(func, SATA_RESET_PORT) == 0) {
		len = strlen(SATA_CONFIRM_PORT) +
		    strlen(SATA_CONFIRM_DEVICE_ABORT) +
		    strlen("Reset Port") + strlen(ap_id);

		if ((msg = (char *)calloc(len +3, 1)) != NULL) {
			(void) snprintf(msg, len +3, "Reset"
			    " %s%s\n%s",
			    SATA_CONFIRM_PORT, ap_id,
			    SATA_CONFIRM_DEVICE_ABORT);
		} else {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}

		if (!sata_confirm(confp, msg)) {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}

		rv = do_control_ioctl(ap_id, SATA_CFGA_RESET_PORT, NULL,
		    (void **)&str_p, &size);

	} else if (strcmp(func, SATA_RESET_DEVICE) == 0) {
		if ((rv = port_state(hdl, list, &rstate, &ostate)) !=
		    CFGA_SATA_OK)
			goto bailout;
		/*
		 * Reset device function requires device to be connected
		 */
		if (rstate != AP_RSTATE_CONNECTED) {
			rv = CFGA_SATA_NOT_CONNECTED;
			goto bailout;
		}

		len = strlen(SATA_CONFIRM_DEVICE) +
		    strlen(SATA_CONFIRM_DEVICE_ABORT) +
		    strlen("Reset Device") + strlen(ap_id);

		if ((msg = (char *)calloc(len +3, 1)) != NULL) {
			(void) snprintf(msg, len +3, "Reset"
			    " %s%s\n%s",
			    SATA_CONFIRM_DEVICE, ap_id,
			    SATA_CONFIRM_DEVICE_ABORT);
		} else {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}

		if (!sata_confirm(confp, msg)) {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}

		rv = do_control_ioctl(ap_id, SATA_CFGA_RESET_DEVICE, NULL,
		    (void **)&str_p, &size);

	} else if (strcmp(func, SATA_RESET_ALL) == 0) {
		len = strlen(SATA_CONFIRM_CONTROLLER) +
		    strlen(SATA_CONFIRM_CONTROLLER_ABORT) +
		    strlen("Reset All") + strlen(ap_id);

		if ((msg = (char *)calloc(len +3, 1)) != NULL) {
			(void) snprintf(msg, len +3, "Reset"
			    " %s%s\n%s",
			    SATA_CONFIRM_CONTROLLER, ap_id,
			    SATA_CONFIRM_CONTROLLER_ABORT);
		} else {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}

		if (!sata_confirm(confp, msg)) {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}
		rv = do_control_ioctl(ap_id, SATA_CFGA_RESET_ALL, NULL,
		    (void **)&str_p, &size);

	} else if (strcmp(func, SATA_PORT_DEACTIVATE) == 0) {
		len = strlen(SATA_CONFIRM_PORT) +
		    strlen(SATA_CONFIRM_PORT_DISABLE) +
		    strlen("Deactivate Port") + strlen(ap_id);

		if ((msg = (char *)calloc(len +3, 1)) != NULL) {
			(void) snprintf(msg, len +3, "Deactivate"
			    " %s%s\n%s",
			    SATA_CONFIRM_PORT, ap_id,
			    SATA_CONFIRM_PORT_DISABLE);
		} else {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}
		if (!sata_confirm(confp, msg)) {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}

		rv = do_control_ioctl(ap_id, SATA_CFGA_PORT_DEACTIVATE, NULL,
		    (void **)&str_p, &size);

	} else if (strcmp(func, SATA_PORT_ACTIVATE) == 0) {
		len = strlen(SATA_CONFIRM_PORT) +
		    strlen(SATA_CONFIRM_PORT_ENABLE) +
		    strlen("Activate Port") + strlen(ap_id);

		if ((msg = (char *)calloc(len +3, 1)) != NULL) {
			(void) snprintf(msg, len +3, "Activate"
			    " %s%s\n%s",
			    SATA_CONFIRM_PORT, ap_id,
			    SATA_CONFIRM_PORT_ENABLE);
		} else {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}
		if (!sata_confirm(confp, msg)) {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}

		rv = do_control_ioctl(ap_id, SATA_CFGA_PORT_ACTIVATE,
		    NULL, (void **)&str_p, &size);
		goto bailout;

	} else if (strcmp(func, SATA_PORT_SELF_TEST) == 0) {
		len = strlen(SATA_CONFIRM_PORT) +
		    strlen(SATA_CONFIRM_DEVICE_SUSPEND) +
		    strlen("Self Test Port") + strlen(ap_id);

		if ((msg = (char *)calloc(len +3, 1)) != NULL) {
			(void) snprintf(msg, len +3, "Self Test"
			    " %s%s\n%s",
			    SATA_CONFIRM_PORT, ap_id,
			    SATA_CONFIRM_DEVICE_SUSPEND);
		} else {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}
		if (!sata_confirm(confp, msg)) {
			rv = CFGA_SATA_NACK;
			goto bailout;
		}

		rv = do_control_ioctl(ap_id, SATA_CFGA_PORT_SELF_TEST,
		    NULL, (void **)&str_p, &size);
	} else {
		/* Unrecognized operation request */
		rv = CFGA_SATA_HWOPNOTSUPP;
	}

bailout:
	cleanup_after_devctl_cmd(hdl, list);

	return (sata_err_msg(errstring, rv, ap_id, errno));

}
Example #17
0
int
main(int argc, char **argv)
{
	int			c;
	char		*nodename = NULL; /* GTM Proxy nodename */

	progname = "gtm_ctl";

	/*
	 * save argv[0] so do_start() can look for the gtm if necessary. we
	 * don't look for gtm here because in many cases we won't need it.
	 */
	argv0 = argv[0];

	umask(077);

	/* support --help and --version even if invoked as root */
	if (argc > 1)
	{
		if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
			strcmp(argv[1], "-?") == 0)
		{
			do_help();
			exit(0);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			puts("gtm_ctl (Postgres-XC) " PGXC_VERSION);
			exit(0);
		}
	}

	/*
	 * Disallow running as root, to forestall any possible security holes.
	 */
	if (geteuid() == 0)
	{
		write_stderr(_("%s: cannot be run as root\n"
					   "Please log in (using, e.g., \"su\") as the "
					   "(unprivileged) user that will\n"
					   "own the server process.\n"),
					 progname);
		exit(1);
	}

	/*
	 * 'Action' can be before or after args so loop over both. Some
	 * getopt_long() implementations will reorder argv[] to place all flags
	 * first (GNU?), but we don't rely on it. Our /port version doesn't do
	 * that.
	 */
	optind = 1;

	/* process command-line options */
	while (optind < argc)
	{
		while ((c = getopt(argc, argv, "D:i:l:m:o:p:t:wWZ:C:")) != -1)
		{
			switch (c)
			{
				case 'D':
					{
						char	   *env_var = pg_malloc(strlen(optarg) + 9);

						gtmdata_D = xstrdup(optarg);
						canonicalize_path(gtmdata_D);
						snprintf(env_var, strlen(optarg) + 9, "GTMDATA=%s",
								 gtmdata_D);
						putenv(env_var);

						/*
						 * We could pass GTMDATA just in an environment
						 * variable but we do -D too for clearer gtm
						 * 'ps' display
						 */
						gtmdata_opt = (char *) pg_malloc(strlen(gtmdata_D) + 8);
						snprintf(gtmdata_opt, strlen(gtmdata_D) + 8,
								 "-D \"%s\" ",
								 gtmdata_D);
						break;
					}
				case 'i':
					nodename = strdup(optarg);
					break;
				case 'l':
					log_file = xstrdup(optarg);
					break;
				case 'm':
					set_mode(optarg);
					break;
				case 'o':
					gtm_opts = xstrdup(optarg);
					break;
				case 'p':
					gtm_path = xstrdup(optarg);
					canonicalize_path(gtm_path);
					break;
				case 't':
					wait_seconds = atoi(optarg);
					break;
				case 'C':
					control_file = xstrdup(optarg);
					break;
				case 'w':
					do_wait = true;
					wait_set = true;
					break;
				case 'W':
					do_wait = false;
					wait_set = true;
					break;
				case 'Z':
					gtm_app = xstrdup(optarg);
					if (strcmp(gtm_app,"gtm_proxy") != 0
						&& strcmp(gtm_app,"gtm_standby") != 0
						&& strcmp(gtm_app,"gtm") != 0)
					{
						write_stderr(_("%s: %s launch name set not correct\n"), progname, gtm_app);
						do_advice();
						exit(1);
					}
					break;
				default:
					/* getopt_long already issued a suitable error message */
					do_advice();
					exit(1);
			}
		}

		/* Process an action */
		if (optind < argc)
		{
			if (ctl_command != NO_COMMAND)
			{
				write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
				do_advice();
				exit(1);
			}

			if (strcmp(argv[optind], "start") == 0)
				ctl_command = START_COMMAND;
			else if (strcmp(argv[optind], "stop") == 0)
				ctl_command = STOP_COMMAND;
			else if (strcmp(argv[optind], "promote") == 0)
				ctl_command = PROMOTE_COMMAND;
			else if (strcmp(argv[optind], "restart") == 0)
				ctl_command = RESTART_COMMAND;
			else if (strcmp(argv[optind], "status") == 0)
				ctl_command = STATUS_COMMAND;
			else if (strcmp(argv[optind], "reconnect") == 0)
				ctl_command = RECONNECT_COMMAND;
			else
			{
				write_stderr(_("%s: unrecognized operation mode \"%s\"\n"),
							 progname, argv[optind]);
				do_advice();
				exit(1);
			}
			optind++;
		}
	}

	/*
	 * Take care of the control file (-C Option)
	 */
	if (control_file)
	{
		char ctrl_path[MAXPGPATH+1];
		char C_opt_path[MAXPGPATH+1];
		char bkup_path[MAXPGPATH+1];
		FILE *f1, *f2;
		int c;

		if (!gtmdata_D)
		{
			write_stderr(_("No -D option specified.\n"));
			exit(1);
		}
		if ((strcmp(gtm_app, "gtm") != 0) && (strcmp(gtm_app, "gtm_master") != 0))
		{
			write_stderr(_("-C option is valid only for gtm.\n"));
			exit(1);
		}
		/* If there's already a control file, backup it to *.bak */
		trim_last_slash(gtmdata_D);
		snprintf(ctrl_path, MAXPGPATH, "%s/%s", gtmdata_D, GTM_CONTROL_FILE);
		if ((f1 = fopen(ctrl_path, "r")))
		{

			snprintf(bkup_path, MAXPGPATH, "%s/%s.bak", gtmdata_D, GTM_CONTROL_FILE);
			if (!(f2 = fopen(bkup_path, "w")))
			{
				fclose(f1);
				write_stderr(_("Cannot open backup file, %s/%s.bak, %s\n"),
							 gtmdata_D, GTM_CONTROL_FILE, strerror(errno));
				exit(1);
			}
			while ((c = getc(f1)) != EOF)
				putc(c, f2);
			fclose(f1);
			fclose(f2);
		}
		/* Copy specified control file. */
		snprintf(C_opt_path, MAXPGPATH, "%s/%s", gtmdata_D, control_file);
		if (!(f1 = fopen(ctrl_path, "w")))
		{
			write_stderr(_("Cannot oopen control file, %s, %s\n"), ctrl_path, strerror(errno));
			exit(1);
		}
		if (!(f2 = fopen(C_opt_path, "r")))
		{
			fclose(f1);
			write_stderr(_("Cannot open -C option file, %s, %s\n"), C_opt_path, strerror(errno));
			exit(1);
		}
		while ((c = getc(f2)) != EOF)
			putc(c, f1);
		fclose(f1);
		fclose(f2);
	}

	if (ctl_command == NO_COMMAND)
	{
		write_stderr(_("%s: no operation specified\n"), progname);
		do_advice();
		exit(1);
	}

	gtm_data = getenv("GTMDATA");

	if (gtm_data)
	{
		gtm_data = xstrdup(gtm_data);
		canonicalize_path(gtm_data);
	}

	if (!gtm_data)
	{
		write_stderr("%s: no GTM/GTM Proxy directory specified \n",
					 progname);
		do_advice();
		exit(1);
	}

	/*
	 * pid files of gtm and gtm proxy are named differently
	 * -Z option has also to be set for STOP_COMMAND
	 * or gtm_ctl will not be able to find the correct pid_file
	 */
	if (!gtm_app)
	{
		write_stderr("%s: no launch option not specified\n",
					 progname);
		do_advice();
		exit(1);
	}

	if (strcmp(gtm_app,"gtm_proxy") != 0 &&
		strcmp(gtm_app, "gtm_standby") != 0 &&
		strcmp(gtm_app,"gtm") != 0)
	{
		write_stderr(_("%s: launch option incorrect\n"),
						progname);
		do_advice();
		exit(1);
	}

	/* Check if GTM Proxy ID is set, this is not necessary when stopping */
	if (ctl_command == START_COMMAND ||
		ctl_command == RESTART_COMMAND)
	{
		/* Rebuild option string to include Proxy ID */
		if (strcmp(gtm_app, "gtm_proxy") == 0)
		{
			gtmdata_opt = (char *) pg_realloc(gtmdata_opt, strlen(gtmdata_opt) + 9);
			if (nodename)
				sprintf(gtmdata_opt, "%s -i %s ", gtmdata_opt, nodename);
			else
				sprintf(gtmdata_opt, "%s ", gtmdata_opt);
		}
	}

	if (!wait_set)
	{
		switch (ctl_command)
		{
			case RESTART_COMMAND:
			case START_COMMAND:
			case PROMOTE_COMMAND:
			case STATUS_COMMAND:
				do_wait = false;
				break;
			case STOP_COMMAND:
				do_wait = true;
				break;
			default:
				break;
		}
	}

	/* Build strings for pid file and option file */
	if (strcmp(gtm_app,"gtm_proxy") == 0)
	{
		snprintf(pid_file, MAXPGPATH, "%s/gtm_proxy.pid", gtm_data);
		snprintf(gtmopts_file, MAXPGPATH, "%s/gtm_proxy.opts", gtm_data);
		snprintf(conf_file, MAXPGPATH, "%s/gtm_proxy.conf", gtm_data);
	}
	else if (strcmp(gtm_app,"gtm") == 0)
	{
		snprintf(pid_file, MAXPGPATH, "%s/gtm.pid", gtm_data);
		snprintf(gtmopts_file, MAXPGPATH, "%s/gtm.opts", gtm_data);
		snprintf(conf_file, MAXPGPATH, "%s/gtm.conf", gtm_data);
	}
	else if (strcmp(gtm_app,"gtm_standby") == 0)
	{
		snprintf(pid_file, MAXPGPATH, "%s/gtm.pid", gtm_data);
		snprintf(gtmopts_file, MAXPGPATH, "%s/gtm.opts", gtm_data);
		snprintf(conf_file, MAXPGPATH, "%s/gtm.conf", gtm_data);
	}

	if (ctl_command==STATUS_COMMAND)
		gtm_opts = xstrdup("-c");

	switch (ctl_command)
	{
		case START_COMMAND:
			do_start();
			break;
		case STOP_COMMAND:
			do_stop();
			break;
		case PROMOTE_COMMAND:
			do_promote();
			break;
		case RESTART_COMMAND:
			do_restart();
			break;
		case STATUS_COMMAND:
			do_status();
			break;
		case RECONNECT_COMMAND:
			do_reconnect();
			break;
		default:
			break;
	}

	exit(0);
}
Example #18
0
/*
 * void
 * setup() - performs all ONE TIME setup for this test.
 *  Create a temporary directory and change directory to it.
 *  Create a test file under temporary directory and close it
 *  Change the ownership of testfile to that of "bin" user.
 *  Record the current time.
 */
void setup()
{
	int fildes;		/* file handle for temp file */
	char *tmpd = NULL;

	/* capture signals */
	tst_sig(FORK, DEF_HANDLER, cleanup);

	/* Check that the test process id is not super/root  */
	if (geteuid() != 0) {
		tst_brkm(TBROK, NULL, "Must be root for this test!");
		tst_exit();
	}

	/* Pause if that option was specified
	 * TEST_PAUSE contains the code to fork the test with the -i option.
	 * You want to make sure you do this before you create your temporary
	 * directory.
	 */
	TEST_PAUSE;

	/* make a temp directory and cd to it */
	tst_tmpdir();

	/* get the name of the temporary directory */
	if ((tmpd = getcwd(tmpd, 0)) == NULL) {
		tst_brkm(TBROK, tst_exit, "getcwd failed");
	}

	/* Creat a temporary file under above directory */
	if ((fildes = creat(TEMP_FILE, FILE_MODE)) == -1) {
		tst_brkm(TBROK, cleanup,
			 "creat(%s, %#o) Failed, errno=%d :%s",
			 TEMP_FILE, FILE_MODE, errno, strerror(errno));
	 /*NOTREACHED*/}

	/* Close the temporary file created */
	if (close(fildes) < 0) {
		tst_brkm(TBROK, cleanup,
			 "close(%s) Failed, errno=%d : %s:",
			 TEMP_FILE, errno, strerror(errno));
	 /*NOTREACHED*/}

	/*
	 * Make sure that specified Mode permissions set as
	 * umask value may be different.
	 */
	if (chmod(TEMP_FILE, FILE_MODE) < 0) {
		tst_brkm(TBROK, cleanup,
			 "chmod(%s) Failed, errno=%d : %s:",
			 TEMP_FILE, errno, strerror(errno));
	 /*NOTREACHED*/}

	if (chmod(tmpd, 0711) != 0) {
		tst_brkm(TBROK, cleanup, "chmod() failed");
	}

	if ((ltpuser = getpwnam(LTPUSER2)) == NULL) {
		tst_brkm(TBROK, cleanup, "%s not found in /etc/passwd",
			 LTPUSER2);
	 /*NOTREACHED*/}

	/* get uid/gid of user accordingly */
	user_uid = ltpuser->pw_uid;
	group_gid = ltpuser->pw_gid;

	/*
	 * Change the ownership of test directory/file specified by
	 * pathname to that of user_uid and group_gid.
	 */
	if (chown(TEMP_FILE, user_uid, group_gid) < 0) {
		tst_brkm(TBROK, cleanup, "chown() of %s failed, error %d",
			 TEMP_FILE, errno);
	 /*NOTREACHED*/}

	/* Get the current time */
	if ((curr_time = time(&tloc)) < 0) {
		tst_brkm(TBROK, cleanup,
			 "time() failed to get current time, errno=%d", errno);
	 /*NOTREACHED*/}

	/*
	 * Sleep for a second so that mod time and access times will be
	 * different from the current time
	 */
	sleep(2);		/* sleep(1) on IA64 sometimes sleeps < 1 sec!! */

}				/* End setup() */
Example #19
0
/**
 * Main program
 * @param argc argument counter
 * @param argv argument vector
 * @param appdata application data
 * @return application return code to shell
 */
int
oonf_main(int argc, char **argv, const struct oonf_appdata *appdata) {
  int return_code;
  int result;

  /* early initialization */
  return_code = 1;

  _schema_name = NULL;
  _display_schema = false;
  _debug_early = false;
  _ignore_unknown = false;

  /* setup signal handler */
  _end_oonf_signal = false;
  setup_signalhandler();

  /* parse "early" command line arguments */
  parse_early_commandline(argc, argv);

  /* initialize core */
  os_core_init(appdata->app_name);

  /* initialize logger */
  if (oonf_log_init(appdata, _debug_early ? LOG_SEVERITY_DEBUG : LOG_SEVERITY_WARN)) {
    goto oonf_cleanup;
  }

  /* prepare plugin initialization */
  oonf_subsystem_init();

  /* initialize configuration system */
  if (oonf_cfg_init(argc, argv, appdata->default_cfg_handler)) {
    goto oonf_cleanup;
  }

  /* add custom configuration definitions */
  oonf_logcfg_init();

  /* parse command line and read configuration files */
  return_code = parse_commandline(argc, argv, appdata, false);
  if (return_code != -1) {
    /* end OONFd now */
    goto oonf_cleanup;
  }

  /* prepare for an error during initialization */
  return_code = 1;

  /* read global section early */
  if ((result = oonf_cfg_update_globalcfg(true))) {
    OONF_WARN(LOG_MAIN, "Cannot read global configuration section (%d)", result);
    goto oonf_cleanup;
  }

  /* configure logger */
  if (oonf_logcfg_apply(oonf_cfg_get_rawdb())) {
    goto oonf_cleanup;
  }

  /* load plugins */
  if (oonf_cfg_load_subsystems()) {
    goto oonf_cleanup;
  }

  /* show schema if necessary */
  if (_display_schema) {
    return_code = display_schema();
    goto oonf_cleanup;
  }

  /* check if we are root, otherwise stop */
  if (appdata->need_root) {
    if (geteuid() != 0) {
      OONF_WARN(LOG_MAIN, "You must be root(uid = 0) to run %s!\n",
          appdata->app_name);
      goto oonf_cleanup;
    }
  }

  if (appdata->need_lock
      && config_global.lockfile != NULL && *config_global.lockfile != 0) {
    /* create application lock */
    if (os_core_create_lockfile(config_global.lockfile)) {
      OONF_WARN(LOG_MAIN, "Could not acquire application lock '%s'",
          config_global.lockfile);
      goto oonf_cleanup;
    }
  }

  /* call initialization callbacks of dynamic plugins */
  oonf_cfg_initplugins();

  /* apply configuration */
  if (oonf_cfg_apply()) {
    goto oonf_cleanup;
  }

  if (!oonf_cfg_is_running()) {
    /*
     * mayor error during late initialization
     * or maybe the user decided otherwise and pressed CTRL-C
     */
    return_code = _end_oonf_signal ? 0 : 1;
    goto oonf_cleanup;
  }

  if (!_handle_scheduling) {
    OONF_WARN(LOG_MAIN, "No event scheduler present");
    return_code = 1;
    goto oonf_cleanup;
  }
  /* see if we need to fork */
  if (config_global.fork && !_display_schema) {
    /* tell main process that we are finished with initialization */
    if (daemon(0,0) < 0) {
      OONF_WARN(LOG_MAIN, "Could not fork into background: %s (%d)",
          strerror(errno), errno);
      goto oonf_cleanup;
    }

    if (config_global.pidfile && *config_global.pidfile != 0) {
      if (_write_pidfile(config_global.pidfile)) {
        goto oonf_cleanup;
      }
    }
  }

  /* activate mainloop */
  return_code = mainloop(argc, argv, appdata);

  /* tell plugins shutdown is in progress */
  oonf_subsystem_initiate_shutdown();

  /* wait for 500 ms and process socket events */
  while(!_handle_scheduling());

oonf_cleanup:
  /* free plugins */
  oonf_cfg_unconfigure_subsystems();
  oonf_subsystem_cleanup();

  /* free logging/config bridge resources */
  oonf_logcfg_cleanup();

  /* free configuration resources */
  oonf_cfg_cleanup();

  /* free logger resources */
  oonf_log_cleanup();

  /* free core resources */
  os_core_cleanup();

  return return_code;
}
Example #20
0
int tunctl_main(int argc UNUSED_PARAM, char **argv)
{
	struct ifreq ifr;
	int fd;
	const char *opt_name = "tap%d";
	const char *opt_device = "/dev/net/tun";
#if ENABLE_FEATURE_TUNCTL_UG
	const char *opt_user, *opt_group;
	long user = -1, group = -1;
#endif
	unsigned opts;

	enum {
		OPT_f = 1 << 0, // control device name (/dev/net/tun)
		OPT_t = 1 << 1, // create named interface
		OPT_d = 1 << 2, // delete named interface
#if ENABLE_FEATURE_TUNCTL_UG
		OPT_u = 1 << 3, // set new interface owner
		OPT_g = 1 << 4, // set new interface group
		OPT_b = 1 << 5, // brief output
#endif
	};

	opt_complementary = "=0:t--d:d--t"; // no arguments; t ^ d
	opts = getopt32(argv, "f:t:d:" IF_FEATURE_TUNCTL_UG("u:g:b"),
			&opt_device, &opt_name, &opt_name
			IF_FEATURE_TUNCTL_UG(, &opt_user, &opt_group));

	// select device
	memset(&ifr, 0, sizeof(ifr));
	ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
	strncpy_IFNAMSIZ(ifr.ifr_name, opt_name);

	// open device
	fd = xopen(opt_device, O_RDWR);
	IOCTL(fd, TUNSETIFF, (void *)&ifr);

	// delete?
	if (opts & OPT_d) {
		IOCTL(fd, TUNSETPERSIST, (void *)(uintptr_t)0);
		printf("Set '%s' nonpersistent\n", ifr.ifr_name);
		return EXIT_SUCCESS;
	}

	// create
#if ENABLE_FEATURE_TUNCTL_UG
	if (opts & OPT_g) {
		group = xgroup2gid(opt_group);
		IOCTL(fd, TUNSETGROUP, (void *)(uintptr_t)group);
	} else
		user = geteuid();
	if (opts & OPT_u)
		user = xuname2uid(opt_user);
	IOCTL(fd, TUNSETOWNER, (void *)(uintptr_t)user);
#endif
	IOCTL(fd, TUNSETPERSIST, (void *)(uintptr_t)1);

	// show info
#if ENABLE_FEATURE_TUNCTL_UG
	if (opts & OPT_b) {
		puts(ifr.ifr_name);
	} else {
		printf("Set '%s' %spersistent", ifr.ifr_name, "");
		printf(" and owned by uid %ld", user);
		if (group != -1)
			printf(" gid %ld", group);
		bb_putchar('\n');
	}
#else
	puts(ifr.ifr_name);
#endif
	return EXIT_SUCCESS;
}
Example #21
0
/* Daemon for self dump */
int daemon_dump(void)
{
	int ret;

	/* Check if daemon is running as root */
	if (geteuid()) {
		fprintf(stderr, "Run the daemon as root.\n");
		return -1;
	}

	/* Daemonizing it */
	if (daemon(0, 0)) {
		fprintf(stderr, "Daemon not up %s.", strerror(errno));
		return -1;
	}

	/* Get the PID of the daemon */
	pid_log = getpid();

	fp_log = fopen(GENCORE_DAEMON_LOGFILE, "w+");
	if (fp_log == NULL) {
		openlog("gencore_daemon_log", LOG_PID|LOG_CONS, LOG_USER);
		syslog(LOG_DAEMON, "Could not open: %s.\n",
					GENCORE_DAEMON_LOGFILE);
		closelog();
		return -1;
	}

	/* Setting up server */
	ret = setup_server();
	if (ret)
		goto cleanup;

	/* Flush the log */
	fflush(fp_log);

	/* SIGCHILD - Signal handler */
	signal(SIGCHLD, sigchild_handler);

	/* Terminate Daemon - signal handler */
	signal(SIGTERM, sig_daemon_handler);
	signal(SIGSEGV, sig_daemon_handler);
	signal(SIGPIPE, sig_daemon_handler);

	while (1) {

		/* Blocks on request */
		ret = block_on_request();
		if (ret)
			goto cleanup;

		/* Flush the log */
		fflush(fp_log);

		/* Handle new connections */
		ret = handle_request();
		if (ret)
			goto cleanup;

		/* Flush the log */
		fflush(fp_log);
	}

	return 0;

cleanup:

	fclose(fp_log);

	if (ret == -1)
		return -1;

	return 0;
}
Example #22
0
/* Tries to authenticate the user using the .shosts or .rhosts file.
   Returns true if authentication succeeds.  If config->ignore_rhosts
   is true, only /etc/hosts.equiv will be considered (.rhosts and
   .shosts are ignored), unless the user is root and
   config->ignore_root_rhosts isn't true. */
Boolean ssh_server_auth_hostbased_rhosts(SshUser user_data,
                                         const char *client_user,
                                         void *context)
{
  char buf[1024];
  const char *hostname, *ipaddr;
  struct stat st;
  static const char *rhosts_files[] = { ".shosts", ".rhosts", NULL };
  unsigned int rhosts_file_index;
  SshConfig config;
  SshServer server = (SshServer) context;
  SshUser effective_user_data =
    ssh_user_initialize_with_uid(geteuid(), FALSE);
  
  config = server->config;

  ssh_userfile_init(ssh_user_name(user_data), ssh_user_uid(user_data),
                    ssh_user_gid(user_data), NULL, NULL);

  /* Get the name, address, and port of the remote host.  */
  hostname = server->common->remote_host;
  ipaddr = server->common->remote_ip;

  /* Quick check: if the user has no .shosts or .rhosts files, return failure
     immediately without doing costly lookups from name servers. */
  for (rhosts_file_index = 0; rhosts_files[rhosts_file_index];
       rhosts_file_index++)
    {
      /* Check users .rhosts or .shosts. */
      snprintf(buf, sizeof(buf), "%.500s/%.100s", 
              ssh_user_dir(user_data), rhosts_files[rhosts_file_index]);
      if (ssh_userfile_stat(ssh_user_uid(user_data), buf, &st) >= 0)
        break;
    }

  if (!rhosts_files[rhosts_file_index] && 
      ssh_userfile_stat(ssh_user_uid(user_data), "/etc/hosts.equiv", &st) < 0 &&
      ssh_userfile_stat(ssh_user_uid(user_data), SSH_HOSTS_EQUIV, &st) < 0)
    return FALSE; /* The user has no .shosts or .rhosts file and there are no
                 system-wide files. */
  
  /* If not logging in as superuser, try /etc/hosts.equiv and shosts.equiv. */
  if (ssh_user_uid(user_data) != UID_ROOT)
    {
      if (check_rhosts_file(ssh_user_uid(effective_user_data), 
                            "/etc/hosts.equiv", hostname, ipaddr, client_user,
                            ssh_user_name(user_data), server))
        {
          SSH_TRACE(2, ("Accepted for %.100s [%.100s] by " \
                        "/etc/hosts.equiv.", hostname, ipaddr));
          return TRUE;
        }
      if (check_rhosts_file(ssh_user_uid(effective_user_data),
                            SSH_HOSTS_EQUIV, hostname, ipaddr, client_user,
                            ssh_user_name(user_data), server))
        {
          SSH_TRACE(2, ("Accepted for %.100s [%.100s] by %.100s.",  \
                            hostname, ipaddr, SSH_HOSTS_EQUIV));
          return TRUE;
        }
    }

  /* Check that the home directory is owned by root or the user, and is not 
     group or world writable. */
  if (ssh_userfile_stat(ssh_user_uid(user_data), ssh_user_dir(user_data),
                    &st) < 0)
    {
      ssh_log_event(config->log_facility, SSH_LOG_WARNING,
                    "hostbased-authentication (rhosts) refused for " \
                    "%.100: no home directory %.200s",
                    ssh_user_name(user_data),
                    ssh_user_dir(user_data));
      SSH_TRACE(2, ("hostbased-authentication (rhosts) refused for " \
                    "%.100: no home directory %.200s", \
                    ssh_user_name(user_data), ssh_user_dir(user_data)));
      return FALSE;
    }
  
  if (config->strict_modes && 
      ((st.st_uid != UID_ROOT && st.st_uid != ssh_user_uid(user_data)) ||
#ifdef ALLOW_GROUP_WRITEABILITY
       (st.st_mode & 002) != 0)
#else
       (st.st_mode & 022) != 0)
#endif
      )
    {
      ssh_log_event(config->log_facility, SSH_LOG_WARNING,
                    "hostbased-authentication (rhosts) refused for " \
                    "%.100s: bad ownership or modes for home directory.",
                    ssh_user_name(user_data));
      SSH_TRACE(2, ("hostbased-authentication (rhosts) refused for " \
                    "%.100s: bad ownership or modes for home directory.", \
                    ssh_user_name(user_data)));
      return FALSE;
    }
  
  /* Check all .rhosts files (currently .shosts and .rhosts). */
  for (rhosts_file_index = 0; rhosts_files[rhosts_file_index];
       rhosts_file_index++)
    {
      /* Check users .rhosts or .shosts. */
      snprintf(buf, sizeof(buf), "%.500s/%.100s", 
              ssh_user_dir(user_data), rhosts_files[rhosts_file_index]);
      if (ssh_userfile_stat(ssh_user_uid(user_data), buf, &st) < 0)
        continue; /* No such file. */

      /* Make sure that the file is either owned by the user or by root,
         and make sure it is not writable by anyone but the owner.  This is
         to help avoid novices accidentally allowing access to their account
         by anyone. */
      if (config->strict_modes &&
          ((st.st_uid != UID_ROOT && st.st_uid != ssh_user_uid(user_data)) ||
           (st.st_mode & 022) != 0))
        {
          ssh_log_event(config->log_facility, SSH_LOG_WARNING,
                        "hostbased-authentication (rhosts) refused for " \
                        "%.100s: bad modes for %.200s",
                        ssh_user_name(user_data), buf);
          SSH_TRACE(2, ("hostbased-authentication (rhosts) refused for " \
                        "%.100s: bad modes for %.200s", \
                        ssh_user_name(user_data), buf));
          continue;
        }

      /* Check if we have been configured to ignore .rhosts and .shosts 
         files.  If root, check ignore_root_rhosts first. */
      if ((ssh_user_uid(user_data) == UID_ROOT &&
           config->ignore_root_rhosts) ||
          (ssh_user_uid(user_data) != UID_ROOT &&
           config->ignore_rhosts))
        {
          SSH_TRACE(2, ("Server has been configured to ignore %.100s.", \
                        rhosts_files[rhosts_file_index]));
          continue;
        }

      /* Check if authentication is permitted by the file. */
      if (check_rhosts_file(ssh_user_uid(user_data), buf, hostname,
                            ipaddr, client_user, ssh_user_name(user_data),
                            server))
        {
          SSH_TRACE(2, ("Accepted by %.100s.", \
                        rhosts_files[rhosts_file_index]));
          return TRUE;
        }
    }

  /* Rhosts authentication denied. */
  SSH_TRACE(2, ("hostbased-authentication (rhosts) refused: client " \
                "user '%.100s', server user '%.100s', " \
                "client host '%.200s'.", \
                client_user, ssh_user_name(user_data), hostname));

  ssh_log_event(config->log_facility, SSH_LOG_WARNING,
                "hostbased-authentication (rhosts) refused: client " \
                "user '%.100s', server user '%.100s', " \
                "client host '%.200s'.", \
                client_user, ssh_user_name(user_data), hostname);

  return FALSE;
}
Example #23
0
static void
add_printer_filter(
    const char  *command,		/* I - Command name */
    mime_t      *mime,			/* I - MIME database */
    mime_type_t *filtertype,		/* I - Printer or prefilter MIME type */
    const char  *filter)		/* I - Filter to add */
{
  char		super[MIME_MAX_SUPER],	/* Super-type for filter */
		type[MIME_MAX_TYPE],	/* Type for filter */
		dsuper[MIME_MAX_SUPER],	/* Destination super-type for filter */
		dtype[MIME_MAX_TYPE],	/* Destination type for filter */
		dest[MIME_MAX_SUPER + MIME_MAX_TYPE + 2],
					/* Destination super/type */
		program[1024];		/* Program/filter name */
  int		cost;			/* Cost of filter */
  size_t	maxsize = 0;		/* Maximum supported file size */
  mime_type_t	*temptype,		/* MIME type looping var */
		*desttype;		/* Destination MIME type */
  mime_filter_t	*filterptr;		/* MIME filter */


 /*
  * Parse the filter string; it should be in one of the following formats:
  *
  *     source/type cost program
  *     source/type cost maxsize(nnnn) program
  *     source/type dest/type cost program
  *     source/type dest/type cost maxsize(nnnn) program
  */

  if (sscanf(filter, "%15[^/]/%255s%*[ \t]%15[^/]/%255s%d%*[ \t]%1023[^\n]",
             super, type, dsuper, dtype, &cost, program) == 6)
  {
    snprintf(dest, sizeof(dest), "%s/%s/%s", filtertype->type, dsuper, dtype);

    if ((desttype = mimeType(mime, "printer", dest)) == NULL)
      desttype = mimeAddType(mime, "printer", dest);
  }
  else
  {
    if (sscanf(filter, "%15[^/]/%255s%d%*[ \t]%1023[^\n]", super, type, &cost,
               program) == 4)
    {
      desttype = filtertype;
    }
    else
    {
      _cupsLangPrintf(stderr, _("%s: Invalid filter string \"%s\"."), command,
		      filter);
      return;
    }
  }

  if (!strncmp(program, "maxsize(", 8))
  {
    char	*ptr;			/* Pointer into maxsize(nnnn) program */

    maxsize = strtoll(program + 8, &ptr, 10);

    if (*ptr != ')')
    {
      printf("testmime: Invalid filter string \"%s\".\n", filter);
      return;
    }

    ptr ++;
    while (_cups_isspace(*ptr))
      ptr ++;

    _cups_strcpy(program, ptr);
  }

 /*
  * See if the filter program exists; if not, stop the printer and flag
  * the error!
  */

  if (strcmp(program, "-"))
  {
    char filename[1024];		/* Full path to program */

    if (program[0] == '/')
      strlcpy(filename, program, sizeof(filename));
    else
      snprintf(filename, sizeof(filename), "%s/filter/%s", ServerBin, program);

    if (_cupsFileCheck(filename, _CUPS_FILE_CHECK_PROGRAM, !geteuid(), check_cb,
                       (void *)command))
      return;
  }

 /*
  * Add the filter to the MIME database, supporting wildcards as needed...
  */

  for (temptype = mimeFirstType(mime);
       temptype;
       temptype = mimeNextType(mime))
    if (((super[0] == '*' && _cups_strcasecmp(temptype->super, "printer")) ||
         !_cups_strcasecmp(temptype->super, super)) &&
        (type[0] == '*' || !_cups_strcasecmp(temptype->type, type)))
    {
      if (desttype != filtertype)
      {
        filterptr = mimeAddFilter(mime, temptype, desttype, cost, program);

        if (!mimeFilterLookup(mime, desttype, filtertype))
          mimeAddFilter(mime, desttype, filtertype, 0, "-");
      }
      else
        filterptr = mimeAddFilter(mime, temptype, filtertype, cost, program);

      if (filterptr)
	filterptr->maxsize = maxsize;
    }
}
Example #24
0
int
main(int argc, char * argv[])
{
	struct timeval timeout;
	fd_set fdset;
	int nfds;
	struct pidfh *pfh = NULL;
	const char *pidfile = NULL;
	int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
	int minfreq = -1, maxfreq = -1;
	int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
	uint64_t mjoules_used;
	size_t len;

	/* Default mode for all AC states is adaptive. */
	mode_ac = mode_none = MODE_HIADAPTIVE;
	mode_battery = MODE_ADAPTIVE;
	cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
	cpu_idle_mark = DEFAULT_IDLE_PERCENT;
	poll_ival = DEFAULT_POLL_INTERVAL;
	mjoules_used = 0;
	vflag = 0;

	/* User must be root to control frequencies. */
	if (geteuid() != 0)
		errx(1, "must be root to run");

	while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
		switch (ch) {
		case 'a':
			parse_mode(optarg, &mode_ac, ch);
			break;
		case 'b':
			parse_mode(optarg, &mode_battery, ch);
			break;
		case 'i':
			cpu_idle_mark = atoi(optarg);
			if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
				warnx("%d is not a valid percent",
				    cpu_idle_mark);
				usage();
			}
			break;
		case 'm':
			minfreq = atoi(optarg);
			if (minfreq < 0) {
				warnx("%d is not a valid CPU frequency",
				    minfreq);
				usage();
			}
			break;
		case 'M':
			maxfreq = atoi(optarg);
			if (maxfreq < 0) {
				warnx("%d is not a valid CPU frequency",
				    maxfreq);
				usage();
			}
			break;
		case 'n':
			parse_mode(optarg, &mode_none, ch);
			break;
		case 'p':
			poll_ival = atoi(optarg);
			if (poll_ival < 5) {
				warnx("poll interval is in units of ms");
				usage();
			}
			break;
		case 'P':
			pidfile = optarg;
			break;
		case 'r':
			cpu_running_mark = atoi(optarg);
			if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
				warnx("%d is not a valid percent",
				    cpu_running_mark);
				usage();
			}
			break;
		case 'v':
			vflag = 1;
			break;
		default:
			usage();
		}

	mode = mode_none;

	/* Poll interval is in units of ms. */
	poll_ival *= 1000;

	/* Look up various sysctl MIBs. */
	len = 2;
	if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
		err(1, "lookup kern.cp_times");
	len = 4;
	if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
		err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
	len = 4;
	if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
		err(1, "lookup freq_levels");

	/* Check if we can read the load and supported freqs. */
	if (read_usage_times(NULL))
		err(1, "read_usage_times");
	if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
		err(1, "error reading supported CPU frequencies");
	if (numfreqs == 0)
		errx(1, "no CPU frequencies in user-specified range");

	/* Run in the background unless in verbose mode. */
	if (!vflag) {
		pid_t otherpid;

		pfh = pidfile_open(pidfile, 0600, &otherpid);
		if (pfh == NULL) {
			if (errno == EEXIST) {
				errx(1, "powerd already running, pid: %d",
				    otherpid);
			}
			warn("cannot open pid file");
		}
		if (daemon(0, 0) != 0) {
			warn("cannot enter daemon mode, exiting");
			pidfile_remove(pfh);
			exit(EXIT_FAILURE);

		}
		pidfile_write(pfh);
	}

	/* Decide whether to use ACPI or APM to read the AC line status. */
	acline_init();

	/*
	 * Exit cleanly on signals.
	 */
	signal(SIGINT, handle_sigs);
	signal(SIGTERM, handle_sigs);

	freq = initfreq = curfreq = get_freq();
	i = get_freq_id(curfreq, freqs, numfreqs);
	if (freq < 1)
		freq = 1;

	/*
	 * If we are in adaptive mode and the current frequency is outside the
	 * user-defined range, adjust it to be within the user-defined range.
	 */
	acline_read();
	if (acline_status > SRC_UNKNOWN)
		errx(1, "invalid AC line status %d", acline_status);
	if ((acline_status == SRC_AC &&
	    (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
	    (acline_status == SRC_BATTERY &&
	    (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
	    (acline_status == SRC_UNKNOWN &&
	    (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
		/* Read the current frequency. */
		len = sizeof(curfreq);
		if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
			if (vflag)
				warn("error reading current CPU frequency");
		}
		if (curfreq < freqs[numfreqs - 1]) {
			if (vflag) {
				printf("CPU frequency is below user-defined "
				    "minimum; changing frequency to %d "
				    "MHz\n", freqs[numfreqs - 1]);
			}
			if (set_freq(freqs[numfreqs - 1]) != 0) {
				warn("error setting CPU freq %d",
				    freqs[numfreqs - 1]);
			}
		} else if (curfreq > freqs[0]) {
			if (vflag) {
				printf("CPU frequency is above user-defined "
				    "maximum; changing frequency to %d "
				    "MHz\n", freqs[0]);
			}
			if (set_freq(freqs[0]) != 0) {
				warn("error setting CPU freq %d",
				    freqs[0]);
			}
		}
	}

	idle = 0;
	/* Main loop. */
	for (;;) {
		FD_ZERO(&fdset);
		if (devd_pipe >= 0) {
			FD_SET(devd_pipe, &fdset);
			nfds = devd_pipe + 1;
		} else {
			nfds = 0;
		}
		if (mode == MODE_HIADAPTIVE || idle < 120)
			to = poll_ival;
		else if (idle < 360)
			to = poll_ival * 2;
		else
			to = poll_ival * 4;
		timeout.tv_sec = to / 1000000;
		timeout.tv_usec = to % 1000000;
		select(nfds, &fdset, NULL, &fdset, &timeout);

		/* If the user requested we quit, print some statistics. */
		if (exit_requested) {
			if (vflag && mjoules_used != 0)
				printf("total joules used: %u.%03u\n",
				    (u_int)(mjoules_used / 1000),
				    (int)mjoules_used % 1000);
			break;
		}

		/* Read the current AC status and record the mode. */
		acline_read();
		switch (acline_status) {
		case SRC_AC:
			mode = mode_ac;
			break;
		case SRC_BATTERY:
			mode = mode_battery;
			break;
		case SRC_UNKNOWN:
			mode = mode_none;
			break;
		default:
			errx(1, "invalid AC line status %d", acline_status);
		}

		/* Read the current frequency. */
		if (idle % 32 == 0) {
			if ((curfreq = get_freq()) == 0)
				continue;
			i = get_freq_id(curfreq, freqs, numfreqs);
		}
		idle++;
		if (vflag) {
			/* Keep a sum of all power actually used. */
			if (mwatts[i] != -1)
				mjoules_used +=
				    (mwatts[i] * (poll_ival / 1000)) / 1000;
		}

		/* Always switch to the lowest frequency in min mode. */
		if (mode == MODE_MIN) {
			freq = freqs[numfreqs - 1];
			if (curfreq != freq) {
				if (vflag) {
					printf("now operating on %s power; "
					    "changing frequency to %d MHz\n",
					    modes[acline_status], freq);
				}
				idle = 0;
				if (set_freq(freq) != 0) {
					warn("error setting CPU freq %d",
					    freq);
					continue;
				}
			}
			continue;
		}

		/* Always switch to the highest frequency in max mode. */
		if (mode == MODE_MAX) {
			freq = freqs[0];
			if (curfreq != freq) {
				if (vflag) {
					printf("now operating on %s power; "
					    "changing frequency to %d MHz\n",
					    modes[acline_status], freq);
				}
				idle = 0;
				if (set_freq(freq) != 0) {
					warn("error setting CPU freq %d",
					    freq);
					continue;
				}
			}
			continue;
		}

		/* Adaptive mode; get the current CPU usage times. */
		if (read_usage_times(&load)) {
			if (vflag)
				warn("read_usage_times() failed");
			continue;
		}

		if (mode == MODE_ADAPTIVE) {
			if (load > cpu_running_mark) {
				if (load > 95 || load > cpu_running_mark * 2)
					freq *= 2;
				else
					freq = freq * load / cpu_running_mark;
				if (freq > freqs[0])
					freq = freqs[0];
			} else if (load < cpu_idle_mark &&
			    curfreq * load < freqs[get_freq_id(
			    freq * 7 / 8, freqs, numfreqs)] *
			    cpu_running_mark) {
				freq = freq * 7 / 8;
				if (freq < freqs[numfreqs - 1])
					freq = freqs[numfreqs - 1];
			}
		} else { /* MODE_HIADAPTIVE */
			if (load > cpu_running_mark / 2) {
				if (load > 95 || load > cpu_running_mark)
					freq *= 4;
				else
					freq = freq * load * 2 / cpu_running_mark;
				if (freq > freqs[0] * 2)
					freq = freqs[0] * 2;
			} else if (load < cpu_idle_mark / 2 &&
			    curfreq * load < freqs[get_freq_id(
			    freq * 31 / 32, freqs, numfreqs)] *
			    cpu_running_mark / 2) {
				freq = freq * 31 / 32;
				if (freq < freqs[numfreqs - 1])
					freq = freqs[numfreqs - 1];
			}
		}
		if (vflag) {
		    printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
			load, curfreq, i, freq);
		}
		j = get_freq_id(freq, freqs, numfreqs);
		if (i != j) {
			if (vflag) {
				printf("changing clock"
				    " speed from %d MHz to %d MHz\n",
				    freqs[i], freqs[j]);
			}
			idle = 0;
			if (set_freq(freqs[j]))
				warn("error setting CPU frequency %d",
				    freqs[j]);
		}
	}
	if (set_freq(initfreq))
		warn("error setting CPU frequency %d", initfreq);
	free(freqs);
	free(mwatts);
	devd_close();
	if (!vflag)
		pidfile_remove(pfh);

	exit(0);
}
Example #25
0
int main(int argc, char **argv)
{
	int ch;
	struct iovec iov;
	struct utmp *utmpptr;
	char *p;
	char line[sizeof(utmpptr->ut_line) + 1];
	int print_banner = TRUE;
	char *mbuf, *fname = NULL;
	size_t mbufsize;
	unsigned timeout = WRITE_TIME_OUT;
	char **mvec = NULL;
	int mvecsz = 0;

	static const struct option longopts[] = {
		{ "nobanner",	no_argument,		0, 'n' },
		{ "timeout",	required_argument,	0, 't' },
		{ "version",	no_argument,		0, 'V' },
		{ "help",	no_argument,		0, 'h' },
		{ NULL,	0, 0, 0 }
	};

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

	while ((ch = getopt_long(argc, argv, "nt:Vh", longopts, NULL)) != -1) {
		switch (ch) {
		case 'n':
			if (geteuid() == 0)
				print_banner = FALSE;
			else
				warnx(_("--nobanner is available only for root"));
			break;
		case 't':
			timeout = strtou32_or_err(optarg, _("invalid timeout argument"));
			if (timeout < 1)
				errx(EXIT_FAILURE, _("invalid timeout argument: %s"), optarg);
			break;
		case 'V':
			printf(UTIL_LINUX_VERSION);
			exit(EXIT_SUCCESS);
		case 'h':
			usage(stdout);
		default:
			usage(stderr);
		}
	}
	argc -= optind;
	argv += optind;

	if (argc == 1 && access(argv[0], F_OK) == 0)
		fname = argv[0];
	else if (argc >= 1) {
		mvec = argv;
		mvecsz = argc;
	}

	mbuf = makemsg(fname, mvec, mvecsz, &mbufsize, print_banner);

	iov.iov_base = mbuf;
	iov.iov_len = mbufsize;
	while((utmpptr = getutent())) {
		if (!utmpptr->ut_user[0])
			continue;
#ifdef USER_PROCESS
		if (utmpptr->ut_type != USER_PROCESS)
			continue;
#endif
		/* Joey Hess reports that use-sessreg in /etc/X11/wdm/
		   produces ut_line entries like :0, and a write
		   to /dev/:0 fails. */
		if (utmpptr->ut_line[0] == ':')
			continue;

		xstrncpy(line, utmpptr->ut_line, sizeof(utmpptr->ut_line));
		if ((p = ttymsg(&iov, 1, line, timeout)) != NULL)
			warnx("%s", p);
	}
	endutent();
	free(mbuf);
	exit(EXIT_SUCCESS);
}
Example #26
0
int
main(int argc, char *argv[])
{
	struct ntpd_conf	 lconf;
	struct pollfd		 pfd[POLL_MAX];
	pid_t			 chld_pid = 0, pid;
	const char		*conffile;
	int			 fd_ctl, ch, nfds;
	int			 pipe_chld[2];
	struct passwd		*pw;
	extern char 		*__progname;

	__progname = _compat_get_progname(argv[0]);

	if (strcmp(__progname, "ntpctl") == 0) {
		ctl_main (argc, argv);
		/* NOTREACHED */
	}

	conffile = CONFFILE;

	bzero(&lconf, sizeof(lconf));

	log_init(1);		/* log to stderr until daemonized */

	while ((ch = getopt(argc, argv, "df:nsSv")) != -1) {
		switch (ch) {
		case 'd':
			lconf.debug = 1;
			break;
		case 'f':
			conffile = optarg;
			break;
		case 'n':
			lconf.noaction = 1;
			break;
		case 's':
			lconf.settime = 1;
			break;
		case 'S':
			lconf.settime = 0;
			break;
		case 'v':
			debugsyslog = 1;
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}

	argc -= optind;
	argv += optind;
	if (argc > 0)
		usage();

	if (parse_config(conffile, &lconf))
		exit(1);

	if (lconf.noaction) {
		fprintf(stderr, "configuration OK\n");
		exit(0);
	}

	if (geteuid())
		errx(1, "need root privileges");

	if ((pw = getpwnam(NTPD_USER)) == NULL)
		errx(1, "unknown user %s", NTPD_USER);

#ifndef HAVE_ARC4RANDOM
	seed_rng();
#endif

	if (setpriority(PRIO_PROCESS, 0, -20) == -1)
		warn("can't set priority");

	reset_adjtime();
	if (!lconf.settime) {
		log_init(lconf.debug);
		if (!lconf.debug)
			if (daemon(1, 0))
				fatal("daemon");
	} else
		timeout = SETTIME_TIMEOUT * 1000;

	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe_chld) == -1)
		fatal("socketpair");

	if ((fd_ctl = control_init(CTLSOCKET)) == -1)
		fatalx("control socket init failed");
	if (control_listen(fd_ctl) == -1)
		fatalx("control socket listen failed");

	signal(SIGCHLD, sighdlr);
	/* fork child process */
	chld_pid = ntp_main(pipe_chld, fd_ctl, &lconf, pw);

	setproctitle("[priv]");
	readfreq();

	signal(SIGTERM, sighdlr);
	signal(SIGINT, sighdlr);
	signal(SIGHUP, sighdlr);

	close(pipe_chld[1]);

	if ((ibuf = malloc(sizeof(struct imsgbuf))) == NULL)
		fatal(NULL);
	imsg_init(ibuf, pipe_chld[0]);

	while (quit == 0) {
		pfd[PFD_PIPE].fd = ibuf->fd;
		pfd[PFD_PIPE].events = POLLIN;
		if (ibuf->w.queued)
			pfd[PFD_PIPE].events |= POLLOUT;

		if ((nfds = poll(pfd, 1, timeout)) == -1)
			if (errno != EINTR) {
				log_warn("poll error");
				quit = 1;
			}

		if (nfds == 0 && lconf.settime) {
			lconf.settime = 0;
			timeout = INFTIM;
			log_init(lconf.debug);
			log_debug("no reply received in time, skipping initial "
			    "time setting");
			if (!lconf.debug)
				if (daemon(1, 0))
					fatal("daemon");
		}

		if (nfds > 0 && (pfd[PFD_PIPE].revents & POLLOUT))
			if (msgbuf_write(&ibuf->w) <= 0 && errno != EAGAIN) {
				log_warn("pipe write error (to child)");
				quit = 1;
			}

		if (nfds > 0 && pfd[PFD_PIPE].revents & POLLIN) {
			nfds--;
			if (dispatch_imsg(&lconf) == -1)
				quit = 1;
		}

		if (sigchld) {
			if (check_child(chld_pid, "child")) {
				quit = 1;
				chld_pid = 0;
			}
			sigchld = 0;
		}

	}

	signal(SIGCHLD, SIG_DFL);

	if (chld_pid)
		kill(chld_pid, SIGTERM);

	do {
		if ((pid = wait(NULL)) == -1 &&
		    errno != EINTR && errno != ECHILD)
			fatal("wait");
	} while (pid != -1 || (pid == -1 && errno == EINTR));

	msgbuf_clear(&ibuf->w);
	free(ibuf);
	log_info("Terminating");
	return (0);
}
Example #27
0
static void
ngx_worker_process_init(ngx_cycle_t *cycle, ngx_int_t worker)
{
    sigset_t          set;
    ngx_int_t         n;
    ngx_uint_t        i;
    struct rlimit     rlmt;
    ngx_core_conf_t  *ccf;
    ngx_listening_t  *ls;

#if (NGX_HAVE_CPU_AFFINITY)
    u_char            buf[2 * sizeof(CPU_SET_T) + 1];
    u_char           *p;
    CPU_SET_T        *cpu_affinity;
#endif

    if (ngx_set_environment(cycle, NULL) == NULL) {
        /* fatal */
        exit(2);
    }

    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    if (worker >= 0 && ccf->priority != 0) {
        if (setpriority(PRIO_PROCESS, 0, ccf->priority) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setpriority(%d) failed", ccf->priority);
        }
    }

    if (ccf->rlimit_nofile != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_nofile;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_nofile;

        if (setrlimit(RLIMIT_NOFILE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_NOFILE, %i) failed",
                          ccf->rlimit_nofile);
        }
    }

    if (ccf->rlimit_core != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_core;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_core;

        if (setrlimit(RLIMIT_CORE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_CORE, %O) failed",
                          ccf->rlimit_core);
        }
    }

#ifdef RLIMIT_SIGPENDING
    if (ccf->rlimit_sigpending != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_sigpending;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_sigpending;

        if (setrlimit(RLIMIT_SIGPENDING, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_SIGPENDING, %i) failed",
                          ccf->rlimit_sigpending);
        }
    }
#endif

    if (geteuid() == 0) {
        if (setgid(ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setgid(%d) failed", ccf->group);
            /* fatal */
            exit(2);
        }

        if (initgroups(ccf->username, ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "initgroups(%s, %d) failed",
                          ccf->username, ccf->group);
        }

        if (setuid(ccf->user) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setuid(%d) failed", ccf->user);
            /* fatal */
            exit(2);
        }
    }

#if (NGX_HAVE_CPU_AFFINITY)

    if (worker >= 0) {
        cpu_affinity = ngx_get_cpu_affinity(worker);

        if (cpu_affinity) {
           n = ngx_min(sizeof(CPU_SET_T) - 1, 7);
            for (p = buf; n >= 0; n--) {
                p = ngx_snprintf(p, 2, "%02Xd", *((u_char *) cpu_affinity + n));
            }

            *p = '\0';

            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0,
                          ngx_setaffinity_n "(0x%s)", buf);

            if (ngx_setaffinity(cpu_affinity) == -1) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                              ngx_setaffinity_n "(0x%s) failed", buf);
            }
        }
    }

#endif

#if (NGX_HAVE_PR_SET_DUMPABLE)

    /* allow coredump after setuid() in Linux 2.4.x */

    if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "prctl(PR_SET_DUMPABLE) failed");
    }

#endif

    if (ccf->working_directory.len) {
        if (chdir((char *) ccf->working_directory.data) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "chdir(\"%s\") failed", ccf->working_directory.data);
            /* fatal */
            exit(2);
        }
    }

    sigemptyset(&set);

    if (sigprocmask(SIG_SETMASK, &set, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "sigprocmask() failed");
    }

    srandom((ngx_pid << 16) ^ ngx_time());

    /*
     * disable deleting previous events for the listening sockets because
     * in the worker processes there are no events at all at this point
     */
    ls = cycle->listening.elts;
    for (i = 0; i < cycle->listening.nelts; i++) {
        ls[i].previous = NULL;
    }

    for (i = 0; ngx_modules[i]; i++) {
        if (ngx_modules[i]->init_process) {
            if (ngx_modules[i]->init_process(cycle) == NGX_ERROR) {
                /* fatal */
                exit(2);
            }
        }
    }

    for (n = 0; n < ngx_last_process; n++) {

        if (ngx_processes[n].pid == -1) {
            continue;
        }

        if (n == ngx_process_slot) {
            continue;
        }

        if (ngx_processes[n].channel[1] == -1) {
            continue;
        }

        if (close(ngx_processes[n].channel[1]) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "close() channel failed");
        }
    }

    if (close(ngx_processes[ngx_process_slot].channel[0]) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "close() channel failed");
    }

#if 0
    ngx_last_process = 0;
#endif

    if (ngx_add_channel_event(cycle, ngx_channel, NGX_READ_EVENT,
                              ngx_channel_handler)
        == NGX_ERROR)
    {
        /* fatal */
        exit(2);
    }
}
Example #28
0
static int
LinuxInit (void)
{
    int fd = -1;
    char vtname[11];
    struct vt_stat vts;

    LinuxConsoleFd = -1;
    /* check if we're run with euid==0 */
    if (geteuid() != 0)
    {
	FatalError("LinuxInit: Server must be suid root\n");
    }

    if (kdVirtualTerminal >= 0)
	vtno = kdVirtualTerminal;
    else
    {
	if ((fd = open("/dev/tty0",O_WRONLY,0)) < 0)
	{
	    FatalError(
		       "LinuxInit: Cannot open /dev/tty0 (%s)\n",
		       strerror(errno));
	}
	if ((ioctl(fd, VT_OPENQRY, &vtno) < 0) ||
	    (vtno == -1))
	{
	    FatalError("xf86OpenConsole: Cannot find a free VT\n");
	}
	close(fd);
    }

    snprintf(vtname,sizeof(vtname),"/dev/tty%d",vtno); /* /dev/tty1-64 */

    if ((LinuxConsoleFd = open(vtname, O_RDWR|O_NDELAY, 0)) < 0)
    {
	FatalError("LinuxInit: Cannot open %s (%s)\n",
		   vtname, strerror(errno));
    }

    /* change ownership of the vt */
    LinuxCheckChown (vtname);

    /*
     * the current VT device we're running on is not "console", we want
     * to grab all consoles too
     *
     * Why is this needed?
     */
    LinuxCheckChown ("/dev/tty0");
    /*
     * Linux doesn't switch to an active vt after the last close of a vt,
     * so we do this ourselves by remembering which is active now.
     */
    memset (&vts, '\0', sizeof (vts));	/* valgrind */
    if (ioctl(LinuxConsoleFd, VT_GETSTATE, &vts) == 0)
    {
	activeVT = vts.v_active;
    }

    return 1;
}
Example #29
0
int
main(int argc, char *argv[])
{
	char *arg;
	const char *printer;
	struct passwd *p;
	static char root[] = "root";

	printer = NULL;
	uid = getuid();
	euid = geteuid();
	PRIV_END	/* be safe */
	progname = argv[0];
	gethostname(local_host, sizeof(local_host));
	openlog("lpd", 0, LOG_LPR);

	/*
	 * Bogus code later checks for string equality between 
	 * `person' and "root", so if we are root, better make sure
	 * that code will succeed.
	 */
	if (getuid() == 0) {
		person = root;
	} else if ((person = getlogin()) == NULL) {
		if ((p = getpwuid(getuid())) == NULL)
			fatal(0, "Who are you?");
		if (strlen(p->pw_name) >= sizeof(luser))
			fatal(0, "Your name is too long");
		strcpy(luser, p->pw_name);
		person = luser;
	}
	while (--argc) {
		if ((arg = *++argv)[0] == '-')
			switch (arg[1]) {
			case 'P':
				if (arg[2])
					printer = &arg[2];
				else if (argc > 1) {
					argc--;
					printer = *++argv;
				}
				break;
			case '\0':
				if (!users) {
					users = -1;
					break;
				}
			default:
				usage();
			}
		else {
			if (users < 0)
				usage();
			if (isdigit(arg[0])) {
				if (requests >= MAXREQUESTS)
					fatal(0, "Too many requests");
				requ[requests++] = atoi(arg);
			} else {
				if (users >= MAXUSERS)
					fatal(0, "Too many users");
				user[users++] = arg;
			}
		}
	}
	if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;

	rmjob(printer);
	exit(0);
}
/**
    Default constructor, represents current user.
*/
    SCXUser::SCXUser() : m_uid(geteuid())
    {
        SetName();
    }