예제 #1
0
/****************************************************************************
check for a possible hosts equiv or rhosts entry for the user
****************************************************************************/
BOOL check_hosts_equiv(char *user)
{
  char *fname = NULL;
  pstring rhostsfile;
  struct passwd *pass = Get_Pwnam(user,True);

  if (!pass) 
    return(False);

  fname = lp_hosts_equiv();

  /* note: don't allow hosts.equiv on root */
  if (fname && *fname && (pass->pw_uid != 0))
    {
      if (check_user_equiv(user,client_name(),fname))
	return(True);
    }
  
  if (lp_use_rhosts())
    {
      char *home = get_home_dir(user);
      if (home)
	{
	  slprintf(rhostsfile, sizeof(rhostsfile)-1, "%s/.rhosts", home);
	  if (check_user_equiv(user,client_name(),rhostsfile))
	    return(True);
	}
    }

  return(False);
}
예제 #2
0
/* return true if access should be allowed to a service*/
BOOL check_access(int snum)
{
  char *denyl,*allowl;
  BOOL ret = False;

  denyl = lp_hostsdeny(snum);
  if (denyl) denyl = strdup(denyl);

  allowl = lp_hostsallow(snum);
  if (allowl) allowl = strdup(allowl);

  if ((!denyl || *denyl==0) && (!allowl || *allowl==0))
    ret = True;

  if (!ret)
    {
      if (allow_access(denyl,allowl,client_name(),client_addr()))
	{
	  if (snum >= 0)
	    DEBUG(2,("Allowed connection from %s (%s) to %s\n",
		     client_name(),client_addr(),
		     lp_servicename(snum)));
	  ret = True;
	}
      else
	if (snum >= 0)
	  DEBUG(0,("%s Denied connection from %s (%s) to %s\n",
		   timestring(), client_name(),client_addr(),
		   lp_servicename(snum)));
    }

  if (denyl) free(denyl);
  if (allowl) free(allowl);
  return(ret);
}
예제 #3
0
/***************************************************************************
 * int replace
 *
 * fill in the template given by source using the stack and return it into
 * dest
 * *************************************************************************/
int replace(const char *source, struct strstack *stack, pstring dest, MYSQL *mysql)
{
	char *uname = current_user_info.smb_name;
	const char *remote;
	enum { COPY, PARAM } state = COPY;
	char buffer[6];
	int i, cur_parm, bindex = 0;
	fstring replaced;
	char replaced2[512];

	for (i=0; i < strlen(source); i++) {
		switch (state) {
			case COPY:
				if ( source[i] != '$' )
					*dest++ = source[i];
				else state = PARAM;
				break;
			case PARAM:
				if ( source[i] > '9' || source[i] < '0' ) {
					buffer[bindex] = '\0';
					if ( buffer[0] == '\0' ) {
						switch (source[i]) {
							case 'U':		/* user name */
								pstrcpy(dest, uname);
								dest += strlen(uname);
								break;
							case 'I':		/* remote host ip address */
								pstrcpy(dest, client_name());
								dest += strlen(client_name());
								break;
							case 'N':		/* host name */
								remote = get_remote_machine_name();
								pstrcpy(dest, remote);
								dest += strlen(remote);
								break;
							default:
								*dest++ = source[i];
								break;
						}
					} else {
						cur_parm = atoi(buffer);
						stack_get(stack, cur_parm, replaced);
						mysql_real_escape_string(mysql, replaced2, replaced,
								strlen(replaced));
						pstrcpy(dest, replaced2);
						dest += strlen(replaced2);
						*dest++ = source[i];
					}
					bindex = 0;
					state = COPY;
				} else
					buffer[bindex++] = source[i];
				break;
		}
	}
	*dest = '\0';

	return 1;
}
예제 #4
0
void *
proc (void *args)
{
    CommandContext *context = (CommandContext *) args;
    const char **argv = context->getArgv();
    std::string client_name(argv[2] + std::to_string(some_id++));
    AgentClient *client;

    // Find this client
    client = AgentClient::find(client_name);
    if (client != NULL) {
        std::cout << "Client already exist: " << client_name << std::endl;
        return NULL;
    }

    // Create a client
    client = AgentClient::create(grpc::CreateChannel(AGENT_SERVER_IP_PORT,
                                 grpc::InsecureCredentials()),
                                 client_name,
                                 global_id++,
                                 parser->getLogDir());

    // Sample Frequency
    uint32_t sample_frequency = atoi(argv[3]);

    // collect the list of paths
    std::vector<std::string> path_list;
    for (int i = 4; argv[i]; i++) {
        path_list.push_back(argv[i]);
    }

    client->subscribeTelemetry(path_list, sample_frequency);
    delete client;
    return NULL;
}
예제 #5
0
void
handle_subscribe_limits (int argc, const char *argv[])
{
    std::string client_name(argv[1]);
    AgentClient *client;

    // Find this client
    client = AgentClient::find(client_name);
    if (client != NULL) {
        std::cout << "Client already exist: " << client_name << std::endl;
        return;
    }

    // Create a client
    client = AgentClient::create(grpc::CreateChannel(AGENT_SERVER_IP_PORT,
                                 grpc::InsecureCredentials()),
                                 client_name,
                                 global_id++,
                                 parser->getLogDir());

    // Sample Frequency
    uint32_t sample_frequency = atoi(argv[2]);
    uint32_t limit_records = atoi(argv[3]);
    uint32_t limit_seconds = atoi(argv[4]);

    // collect the list of paths
    std::vector<std::string> path_list;
    for (int i = 5; argv[i]; i++) {
        path_list.push_back(argv[i]);
    }

    client->subscribeTelemetry(path_list, sample_frequency,
                               false, limit_records, limit_seconds);
    delete client;
}
예제 #6
0
static BOOL get_md4pw(char *md4pw, char *mach_acct)
{
	SAM_ACCOUNT *sampass = NULL;
	const uint8 *pass;
	BOOL ret;
	uint32 acct_ctrl;

#if 0
    /*
     * Currently this code is redundent as we already have a filter
     * by hostname list. What this code really needs to do is to 
     * get a hosts allowed/hosts denied list from the SAM database
     * on a per user basis, and make the access decision there.
     * I will leave this code here for now as a reminder to implement
     * this at a later date. JRA.
     */

	if (!allow_access(lp_domain_hostsdeny(), lp_domain_hostsallow(),
	                  client_name(), client_addr()))
	{
		DEBUG(0,("get_md4pw: Workstation %s denied access to domain\n", mach_acct));
		return False;
	}
#endif /* 0 */

	if(!NT_STATUS_IS_OK(pdb_init_sam(&sampass)))
		return False;

	/* JRA. This is ok as it is only used for generating the challenge. */
	become_root();
	ret=pdb_getsampwnam(sampass, mach_acct);
	unbecome_root();
 
 	if (ret==False) {
 		DEBUG(0,("get_md4pw: Workstation %s: no account in domain\n", mach_acct));
		pdb_free_sam(&sampass);
		return False;
	}

	acct_ctrl = pdb_get_acct_ctrl(sampass);
	if (!(acct_ctrl & ACB_DISABLED) &&
	    ((acct_ctrl & ACB_DOMTRUST) ||
	     (acct_ctrl & ACB_WSTRUST) ||
	     (acct_ctrl & ACB_SVRTRUST)) &&
	    ((pass=pdb_get_nt_passwd(sampass)) != NULL)) {
		memcpy(md4pw, pass, 16);
		dump_data(5, md4pw, 16);
 		pdb_free_sam(&sampass);
		return True;
	}
 	
	DEBUG(0,("get_md4pw: Workstation %s: no account in domain\n", mach_acct));
	pdb_free_sam(&sampass);
	return False;

}
예제 #7
0
 //--------------------------------------------------------------
 unsigned int
 Reactor::_allow(struct libwebsocket *ws, Protocol* const protocol, const long fd){
     std::string client_ip(128, 0);
     std::string client_name(128, 0);
     
     libwebsockets_get_peer_addresses(context, ws, libwebsocket_get_socket_fd(ws),
                                      &client_name[0], client_name.size(),
                                      &client_ip[0], client_ip.size());
     return protocol->_allowClient(client_name, client_ip);
 }
예제 #8
0
 //--------------------------------------------------------------
 unsigned int
 Reactor::_allow(Protocol* const protocol, const long fd){
     std::string client_ip(128, 0);
     std::string client_name(128, 0);
     
     libwebsockets_get_peer_addresses((int)fd,
                                      &client_name[0], client_name.size(),
                                      &client_ip[0], client_ip.size());
     return protocol->_allowClient(client_name, client_ip);
 }
예제 #9
0
void
handle_unsubscribe_id (int argc, const char *argv[])
{
    uint32_t subscription_id = atoi(argv[1]);
    std::string client_name(AGENTCLIENT_MGMT);
    AgentClient *client;

    // Find this client
    client = AgentClient::find(client_name);
    if (!client) {
        std::cout << "Failed to find client: " << client_name << std::endl;
        return;
    }

    client->cancelSubscribeTelemetryId(subscription_id);
    // Leave the delete of client in the subscription thread
}
예제 #10
0
unsigned int WebSockets::onAllow(
			WebSocketProtocol* protocol
			,const long fd
)
{
	string client_ip(128, 0);
	string client_name(128, 0);
	
	libwebsockets_get_peer_addresses(
			(int)fd
			,&client_name[0]
			,client_name.size()
			,&client_ip[0]
			,client_ip.size()
	);
	
	return protocol->allowClient(client_name, client_ip);
}
예제 #11
0
static pa_hook_result_t source_output_new_hook_callback(pa_core *c, pa_source_output_new_data *data, struct userdata *u) {
    struct rule *r;
    char *name;

    pa_assert(data);

    if (!data->client || !(name = client_name(data->client)))
        return PA_HOOK_OK;

    if ((r = pa_hashmap_get(u->hashmap, name))) {
        if (!data->source && r->source) {
            if ((data->source = pa_namereg_get(c, r->source, PA_NAMEREG_SOURCE, 1)))
                pa_log_info("Restoring source for <%s>", r->name);
        }
    }

    return PA_HOOK_OK;
}
예제 #12
0
void
handle_unsubscribe (int argc, const char *argv[])
{
    std::string client_name((const char *) argv[1]);
    AgentClient *client;

    if (strcmp(argv[1], AGENTCLIENT_MGMT) == 0) {
        std::cout << AGENTCLIENT_MGMT << " cannot be deleted" << std::endl;
        return;
    }

    // Find this client
    client = AgentClient::find(client_name);
    if (!client) {
        std::cout << "Failed to find client: " << client_name << std::endl;
        return;
    }

    client->cancelSubscribeTelemetry();
    // Leave the delete of client in the subscription thread
}
예제 #13
0
static pa_hook_result_t sink_input_new_hook_callback(pa_core *c, pa_sink_input_new_data *data, struct userdata *u) {
    struct rule *r;
    char *name;

    pa_assert(data);

    /* In the NEW hook we only adjust the device. Adjusting the volume
     * is left for the FIXATE hook */

    if (!data->client || !(name = client_name(data->client)))
        return PA_HOOK_OK;

    if ((r = pa_hashmap_get(u->hashmap, name))) {
        if (!data->sink && r->sink) {
            if ((data->sink = pa_namereg_get(c, r->sink, PA_NAMEREG_SINK, 1)))
                pa_log_info("Restoring sink for <%s>", r->name);
        }
    }

    pa_xfree(name);

    return PA_HOOK_OK;
}
예제 #14
0
static pa_hook_result_t sink_input_fixate_hook_callback(pa_core *c, pa_sink_input_new_data *data, struct userdata *u) {
    struct rule *r;
    char *name;

    pa_assert(data);

    /* In the FIXATE hook we only adjust the volum. Adjusting the device
     * is left for the NEW hook */

    if (!data->client || !(name = client_name(data->client)))
        return PA_HOOK_OK;

    if ((r = pa_hashmap_get(u->hashmap, name))) {

        if (r->volume_is_set && data->sample_spec.channels == r->volume.channels) {
            pa_log_info("Restoring volume for <%s>", r->name);
            pa_sink_input_new_data_set_volume(data, &r->volume);
        }
    }

    pa_xfree(name);

    return PA_HOOK_OK;
}
예제 #15
0
char *alloc_sub_basic(const char *smb_name, const char *str)
{
	char *b, *p, *s, *t, *r, *a_string;
	fstring pidstr;
	struct passwd *pass;
	const char *local_machine_name = get_local_machine_name();

	/* workaround to prevent a crash while lookinf at bug #687 */
	
	if ( !str ) {
		DEBUG(0,("alloc_sub_basic: NULL source string!  This should not happen\n"));
		return NULL;
	}
	
	a_string = strdup(str);
	if (a_string == NULL) {
		DEBUG(0, ("alloc_sub_specified: Out of memory!\n"));
		return NULL;
	}
	
	for (b = s = a_string; (p = strchr_m(s, '%')); s = a_string + (p - b)) {

		r = NULL;
		b = t = a_string;
		
		switch (*(p+1)) {
		case 'U' : 
			r = strdup_lower(smb_name);
			if (r == NULL) goto error;
			t = realloc_string_sub(t, "%U", r);
			break;
		case 'G' :
			r = strdup(smb_name);
			if (r == NULL) goto error;
			if ((pass = Get_Pwnam(r))!=NULL) {
				t = realloc_string_sub(t, "%G", gidtoname(pass->pw_gid));
			} 
			break;
		case 'D' :
			r = strdup_upper(current_user_info.domain);
			if (r == NULL) goto error;
			t = realloc_string_sub(t, "%D", r);
			break;
		case 'I' :
			t = realloc_string_sub(t, "%I", client_addr());
			break;
		case 'L' : 
			if (local_machine_name && *local_machine_name)
				t = realloc_string_sub(t, "%L", local_machine_name); 
			else
				t = realloc_string_sub(t, "%L", global_myname()); 
			break;
		case 'N':
			t = realloc_string_sub(t, "%N", automount_server(smb_name));
			break;
		case 'M' :
			t = realloc_string_sub(t, "%M", client_name());
			break;
		case 'R' :
			t = realloc_string_sub(t, "%R", remote_proto);
			break;
		case 'T' :
			t = realloc_string_sub(t, "%T", timestring(False));
			break;
		case 'a' :
			t = realloc_string_sub(t, "%a", remote_arch);
			break;
		case 'd' :
			slprintf(pidstr,sizeof(pidstr)-1, "%d",(int)sys_getpid());
			t = realloc_string_sub(t, "%d", pidstr);
			break;
		case 'h' :
			t = realloc_string_sub(t, "%h", myhostname());
			break;
		case 'm' :
			t = realloc_string_sub(t, "%m", remote_machine);
			break;
		case 'v' :
			t = realloc_string_sub(t, "%v", SAMBA_VERSION_STRING);
			break;
		case '$' :
			t = realloc_expand_env_var(t, p); /* Expand environment variables */
			break;
			
		default: 
			break;
		}

		p++;
		SAFE_FREE(r);
		if (t == NULL) goto error;
		a_string = t;
	}

	return a_string;
error:
	SAFE_FREE(a_string);
	return NULL;
}
예제 #16
0
파일: S5.c 프로젝트: libm3l/lsipdx
int main(int argc, char *argv[])
{
	node_t *Gnode=NULL, *RecNode=NULL, *TmpNode = NULL;
	pid_t  childpid;
	size_t *dim, i, j;

	lmint_t sockfd, portno1, portno2, n, status, ch_stat, *tmpint, *tmpi;

        socklen_t clilen;
        struct sockaddr_in cli_addr;
	lmchar_t *nameIn1="DATA_2";
	lmchar_t *nameIn2="DATA_3";
	lmchar_t *nameOut="DATA_4";

	lmint_t nmax, retval;
	lmdouble_t *tmpdf;
	client_fce_struct_t InpPar, *PInpPar;
	opts_t opts, *Popts_1;
	
	struct timespec tim, tim2;
 	tim.tv_sec = 5;
// 	tim.tv_sec = 0;
// 	tim.tv_nsec = 300000000L;    /* 0.1 secs */
	tim.tv_nsec = 10000000L;    /* 0.1 secs */

	nmax = 100000;
	PInpPar = &InpPar;
/*
 * get port number
 */
     if (argc < 4) {
       fprintf(stderr,"ERROR, no IPaddress and port numbers provided\n");
       exit(1);
     }
 	portno1 = atoi(argv[2]);
 	portno2 = atoi(argv[3]);
/*
 * open socket - because we use more then just send - receive scenario
 * we need to open socket manualy and used Send_receive function with hostname = NULL, ie. as server
 * portno is then replaced by socket number
 */
	for(i=0; i<nmax; i++){

 		printf("\n\n--------------------------------    i = %ld\n\n", i);
/*
 * open socket
 */
		PInpPar->channel_name = nameIn1;
		PInpPar->SR_MODE = 'R';
		if ( (PInpPar->mode = get_exchange_channel_mode('D', 'N')) == -1)
			Error("wrong client mode");
		Popts_1 = &opts;
		m3l_set_Send_receive_tcpipsocket(&Popts_1);
	
		if( (sockfd = open_connection_to_server(argv[1], portno1, PInpPar, Popts_1)) < 1)
			Error("client_sender: Error when opening socket");
		
		Gnode=client_receiver(sockfd,  PInpPar, (opts_t *)NULL, (opts_t *)NULL);
		
		if(m3l_Cat(Gnode, "--all", "-P", "-L",  "*",   (char *)NULL) != 0)
			Error("CatData");
/* 
 * close socket
 */
		if( close(sockfd) == -1)
			Perror("close");
		
		if(m3l_Umount(&Gnode) != 1)
			Perror("m3l_Umount");
		
		
		printf(" Data received \n");
	
		
		
		
		
/*
 * open socket
 */
		PInpPar->channel_name = nameIn2;
		PInpPar->SR_MODE = 'R';
		if ( (PInpPar->mode = get_exchange_channel_mode('D', 'N')) == -1)
			Error("wrong client mode");
		Popts_1 = &opts;
		m3l_set_Send_receive_tcpipsocket(&Popts_1);
	
		if( (sockfd = open_connection_to_server(argv[1], portno2, PInpPar, Popts_1)) < 1)
			Error("client_sender: Error when opening socket");
		
		Gnode = client_receiver(sockfd,  PInpPar, (opts_t *)NULL, (opts_t *)NULL);
		
		if(m3l_Cat(Gnode, "--all", "-P", "-L",  "*",   (char *)NULL) != 0)
			Error("CatData");
/* 
 * close socket
 */
		if( close(sockfd) == -1)
			Perror("close");
		
		if(m3l_Umount(&Gnode) != 1)
			Perror("m3l_Umount");
		
		
		printf(" Data received \n");
		
		
/*
 * open socket, IP address of server is in argv[1], port number is in portno
 */
		Gnode = client_name("Text from Solver_5");
// 	
		dim = (size_t *) malloc( 1* sizeof(size_t));
		dim[0] = 1;
/*
 * add iteraztion number
 */
		if(  (TmpNode = m3l_Mklist("Iteration_Number", "I", 1, dim, &Gnode, "/Client_Data", "./", (char *)NULL)) == 0)
				Error("m3l_Mklist");
		TmpNode->data.i[0] = i;
/*
 * add pressure array, array has 5 pressure with some values
 */	
		dim[0] = 3;
		if(  (TmpNode = m3l_Mklist("S4_numbers", "D", 1, dim, &Gnode, "/Client_Data", "./", (char *)NULL)) == 0)
				Error("m3l_Mklist");
		tmpdf = (double *)m3l_get_data_pointer(TmpNode);
		for(j=0; j<3; j++)
			tmpdf[j] = (i+1)*j*2.3;
		free(dim);
		
// 		if(m3l_Cat(Gnode, "--all", "-P", "-L",  "*",   (char *)NULL) != 0)
// 			Error("CatData");
/*
 * open socket
 */
		PInpPar->channel_name = nameOut;
		PInpPar->SR_MODE = 'S';
		if ( (PInpPar->mode = get_exchange_channel_mode('D', 'N')) == -1)
			Error("wrong client mode");
		Popts_1 = &opts;
		m3l_set_Send_receive_tcpipsocket(&Popts_1);
	
		if( (sockfd = open_connection_to_server(argv[1], portno2, PInpPar, Popts_1)) < 1)
			Error("client_sender: Error when opening socket");
		
		client_sender(Gnode, sockfd,  PInpPar, (opts_t *)NULL, (opts_t *)NULL);
/* 
 * close socket
 */
		if( close(sockfd) == -1)
			Perror("close");
		
		if(m3l_Umount(&Gnode) != 1)
			Perror("m3l_Umount");



		if(nanosleep(&tim , &tim2) < 0 )
			Error("Nano sleep system call failed \n");
 	}


     return 0; 
}
예제 #17
0
static int
cups_job_submit(int snum, struct printjob *pjob)
{
	int		ret;		/* Return value */
	http_t		*http;		/* HTTP connection to server */
	ipp_t		*request,	/* IPP Request */
			*response;	/* IPP Response */
	cups_lang_t	*language;	/* Default language */
	char		uri[HTTP_MAX_URI]; /* printer-uri attribute */
	char 		*clientname; 	/* hostname of client for job-originating-host attribute */
	pstring		new_jobname;
	int		num_options = 0; 
	cups_option_t 	*options;

	DEBUG(5,("cups_job_submit(%d, %p (%d))\n", snum, pjob, pjob->sysjob));

       /*
        * Make sure we don't ask for passwords...
	*/

        cupsSetPasswordCB(cups_passwd_cb);

       /*
	* Try to connect to the server...
	*/

	if ((http = httpConnect(cupsServer(), ippPort())) == NULL)
	{
		DEBUG(0,("Unable to connect to CUPS server %s - %s\n", 
			 cupsServer(), strerror(errno)));
		return (1);
	}

       /*
	* Build an IPP_PRINT_JOB request, which requires the following
	* attributes:
	*
	*    attributes-charset
	*    attributes-natural-language
	*    printer-uri
	*    requesting-user-name
	*    [document-data]
	*/

	request = ippNew();

	request->request.op.operation_id = IPP_PRINT_JOB;
	request->request.op.request_id   = 1;

	language = cupsLangDefault();

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
        	     "attributes-charset", NULL, cupsLangEncoding(language));

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
        	     "attributes-natural-language", NULL, language->language);

	slprintf(uri, sizeof(uri) - 1, "ipp://localhost/printers/%s",
	         PRINTERNAME(snum));

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
        	     "printer-uri", NULL, uri);

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
        	     NULL, pjob->user);

	clientname = client_name();
	if (strcmp(clientname, "UNKNOWN") == 0) {
		clientname = client_addr();
	}

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
	             "job-originating-host-name", NULL,
		      clientname);

        pstr_sprintf(new_jobname,"%s%.8u %s", PRINT_SPOOL_PREFIX, 
		(unsigned int)pjob->smbjob, pjob->jobname);

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-name", NULL,
        	     new_jobname);

	/* 
	 * add any options defined in smb.conf 
	 */

	num_options = 0;
	options     = NULL;
	num_options = cupsParseOptions(lp_cups_options(snum), num_options, &options);

	if ( num_options )
		cupsEncodeOptions(request, num_options, options); 

       /*
	* Do the request and get back a response...
	*/

	slprintf(uri, sizeof(uri) - 1, "/printers/%s", PRINTERNAME(snum));

        ret = 1;
	if ((response = cupsDoFileRequest(http, request, uri,
	                                  pjob->filename)) != NULL)
	{
		if (response->request.status.status_code >= IPP_OK_CONFLICT)
			DEBUG(0,("Unable to print file to %s - %s\n", PRINTERNAME(snum),
			         ippErrorString(cupsLastError())));
        	else
			ret = 0;

		ippDelete(response);
	}
	else
		DEBUG(0,("Unable to print file to `%s' - %s\n", PRINTERNAME(snum),
			 ippErrorString(cupsLastError())));

	httpClose(http);

	if ( ret == 0 )
		unlink(pjob->filename);
	/* else print_job_end will do it for us */

	return (ret);
}
예제 #18
0
void standard_sub_basic(const char *smb_name, char *str,size_t len)
{
	char *p, *s;
	fstring pidstr;
	struct passwd *pass;
	const char *local_machine_name = get_local_machine_name();

	for (s=str; (p=strchr_m(s, '%'));s=p) {
		fstring tmp_str;

		int l = (int)len - (int)(p-str);

		if (l < 0)
			l = 0;
		
		switch (*(p+1)) {
		case 'U' : 
			fstrcpy(tmp_str, smb_name);
			strlower_m(tmp_str);
			string_sub(p,"%U",tmp_str,l);
			break;
		case 'G' :
			fstrcpy(tmp_str, smb_name);
			if ((pass = Get_Pwnam(tmp_str))!=NULL) {
				string_sub(p,"%G",gidtoname(pass->pw_gid),l);
			} else {
				p += 2;
			}
			break;
		case 'D' :
			fstrcpy(tmp_str, current_user_info.domain);
			strupper_m(tmp_str);
			string_sub(p,"%D", tmp_str,l);
			break;
		case 'I' :
			string_sub(p,"%I", client_addr(),l);
			break;
		case 'i' :
			string_sub(p,"%i", client_socket_addr(),l);
			break;
		case 'L' : 
			if (local_machine_name && *local_machine_name)
				string_sub(p,"%L", local_machine_name,l); 
			else {
				pstring temp_name;

				pstrcpy(temp_name, global_myname());
				strlower_m(temp_name);
				string_sub(p,"%L", temp_name,l); 
			}
			break;
		case 'M' :
			string_sub(p,"%M", client_name(),l);
			break;
		case 'R' :
			string_sub(p,"%R", remote_proto,l);
			break;
		case 'T' :
			string_sub(p,"%T", timestring(False),l);
			break;
		case 'a' :
			string_sub(p,"%a", remote_arch,l);
			break;
		case 'd' :
			slprintf(pidstr,sizeof(pidstr)-1, "%d",(int)sys_getpid());
			string_sub(p,"%d", pidstr,l);
			break;
		case 'h' :
			string_sub(p,"%h", myhostname(),l);
			break;
		case 'm' :
			string_sub(p,"%m", get_remote_machine_name(),l);
			break;
		case 'v' :
			string_sub(p,"%v", SAMBA_VERSION_STRING,l);
			break;
		case '$' :
			p += expand_env_var(p,l);
			break; /* Expand environment variables */
		case '\0': 
			p++; 
			break; /* don't run off the end of the string */
			
		default: p+=2; 
			break;
		}
	}
}
예제 #19
0
static int iprint_job_submit(int snum, struct printjob *pjob)
{
	int		ret = 1;		/* Return value */
	http_t		*http = NULL;		/* HTTP connection to server */
	ipp_t		*request = NULL,	/* IPP Request */
			*response = NULL;	/* IPP Response */
	ipp_attribute_t	*attr;		/* Current attribute */
	cups_lang_t	*language = NULL;	/* Default language */
	char		uri[HTTP_MAX_URI]; /* printer-uri attribute */
	char 		*clientname = NULL; 	/* hostname of client for job-originating-host attribute */

	DEBUG(5,("iprint_job_submit(%d, %p (%d))\n", snum, pjob, pjob->sysjob));

       /*
	* Make sure we don't ask for passwords...
	*/

	cupsSetPasswordCB(iprint_passwd_cb);

       /*
	* Try to connect to the server...
	*/

	if ((http = httpConnect(iprint_server(), ippPort())) == NULL) {
		DEBUG(0,("Unable to connect to iPrint server %s - %s\n", 
			 iprint_server(), strerror(errno)));
		goto out;
	}

       /*
	* Build an IPP_PRINT_JOB request, which requires the following
	* attributes:
	*
	*    attributes-charset
	*    attributes-natural-language
	*    printer-uri
	*    requesting-user-name
	*    [document-data]
	*/

	request = ippNew();

	request->request.op.operation_id = IPP_PRINT_JOB;
	request->request.op.request_id   = 1;

	language = cupsLangDefault();

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
	             "attributes-charset", NULL, "utf-8");

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
	             "attributes-natural-language", NULL, language->language);

	slprintf(uri, sizeof(uri) - 1, "ipp://%s/ipp/%s", iprint_server(), PRINTERNAME(snum));

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
	             "printer-uri", NULL, uri);

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
	             NULL, pjob->user);

	clientname = client_name();
	if (strcmp(clientname, "UNKNOWN") == 0) {
		clientname = client_addr();
	}

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
	             "job-originating-host-name", NULL,
	             clientname);

	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-name", NULL,
	             pjob->jobname);

       /*
	* Do the request and get back a response...
	*/

	slprintf(uri, sizeof(uri) - 1, "/ipp/%s", PRINTERNAME(snum));

	if ((response = cupsDoFileRequest(http, request, uri, pjob->filename)) != NULL) {
		if (response->request.status.status_code >= IPP_OK_CONFLICT) {
			DEBUG(0,("Unable to print file to %s - %s\n", PRINTERNAME(snum),
			         ippErrorString(cupsLastError())));
		} else {
			ret = 0;
		}
	} else {
		DEBUG(0,("Unable to print file to `%s' - %s\n", PRINTERNAME(snum),
			 ippErrorString(cupsLastError())));
	}

	if ( ret == 0 )
		unlink(pjob->filename);
	/* else print_job_end will do it for us */

	if ( ret == 0 ) {

		attr = ippFindAttribute(response, "job-id", IPP_TAG_INTEGER);
		if (attr != NULL && attr->group_tag == IPP_TAG_JOB)
		{
			pjob->sysjob = attr->values[0].integer;
		}
	}

 out:
	if (response)
		ippDelete(response);

	if (language)
		cupsLangFree(language);

	if (http)
		httpClose(http);

	return ret;
}
예제 #20
0
/* called when a session is created */
BOOL session_claim(user_struct *vuser)
{
	int i = 0;
	TDB_DATA data;
	struct sockaddr sa;
	struct in_addr *client_ip;
	struct sessionid sessionid;
	uint32 pid = (uint32)sys_getpid();
	TDB_DATA key;		
	fstring keystr;
	char * hostname;
	int tdb_store_flag;  /* If using utmp, we do an inital 'lock hold' store,
				but we don't need this if we are just using the 
				(unique) pid/vuid combination */

	vuser->session_keystr = NULL;

	/* don't register sessions for the guest user - its just too
	   expensive to go through pam session code for browsing etc */
	if (vuser->guest) {
		return True;
	}

	if (!tdb) {
		tdb = tdb_open_log(lock_path("sessionid.tdb"), 0, TDB_CLEAR_IF_FIRST|TDB_DEFAULT, 
			       O_RDWR | O_CREAT, 0644);
		if (!tdb) {
			DEBUG(1,("session_claim: failed to open sessionid tdb\n"));
			return False;
		}
	}

	ZERO_STRUCT(sessionid);

	data.dptr = NULL;
	data.dsize = 0;

	if (lp_utmp()) {
		for (i=1;i<MAX_SESSION_ID;i++) {
			slprintf(keystr, sizeof(keystr)-1, "ID/%d", i);
			key.dptr = keystr;
			key.dsize = strlen(keystr)+1;
			
			if (tdb_store(tdb, key, data, TDB_INSERT) == 0) break;
		}
		
		if (i == MAX_SESSION_ID) {
			DEBUG(1,("session_claim: out of session IDs (max is %d)\n", 
				 MAX_SESSION_ID));
			return False;
		}
		slprintf(sessionid.id_str, sizeof(sessionid.id_str)-1, SESSION_UTMP_TEMPLATE, i);
		tdb_store_flag = TDB_MODIFY;
	} else
	{
		slprintf(keystr, sizeof(keystr)-1, "ID/%lu/%u", 
			 (long unsigned int)sys_getpid(), 
			 vuser->vuid);
		slprintf(sessionid.id_str, sizeof(sessionid.id_str)-1, 
			 SESSION_TEMPLATE, (long unsigned int)sys_getpid(), 
			 vuser->vuid);

		key.dptr = keystr;
		key.dsize = strlen(keystr)+1;
			
		tdb_store_flag = TDB_REPLACE;
	}

	/* If 'hostname lookup' == yes, then do the DNS lookup.  This is
           needed because utmp and PAM both expect DNS names 
	   
	   client_name() handles this case internally.
	*/

	hostname = client_name();
	if (strcmp(hostname, "UNKNOWN") == 0) {
		hostname = client_addr();
	}

	fstrcpy(sessionid.username, vuser->user.unix_name);
	fstrcpy(sessionid.hostname, hostname);
	sessionid.id_num = i;  /* Only valid for utmp sessions */
	sessionid.pid = pid;
	sessionid.uid = vuser->uid;
	sessionid.gid = vuser->gid;
	fstrcpy(sessionid.remote_machine, get_remote_machine_name());
	fstrcpy(sessionid.ip_addr, client_addr());

	client_ip = client_inaddr(&sa);

	if (!smb_pam_claim_session(sessionid.username, sessionid.id_str, sessionid.hostname)) {
		DEBUG(1,("pam_session rejected the session for %s [%s]\n",
				sessionid.username, sessionid.id_str));
		if (tdb_store_flag == TDB_MODIFY) {
			tdb_delete(tdb, key);
		}
		return False;
	}

	data.dptr = (char *)&sessionid;
	data.dsize = sizeof(sessionid);
	if (tdb_store(tdb, key, data, tdb_store_flag) != 0) {
		DEBUG(1,("session_claim: unable to create session id record\n"));
		return False;
	}

	if (lp_utmp()) {
		sys_utmp_claim(sessionid.username, sessionid.hostname, 
			       client_ip,
			       sessionid.id_str, sessionid.id_num);
	}

	vuser->session_keystr = strdup(keystr);
	if (!vuser->session_keystr) {
		DEBUG(0, ("session_claim:  strdup() failed for session_keystr\n"));
		return False;
	}
	return True;
}
예제 #21
0
	sconn->sock = fd;

	/*
	 * Initialize sconn->client_id: If we can't find the client's
	 * name, default to its address.
	 */

	if (sconn->client_id.name != NULL &&
	    sconn->client_id.name != sconn->client_id.addr) {
		talloc_free(discard_const_p(char, sconn->client_id.name));
		sconn->client_id.name = NULL;
	}

	client_addr(fd, sconn->client_id.addr, sizeof(sconn->client_id.addr));

	name = client_name(sconn->sock);
	if (strcmp(name, "UNKNOWN") != 0) {
		name = talloc_strdup(sconn, name);
	} else {
		name = NULL;
	}
	sconn->client_id.name =
		(name != NULL) ? name : sconn->client_id.addr;

	sub_set_socket_ids(sconn->client_id.addr, sconn->client_id.name,
			   client_socket_addr(sconn->sock, addr,
					      sizeof(addr)));
}

struct event_context *smbd_event_context(void)
{
예제 #22
0
int main(int argc, char *argv[])
{
	node_t *Gnode=NULL, *RecNode=NULL, *TmpNode = NULL;
	pid_t  childpid;
	size_t *dim, i, j;
	
	FILE *fp;

	lmint_t sockfd, portno, n, status, ch_stat, *tmpint, *tmpi;

        socklen_t clilen;
        struct sockaddr_in cli_addr;
	lmchar_t *name="Pressure";

	lmint_t nmax, retval;
	lmdouble_t *tmpdf;
	client_fce_struct_t InpPar, *PInpPar;
	opts_t opts, *Popts_1;
	
	struct timespec tim, tim2;
// 	tim.tv_sec = 1;
	tim.tv_sec = 0;
// 	tim.tv_nsec = 300000000L;    /* 0.1 secs */
	tim.tv_nsec = 10000000L;    /* 0.1 secs */

	nmax = 100000;
	PInpPar = &InpPar;
/*
 * get port number
 */
     if (argc < 3) {
       fprintf(stderr,"ERROR, no IPaddress and port number provided\n");
       exit(1);
     }
 	portno = atoi(argv[2]);
/*
 * open socket
 */
		PInpPar->channel_name = name;
		PInpPar->SR_MODE = 'S';
		if ( (PInpPar->mode = get_exchange_channel_mode('A', 'Y')) == -1)
			Error("wrong client mode");
		
		Popts_1 = &opts;
		m3l_set_Send_receive_tcpipsocket(&Popts_1);
	
		if( (sockfd = open_connection_to_server(argv[1], portno, PInpPar, Popts_1)) < 1)
			Error("client_sender: Error when opening socket");
/*
 * open socket - because we use more then just send - receive scenario
 * we need to open socket manualy and used Send_receive function with hostname = NULL, ie. as server
 * portno is then replaced by socket number
 */

	dim = (size_t *) malloc( 1* sizeof(size_t));

	Gnode = client_name("Text from Client1");
/*
 * add pressure array, array has 10 pressure with some values
 */	
	dim[0] = 10;
	if(  (TmpNode = m3l_Mklist("numbers", "D", 1, dim, &Gnode, "/Client_Data", "./", (char *)NULL)) == 0)
			Error("m3l_Mklist");
	tmpdf = (double *)m3l_get_data_pointer(TmpNode);
	for(j=0; j<10; j++)
		tmpdf[j] = j*1.1;


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

 		printf("\n\n--------------------------------    i = %ld\n\n", i);
/*
 * open socket, IP address of server is in argv[1], port number is in portno
 */
		
// 		if(m3l_Cat(Gnode, "--all", "-P", "-L",  "*",   (char *)NULL) != 0)
// 			Error("CatData");

		for(j=0; j<10; j++)
			tmpdf[j] = i*j*1.1;
		
		client_sender(Gnode, sockfd, PInpPar, (opts_t *)NULL, (opts_t *)NULL);


		RecNode = client_receiver(sockfd, PInpPar, (opts_t *)NULL, (opts_t *)NULL);

		
//  		if(m3l_Cat(RecNode, "--all", "-P", "-L",  "*",   (char *)NULL) != 0)
//  			Error("CatData");

		if(m3l_Umount(&RecNode) != 1)
			Perror("m3l_Umount");
		
 	}
	free(dim);
	if(m3l_Umount(&Gnode) != 1)
		Perror("m3l_Umount");
/* 
 * close socket
 */
	if( close(sockfd) == -1)
		Perror("close");
	
 	if ( (fp = fopen("PRESSURE_STAT","w")) == NULL)
		Perror("fopen");
	fprintf(fp, "PRESSURE finished\n");
	fclose(fp);	

     return 0; 
}
예제 #23
0
static int rsync_module(int fd, int i)
{
	int argc=0;
	char *argv[MAX_ARGS];
	char **argp;
	char line[MAXPATHLEN];
	uid_t uid = (uid_t)-2;
	gid_t gid = (gid_t)-2;
	char *p;
	char *addr = client_addr(fd);
	char *host = client_name(fd);
	char *name = lp_name(i);
	int use_chroot = lp_use_chroot(i);
	int start_glob=0;
	int ret;
	char *request=NULL;
	extern int am_sender;
	extern int remote_version;
	extern int am_root;

	if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
		rprintf(FERROR,"rsync denied on module %s from %s (%s)\n",
			name, client_name(fd), client_addr(fd));
		io_printf(fd,"@ERROR: access denied to %s from %s (%s)\n",
			  name, client_name(fd), client_addr(fd));
		return -1;
	}

	if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
		if (errno) {
			rprintf(FERROR,"failed to open lock file %s : %s\n",
				lp_lock_file(i), strerror(errno));
			io_printf(fd,"@ERROR: failed to open lock file %s : %s\n",
				  lp_lock_file(i), strerror(errno));
		} else {
			rprintf(FERROR,"max connections (%d) reached\n",
				lp_max_connections(i));
			io_printf(fd,"@ERROR: max connections (%d) reached - try again later\n", lp_max_connections(i));
		}
		return -1;
	}

	
	auth_user = auth_server(fd, i, addr, "@RSYNCD: AUTHREQD ");

	if (!auth_user) {
		rprintf(FERROR,"auth failed on module %s from %s (%s)\n",
			name, client_name(fd), client_addr(fd));
		io_printf(fd,"@ERROR: auth failed on module %s\n",name);
		return -1;		
	}

	module_id = i;

	if (lp_read_only(i))
		read_only = 1;

	am_root = (getuid() == 0);

	if (am_root) {
		p = lp_uid(i);
		if (!name_to_uid(p, &uid)) {
			if (!isdigit(*p)) {
				rprintf(FERROR,"Invalid uid %s\n", p);
				io_printf(fd,"@ERROR: invalid uid\n");
				return -1;
			} 
			uid = atoi(p);
		}

		p = lp_gid(i);
		if (!name_to_gid(p, &gid)) {
			if (!isdigit(*p)) {
				rprintf(FERROR,"Invalid gid %s\n", p);
				io_printf(fd,"@ERROR: invalid gid\n");
				return -1;
			} 
			gid = atoi(p);
		}
	}

	p = lp_include_from(i);
	add_exclude_file(p, 1, 1);

	p = lp_include(i);
	add_include_line(p);

	p = lp_exclude_from(i);
	add_exclude_file(p, 1, 0);

	p = lp_exclude(i);
	add_exclude_line(p);

	log_open();

	if (use_chroot) {
		if (chroot(lp_path(i))) {
			rprintf(FERROR,"chroot %s failed\n", lp_path(i));
			io_printf(fd,"@ERROR: chroot failed\n");
			return -1;
		}

		if (!push_dir("/", 0)) {
			rprintf(FERROR,"chdir %s failed\n", lp_path(i));
			io_printf(fd,"@ERROR: chdir failed\n");
			return -1;
		}

	} else {
		if (!push_dir(lp_path(i), 0)) {
			rprintf(FERROR,"chdir %s failed\n", lp_path(i));
			io_printf(fd,"@ERROR: chdir failed\n");
			return -1;
		}
	}

	if (am_root) {
		if (setgid(gid)) {
			rprintf(FERROR,"setgid %d failed\n", gid);
			io_printf(fd,"@ERROR: setgid failed\n");
			return -1;
		}

		if (setuid(uid)) {
			rprintf(FERROR,"setuid %d failed\n", uid);
			io_printf(fd,"@ERROR: setuid failed\n");
			return -1;
		}

		am_root = (getuid() == 0);
	}

	io_printf(fd,"@RSYNCD: OK\n");

	argv[argc++] = "rsyncd";

	while (1) {
		if (!read_line(fd, line, sizeof(line)-1)) {
			return -1;
		}

		if (!*line) break;

		p = line;

		argv[argc] = strdup(p);
		if (!argv[argc]) {
			return -1;
		}

		if (start_glob) {
			if (start_glob == 1) {
				request = strdup(p);
				start_glob++;
			}
			glob_expand(name, argv, &argc, MAX_ARGS, !use_chroot);
		} else {
			argc++;
		}

		if (strcmp(line,".") == 0) {
			start_glob = 1;
		}

		if (argc == MAX_ARGS) {
			return -1;
		}
	}

	if (!use_chroot) {
		/*
		 * Note that this is applied to all parameters, whether or not
		 *    they are filenames, but no other legal parameters contain
		 *    the forms that need to be sanitized so it doesn't hurt;
		 *    it is not known at this point which parameters are files
		 *    and which aren't.
		 */
		for (i = 1; i < argc; i++) {
			sanitize_path(argv[i]);
		}
	}

	ret = parse_arguments(argc, argv, 0);

	if (request) {
		if (*auth_user) {
			rprintf(FINFO,"rsync %s %s from %s@%s (%s)\n",
				am_sender?"on":"to",
				request, auth_user, host, addr);
		} else {
			rprintf(FINFO,"rsync %s %s from %s (%s)\n",
				am_sender?"on":"to",
				request, host, addr);
		}
		free(request);
	}

#if !TRIDGE
	/* don't allow the logs to be flooded too fast */
	if (verbose > 1) verbose = 1;
#endif

	argc -= optind;
	argp = argv + optind;
	optind = 0;

	if (remote_version > 17 && am_sender)
		io_start_multiplex_out(fd);

	if (!ret) {
		option_error();
	}

	if (lp_timeout(i)) {
		extern int io_timeout;
		io_timeout = lp_timeout(i);
	}

	start_server(fd, fd, argc, argp);

	return 0;
}
예제 #24
0
static void subscribe_callback(pa_core *c, pa_subscription_event_type_t t, uint32_t idx, void *userdata) {
    struct userdata *u =  userdata;
    pa_sink_input *si = NULL;
    pa_source_output *so = NULL;
    struct rule *r;
    char *name;

    pa_assert(c);
    pa_assert(u);

    if (t != (PA_SUBSCRIPTION_EVENT_SINK_INPUT|PA_SUBSCRIPTION_EVENT_NEW) &&
        t != (PA_SUBSCRIPTION_EVENT_SINK_INPUT|PA_SUBSCRIPTION_EVENT_CHANGE) &&
        t != (PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT|PA_SUBSCRIPTION_EVENT_NEW) &&
        t != (PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT|PA_SUBSCRIPTION_EVENT_CHANGE))
        return;

    if ((t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) == PA_SUBSCRIPTION_EVENT_SINK_INPUT) {
        if (!(si = pa_idxset_get_by_index(c->sink_inputs, idx)))
            return;

        if (!si->client || !(name = client_name(si->client)))
            return;
    } else {
        pa_assert((t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) == PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT);

        if (!(so = pa_idxset_get_by_index(c->source_outputs, idx)))
            return;

        if (!so->client || !(name = client_name(so->client)))
            return;
    }

    if ((r = pa_hashmap_get(u->hashmap, name))) {
        pa_xfree(name);

        if (si) {

            if (!r->volume_is_set || !pa_cvolume_equal(pa_sink_input_get_volume(si), &r->volume)) {
                pa_log_info("Saving volume for <%s>", r->name);
                r->volume = *pa_sink_input_get_volume(si);
                r->volume_is_set = TRUE;
                u->modified = TRUE;
            }

            if (!r->sink || strcmp(si->sink->name, r->sink) != 0) {
                pa_log_info("Saving sink for <%s>", r->name);
                pa_xfree(r->sink);
                r->sink = pa_xstrdup(si->sink->name);
                u->modified = TRUE;
            }
        } else {
            pa_assert(so);

            if (!r->source || strcmp(so->source->name, r->source) != 0) {
                pa_log_info("Saving source for <%s>", r->name);
                pa_xfree(r->source);
                r->source = pa_xstrdup(so->source->name);
                u->modified = TRUE;
            }
        }

    } else {
        pa_log_info("Creating new entry for <%s>", name);

        r = pa_xnew(struct rule, 1);
        r->name = name;

        if (si) {
            r->volume = *pa_sink_input_get_volume(si);
            r->volume_is_set = TRUE;
            r->sink = pa_xstrdup(si->sink->name);
            r->source = NULL;
        } else {
            pa_assert(so);
            r->volume_is_set = FALSE;
            r->sink = NULL;
            r->source = pa_xstrdup(so->source->name);
        }

        pa_hashmap_put(u->hashmap, r->name, r);
        u->modified = TRUE;
    }

    if (u->modified && !u->save_time_event) {
        struct timeval tv;
        pa_gettimeofday(&tv);
        tv.tv_sec += SAVE_INTERVAL;
        u->save_time_event = u->core->mainloop->time_new(u->core->mainloop, &tv, save_time_callback, u);
    }
}
예제 #25
0
/* A generic logging routine for send/recv, with parameter substitiution. */
static void log_formatted(enum logcode code, const char *format, const char *op,
			  struct file_struct *file, const char *fname, int iflags,
			  const char *hlink)
{
	char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
	char *p, *s, *c;
	const char *n;
	size_t len, total;
	int64 b;

	*fmt = '%';

	/* We expand % codes one by one in place in buf.  We don't
	 * copy in the terminating null of the inserted strings, but
	 * rather keep going until we reach the null of the format. */
	total = strlcpy(buf, format, sizeof buf);
	if (total > MAXPATHLEN) {
		rprintf(FERROR, "log-format string is WAY too long!\n");
		exit_cleanup(RERR_MESSAGEIO);
	}
	buf[total++] = '\n';
	buf[total] = '\0';

	for (p = buf; (p = strchr(p, '%')) != NULL; ) {
		int humanize = 0;
		s = p++;
		c = fmt + 1;
		while (*p == '\'') {
			humanize++;
			p++;
		}
		if (*p == '-')
			*c++ = *p++;
		while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8)
			*c++ = *p++;
		while (*p == '\'') {
			humanize++;
			p++;
		}
		if (!*p)
			break;
		*c = '\0';
		n = NULL;

		/* Note for %h and %a: it doesn't matter what fd we pass to
		 * client_{name,addr} because rsync_module will already have
		 * forced the answer to be cached (assuming, of course, for %h
		 * that lp_reverse_lookup(module_id) is true). */
		switch (*p) {
		case 'h':
			if (am_daemon) {
				n = lp_reverse_lookup(module_id)
				  ? client_name(0) : undetermined_hostname;
			}
			break;
		case 'a':
			if (am_daemon)
				n = client_addr(0);
			break;
		case 'l':
			strlcat(fmt, "s", sizeof fmt);
			snprintf(buf2, sizeof buf2, fmt,
				 do_big_num(F_LENGTH(file), humanize, NULL));
			n = buf2;
			break;
		case 'U':
			strlcat(fmt, "u", sizeof fmt);
			snprintf(buf2, sizeof buf2, fmt,
				 uid_ndx ? F_OWNER(file) : 0);
			n = buf2;
			break;
		case 'G':
			if (!gid_ndx || file->flags & FLAG_SKIP_GROUP)
				n = "DEFAULT";
			else {
				strlcat(fmt, "u", sizeof fmt);
				snprintf(buf2, sizeof buf2, fmt,
					 F_GROUP(file));
				n = buf2;
			}
			break;
		case 'p':
			strlcat(fmt, "d", sizeof fmt);
			snprintf(buf2, sizeof buf2, fmt, (int)getpid());
			n = buf2;
			break;
		case 'M':
			n = c = timestring(file->modtime);
			while ((c = strchr(c, ' ')) != NULL)
				*c = '-';
			break;
		case 'B':
			c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1;
			permstring(c, file->mode);
			n = c + 1; /* skip the type char */
			break;
		case 'o':
			n = op;
			break;
		case 'f':
			if (fname) {
				c = f_name_buf();
				strlcpy(c, fname, MAXPATHLEN);
			} else
				c = f_name(file, NULL);
			if (am_sender && F_PATHNAME(file)) {
				pathjoin(buf2, sizeof buf2,
					 F_PATHNAME(file), c);
				clean_fname(buf2, 0);
				if (fmt[1]) {
					strlcpy(c, buf2, MAXPATHLEN);
					n = c;
				} else
					n = buf2;
			} else if (am_daemon && *c != '/') {
				pathjoin(buf2, sizeof buf2,
					 curr_dir + module_dirlen, c);
				clean_fname(buf2, 0);
				if (fmt[1]) {
					strlcpy(c, buf2, MAXPATHLEN);
					n = c;
				} else
					n = buf2;
			} else {
				clean_fname(c, 0);
				n = c;
			}
			if (*n == '/')
				n++;
			break;
		case 'n':
			if (fname) {
				c = f_name_buf();
				strlcpy(c, fname, MAXPATHLEN);
			} else
				c = f_name(file, NULL);
			if (S_ISDIR(file->mode))
				strlcat(c, "/", MAXPATHLEN);
			n = c;
			break;
		case 'L':
			if (hlink && *hlink) {
				n = hlink;
				strlcpy(buf2, " => ", sizeof buf2);
			} else if (S_ISLNK(file->mode) && !fname) {
				n = F_SYMLINK(file);
				strlcpy(buf2, " -> ", sizeof buf2);
			} else {
				n = "";
				if (!fmt[1])
					break;
				strlcpy(buf2, "    ", sizeof buf2);
			}
			strlcat(fmt, "s", sizeof fmt);
			snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
			n = buf2;
			break;
		case 'm':
			n = lp_name(module_id);
			break;
		case 't':
			n = timestring(time(NULL));
			break;
		case 'P':
			n = full_module_path;
			break;
		case 'u':
			n = auth_user;
			break;
		case 'b':
		case 'c':
			if (!(iflags & ITEM_TRANSFER))
				b = 0;
			else if ((!!am_sender) ^ (*p == 'c'))
				b = total_data_written - initial_data_written;
			else
				b = total_data_read - initial_data_read;
			strlcat(fmt, "s", sizeof fmt);
			snprintf(buf2, sizeof buf2, fmt,
				 do_big_num(b, humanize, NULL));
			n = buf2;
			break;
		case 'C':
			n = NULL;
			if (S_ISREG(file->mode)) {
				if (always_checksum && canonical_checksum(checksum_type))
					n = sum_as_hex(checksum_type, F_SUM(file));
				else if (iflags & ITEM_TRANSFER && canonical_checksum(xfersum_type))
					n = sum_as_hex(xfersum_type, sender_file_sum);
			}
			if (!n) {
				int checksum_len = csum_len_for_type(always_checksum ? checksum_type : xfersum_type);
				memset(buf2, ' ', checksum_len*2);
				buf2[checksum_len*2] = '\0';
				n = buf2;
			}
			break;
		case 'i':
			if (iflags & ITEM_DELETED) {
				n = "*deleting  ";
				break;
			}
			n  = c = buf2 + MAXPATHLEN - 32;
			c[0] = iflags & ITEM_LOCAL_CHANGE
			      ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c'
			     : !(iflags & ITEM_TRANSFER) ? '.'
			     : !local_server && *op == 's' ? '<' : '>';
			if (S_ISLNK(file->mode)) {
				c[1] = 'L';
				c[3] = '.';
				c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
				     : !preserve_times || !receiver_symlink_times
				    || (iflags & ITEM_REPORT_TIMEFAIL) ? 'T' : 't';
			} else {
				c[1] = S_ISDIR(file->mode) ? 'd'
				     : IS_SPECIAL(file->mode) ? 'S'
				     : IS_DEVICE(file->mode) ? 'D' : 'f';
				c[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
				c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
				     : !preserve_times ? 'T' : 't';
			}
			c[2] = !(iflags & ITEM_REPORT_CHANGE) ? '.' : 'c';
			c[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
			c[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
			c[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
			c[8] = !(iflags & ITEM_REPORT_ATIME) ? '.' : 'u';
			c[9] = !(iflags & ITEM_REPORT_ACL) ? '.' : 'a';
			c[10] = !(iflags & ITEM_REPORT_XATTR) ? '.' : 'x';
			c[11] = '\0';

			if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
				char ch = iflags & ITEM_IS_NEW ? '+' : '?';
				int i;
				for (i = 2; c[i]; i++)
					c[i] = ch;
			} else if (c[0] == '.' || c[0] == 'h' || c[0] == 'c') {
				int i;
				for (i = 2; c[i]; i++) {
					if (c[i] != '.')
						break;
				}
				if (!c[i]) {
					for (i = 2; c[i]; i++)
						c[i] = ' ';
				}
			}
			break;
		}

		/* "n" is the string to be inserted in place of this % code. */
		if (!n)
			continue;
		if (n != buf2 && fmt[1]) {
			strlcat(fmt, "s", sizeof fmt);
			snprintf(buf2, sizeof buf2, fmt, n);
			n = buf2;
		}
		len = strlen(n);

		/* Subtract the length of the escape from the string's size. */
		total -= p - s + 1;

		if (len + total >= (size_t)sizeof buf) {
			rprintf(FERROR,
				"buffer overflow expanding %%%c -- exiting\n",
				p[0]);
			exit_cleanup(RERR_MESSAGEIO);
		}

		/* Shuffle the rest of the string along to make space for n */
		if (len != (size_t)(p - s + 1))
			memmove(s + len, p + 1, total - (s - buf) + 1);
		total += len;

		/* Insert the contents of string "n", but NOT its null. */
		if (len)
			memcpy(s, n, len);

		/* Skip over inserted string; continue looking */
		p = s + len;
	}

	rwrite(code, buf, total, 0);
}
예제 #26
0
/*
 *  Refresh a request, by using proxy_retry_delay, cleanup_delay,
 *  max_request_time, etc.
 *
 *  When walking over the request list, all of the per-request
 *  magic is done here.
 */
static int refresh_request(REQUEST *request, void *data)
{
	rl_walk_t *info = (rl_walk_t *) data;
	time_t difference;
	child_pid_t child_pid;

	rad_assert(request->magic == REQUEST_MAGIC);

	/*
	 *  If the request is marked as a delayed reject, AND it's
	 *  time to send the reject, then do so now.
	 */
	if (request->finished &&
	    ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) != 0)) {
		rad_assert(request->child_pid == NO_SUCH_CHILD_PID);

		difference = info->now - request->timestamp;
		if (difference >= (time_t) mainconfig.reject_delay) {

			/*
			 *  Clear the 'delayed reject' bit, so that we
			 *  don't do this again.
			 */
			request->options &= ~RAD_REQUEST_OPTION_DELAYED_REJECT;
			rad_send(request->reply, request->packet,
				 request->secret);
		}
	}

	/*
	 *  If the request has finished processing, AND it's child has
	 *  been cleaned up, AND it's time to clean up the request,
	 *  OR, it's an accounting request.  THEN, go delete it.
	 *
	 *  If this is a request which had the "don't cache" option
	 *  set, then delete it immediately, as it CANNOT have a
	 *  duplicate.
	 */
	if (request->finished &&
	    ((request->timestamp + mainconfig.cleanup_delay <= info->now) ||
	     ((request->options & RAD_REQUEST_OPTION_DONT_CACHE) != 0))) {
		rad_assert(request->child_pid == NO_SUCH_CHILD_PID);

		/*
		 *  Request completed, delete it, and unlink it
		 *  from the currently 'alive' list of requests.
		 */
		DEBUG2("Cleaning up request %d ID %d with timestamp %08lx",
				request->number, request->packet->id,
				(unsigned long) request->timestamp);

		/*
		 *  Delete the request.
		 */
		rl_delete(request);
		return RL_WALK_CONTINUE;
	}

	/*
	 *  Maybe the child process handling the request has hung:
	 *  kill it, and continue.
	 */
	if ((request->timestamp + mainconfig.max_request_time) <= info->now) {
		int number;

		child_pid = request->child_pid;
		number = request->number;

		/*
		 *	There MUST be a RAD_PACKET reply.
		 */
		rad_assert(request->reply != NULL);

		/*
		 *	If we've tried to proxy the request, and
		 *	the proxy server hasn't responded, then
		 *	we send a REJECT back to the caller.
		 *
		 *	For safety, we assert that there is no child
		 *	handling the request.  If the assertion fails,
		 *	it means that we've sent a proxied request to
		 *	the home server, and the child thread is still
		 *	sitting on the request!
		 */
		if (request->proxy && !request->proxy_reply) {
			rad_assert(request->child_pid == NO_SUCH_CHILD_PID);

			radlog(L_ERR, "Rejecting request %d due to lack of any response from home server %s:%d",
			       request->number,
			       client_name(request->packet->src_ipaddr),
			       request->packet->src_port);
			request_reject(request);
			request->finished = TRUE;
			return RL_WALK_CONTINUE;
		}

		if (mainconfig.kill_unresponsive_children) {
			if (child_pid != NO_SUCH_CHILD_PID) {
				/*
				 *  This request seems to have hung
				 *   - kill it
				 */
#ifdef HAVE_PTHREAD_H
				radlog(L_ERR, "Killing unresponsive thread for request %d",
				       request->number);
				pthread_cancel(child_pid);
#endif
			} /* else no proxy reply, quietly fail */

			/*
			 *	Maybe we haven't killed it.  In that
			 *	case, print a warning.
			 */
		} else if ((child_pid != NO_SUCH_CHILD_PID) &&
			   ((request->options & RAD_REQUEST_OPTION_LOGGED_CHILD) == 0)) {
			radlog(L_ERR, "WARNING: Unresponsive child (id %lu) for request %d",
			       (unsigned long)child_pid, number);

			/*
			 *  Set the option that we've sent a log message,
			 *  so that we don't send more than one message
			 *  per request.
			 */
			request->options |= RAD_REQUEST_OPTION_LOGGED_CHILD;
		}

		/*
		 *  Send a reject message for the request, mark it
		 *  finished, and forget about the child.
		 */
		request_reject(request);
		request->child_pid = NO_SUCH_CHILD_PID;
		if (mainconfig.kill_unresponsive_children)
			request->finished = TRUE;
		return RL_WALK_CONTINUE;
	} /* the request has been in the queue for too long */

	/*
	 *  If the request is still being processed, then due to the
	 *  above check, it's still within it's time limit.  In that
	 *  case, don't do anything.
	 */
	if (request->child_pid != NO_SUCH_CHILD_PID) {
		return RL_WALK_CONTINUE;
	}

	/*
	 *  The request is finished.
	 */
	if (request->finished) goto setup_timeout;

	/*
	 *  We're not proxying requests at all.
	 */
	if (!mainconfig.proxy_requests) goto setup_timeout;

	/*
	 *  We're proxying synchronously, so we don't retry it here.
	 *  Some other code takes care of retrying the proxy requests.
	 */
	if (mainconfig.proxy_synchronous) goto setup_timeout;

	/*
	 *  The proxy retry delay is zero, meaning don't retry.
	 */
	if (mainconfig.proxy_retry_delay == 0) goto setup_timeout;

	/*
	 *  There is no proxied request for this packet, so there's
	 *  no proxy retries.
	 */
	if (!request->proxy) goto setup_timeout;

	/*
	 *  We've already seen the proxy reply, so we don't need
	 *  to send another proxy request.
	 */
	if (request->proxy_reply) goto setup_timeout;

	/*
	 *  It's not yet time to re-send this proxied request.
	 */
	if (request->proxy_next_try > info->now) goto setup_timeout;

	/*
	 *  If the proxy retry count is zero, then
	 *  we've sent the last try, and have NOT received
	 *  a reply from the end server.  In that case,
	 *  we don't bother trying again, but just mark
	 *  the request as finished, and go to the next one.
	 */
	if (request->proxy_try_count == 0) {
		rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
		request_reject(request);
		realm_disable(request->proxy->dst_ipaddr,request->proxy->dst_port);
		request->finished = TRUE;
		goto setup_timeout;
	}

	/*
	 *  We're trying one more time, so count down
	 *  the tries, and set the next try time.
	 */
	request->proxy_try_count--;
	request->proxy_next_try = info->now + mainconfig.proxy_retry_delay;

	/* Fix up Acct-Delay-Time */
	if (request->proxy->code == PW_ACCOUNTING_REQUEST) {
		VALUE_PAIR *delaypair;
		delaypair = pairfind(request->proxy->vps, PW_ACCT_DELAY_TIME);

		if (!delaypair) {
			delaypair = paircreate(PW_ACCT_DELAY_TIME, PW_TYPE_INTEGER);
			if (!delaypair) {
				radlog(L_ERR|L_CONS, "no memory");
				exit(1);
			}
			pairadd(&request->proxy->vps, delaypair);
		}
		delaypair->lvalue = info->now - request->proxy->timestamp;

		/* Must recompile the valuepairs to wire format */
		free(request->proxy->data);
		request->proxy->data = NULL;
	} /* proxy accounting request */

	/*
	 *  Assert that we have NOT seen the proxy reply yet.
	 *
	 *  If we HAVE seen it, then we SHOULD NOT be bugging the
	 *  home server!
	 */
	rad_assert(request->proxy_reply == NULL);

	/*
	 *  Send the proxy packet.
	 */
	request->proxy_outstanding++;
	rad_send(request->proxy, NULL, request->proxysecret);

setup_timeout:
	/*
	 *  Don't do more long-term checks, if we've got to wake
	 *  up now.
	 */
	if (info->smallest == 0) {
		return RL_WALK_CONTINUE;
	}

	/*
	 *  The request is finished.  Wake up when it's time to
	 *  clean it up.
	 */
	if (request->finished) {
		difference = (request->timestamp + mainconfig.cleanup_delay) - info->now;

		/*
		 *  If the request is marked up to be rejected later,
		 *  then wake up later.
		 */
		if ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) != 0) {
			if (difference >= (time_t) mainconfig.reject_delay) {
				difference = (time_t) mainconfig.reject_delay;
			}
		}

	} else if (request->proxy && !request->proxy_reply) {
		/*
		 *  The request is NOT finished, but there is an
		 *  outstanding proxy request, with no matching
		 *  proxy reply.
		 *
		 *  Wake up when it's time to re-send
		 *  the proxy request.
		 *
		 *  But in synchronous proxy, we don't retry but we update
		 *  the next retry time as NAS has not resent the request
		 *  in the given retry window.
		 */
		if (mainconfig.proxy_synchronous) {
			/*
			 *	If the retry_delay * count has passed,
			 *	then mark the realm dead.
			 */
			if (info->now > (request->timestamp + (mainconfig.proxy_retry_delay * mainconfig.proxy_retry_count))) {
				rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
				request_reject(request);
				
				realm_disable(request->proxy->dst_ipaddr,
					      request->proxy->dst_port);
				request->finished = TRUE;
				goto setup_timeout;
			}
			request->proxy_next_try = info->now + mainconfig.proxy_retry_delay;
		}
		difference = request->proxy_next_try - info->now;
	} else {
		/*
		 *  The request is NOT finished.
		 *
		 *  Wake up when it's time to kill the errant
		 *  thread/process.
		 */
		difference = (request->timestamp + mainconfig.max_request_time) - info->now;
	}

	/*
	 *  If the server is CPU starved, then we CAN miss a time
	 *  for servicing requests.  In which case the 'difference'
	 *  value will be negative.  select() doesn't like that,
	 *  so we fix it.
	 */
	if (difference < 0) {
		difference = 0;
	}

	/*
	 *  Update the 'smallest' time.
	 */
	if ((info->smallest < 0) ||
		(difference < info->smallest)) {
		info->smallest = difference;
	}

	return RL_WALK_CONTINUE;
}