/**
 * performs authentication
 * @param ptr authentication structure
 * @return integer 1 on success, otherwise 0
 */
int authenticate (struct auth *ptr) {
	char write_buf[GEN_BUF_SIZE];	/** socket fd write buffer */
	char read_buf[GEN_BUF_SIZE];	/** socket fd read buffer */
	FILE *sock = NULL;
	char srv_code[4];
	int result = 0;
	
	/** connect to server */
	if ((sock = srv_connect()) == NULL)
		return 0; 

	/** format authentication string */
	snprintf(
		write_buf,
		sizeof(write_buf),
		"username=%s\npassword=%s\ncommon_name=%s\nhost=%s\nport=%d\n\n",
		ptr->username,
		ptr->password,
		ptr->common_name,
		ptr->untrusted_ip,
		ptr->untrusted_port
	);

	/** send it to server and flush buffers */
	fprintf(sock, "%s", write_buf);
	fflush(sock);

	/* read response from server */
	if (! fgets(read_buf, sizeof(read_buf), sock)) {
		log_msg("No response read from authentication server: %s (errno %d)", strerror(errno), errno);
		goto outta_func;
	}
	else if (strlen(read_buf) < 3) {
		log_msg("Invalid response from server: %s", read_buf);
		goto outta_func;
	}

	/** chop result code and message */
	memset(srv_code, '\0', sizeof(srv_code));
	chomp(read_buf);
	strncpy(srv_code, read_buf, 2);

	if (strcasecmp(srv_code, "OK") != 0)
		log_msg("Authentication FAILED for user '%s': %s", ptr->username, read_buf);
	else {
		log_msg("Authentication SUCCEEDED for user '%s'", ptr->username);
		result = 1;
	}

	outta_func:

	/* close socket */
	srv_disconnect(sock);

	return result;
}
Exemplo n.º 2
0
int main(int argc, char *argv[])
{
	int opt;
	char *username = NULL;
	char *msg = NULL;
	char *host = NULL;
	int port = 0;
	int index = 0;

        if (argc < 3) {
                exit(1);
        }

	struct option long_opts[] = {
		{ "username", 	required_argument, 0, 'u' },
		{ "message", 	required_argument, 0, 'm' },
		{ "server", 	required_argument, 0, 's' },
		{ "port", 	required_argument, 0, 'p' },
		{ 0,		0,		   0,  0  }
	};

	while ((opt = getopt_long(argc, argv, "u:m:s:p:", long_opts, &index)) != -1) {
		switch (opt) {
		case 'u':
			username = malloc(strlen(optarg)+1);
			strcpy(username, optarg);
			break;
		case 'm':
			msg = malloc(strlen(optarg)+1);
			strcpy(msg, optarg);
			break;
		case 's':
			host = malloc(strlen(optarg)+1);
			strcpy(host, optarg);
			break;
		case 'p':
			port = atoi(optarg);
			break;
		default:
			print_usage();
		}
	}

	/*if (username != NULL)
		printf("%s\n", username);
	if (msg != NULL)
		printf("%s\n", msg);*/

	if (host == NULL)
		print_usage();

        srv_connect(host, port, username, msg);

        return 0;
}
Exemplo n.º 3
0
Arquivo: core.c Projeto: Learath2/sBNC
int core_run(void)
{
	int s_server = 0, s_listener = 0;
	bool running = true;

	struct pollfd fds[MAX_SOCKETS];

	store_init();
	net_init();

	state_init();

	if((s_server = srv_init()) < 0)
		return EXIT_FAILURE;

	if(srv_connect() == -1){
		ERR("srv_connect() failed. Exiting...");
		return EXIT_FAILURE;
	}

	if((s_listener = clt_init()) == -1){
		ERR("clt_init() failed. Exiting...");
		return EXIT_FAILURE;
	}

	memset(fds, 0 , sizeof(fds));

	net_poll_add(s_server, POLLIN);
	net_poll_add_listener(s_listener, POLLIN);

	while(running){
		net_poll(POLLTIMEOUT);
		proc_tick();

		for(int i = 0; i < net_nfds(); i++){
			while(net_socket_avail(i)){
				char msg[513] = "";
				net_socket_msg(i, msg, sizeof msg);
				proc_proc(i, msg);
			}
		}

		while(proc_wqueue_length()){
			wqueue_entry_t ent = proc_wqueue_head();
			net_socket_write(ENT_GET(ent, target), ENT_GET(ent, data), ENT_GET(ent, datasz));
			proc_wqueue_next();
		}
	}

	return EXIT_SUCCESS;
}
int fill_mem_obj(request *rq,struct mem_obj *obj,struct mem_obj *old_obj)
{
//	struct	buff		*to_server_request = NULL;
    char *answer=NULL;
    char *fake_header;
    head_info m_head;
    int fake_header_len=0;
    int r=CONNECT_ERR;
    char mk1123buff[50];
    ERRBUF ;
    memset(&m_head,0,sizeof(m_head));
    if(srv_connect(rq)<=0)
        goto error;
    /*
    to_server_request = alloc_buff(4*CHUNK_SIZE);
    if ( !to_server_request ) {
    //	change_state(obj, OBJ_READY);
    	obj->flags |= FLAG_DEAD;
    	goto error;
    }
    */
//	stored_obj(NULL);
//	printf("rq->if_modified_since=%d,obj->times.last_modified=%d\n",rq->if_modified_since,old_obj->times.last_modified);
    if(old_obj && !TEST(rq->flags,RQ_HAS_IF_MOD_SINCE)) {
        if(old_obj->times.last_modified) {
            if (!mk1123time(old_obj->times.last_modified, mk1123buff, sizeof(mk1123buff)) ) {
                klog(ERR_LOG,"cann't mk1123time obj obj->times.date=%d.\n",old_obj->times.last_modified);
                goto error;
            }
        } else {
            if (!mk1123time(obj->created, mk1123buff, sizeof(mk1123buff)) ) {
                klog(ERR_LOG,"cann't mk1123time obj created=%d.\n",old_obj->created);
                goto error;
            }
        }
        fake_header_len=19+sizeof(mk1123buff)+4;
        fake_header = (char *)malloc(fake_header_len);
        if ( !fake_header ) {
            goto error;
            //error	goto validate_err;
        }
        //	printf("fake_header=%s\n",fake_header);
        memset(fake_header,0,fake_header_len);
        snprintf(fake_header,fake_header_len-1, "If-Modified-Since: %s\r\n", mk1123buff);
        answer=build_direct_request("GET", &rq->url, fake_header, rq, 0);
        free(fake_header);
        //	printf("client have no if-modified-since.\n");
    } else {
        answer=build_direct_request("GET",&rq->url,NULL,rq,0);//连接远程主机
    }
//	printf("answer=%s\n",answer);

    if ( !answer ) {
        klog(ERR_LOG,"no mem to alloc.\n");
        goto error;
    }
    /*
    if ( attach_data(answer, strlen(answer), to_server_request) ) {
    	free_container(to_server_request);
    	goto error;
    }
    if(answer){
    	free(answer);
    	answer = NULL;
    }
    */

    r = rq->client->send(answer);
//	free(answer);
//   free_container(to_server_request); to_server_request = NULL;
    //	printf("send data to remote is:%s",to_server_request->data);
    if ( r <=0 ) {//send error
        say_bad_request("Can't send","",
                        ERR_TRANSFER, rq);
        //	printf("cann't send to server.\n");
        //printf("errno=%d\n",ERRNO);
        goto error;
    }
    r=load_head(rq,obj,m_head);
    switch(r) {
    case HEAD_OK:
        if(load_body(rq,obj)<=0) {
            //printf("load body failed.\n");
            r=CONNECT_ERR;
            goto error;
        }
        goto done;
    case CONNECT_ERR:
        //printf("load head failed.\n");
        goto error;
    case HEAD_NOT_MODIFIED:
        if(old_obj && !TEST(rq->flags,RQ_HAS_IF_MOD_SINCE)) {
            goto error;
        } else {
            if(rq->server->send(m_head.head,m_head.len)<0)
                goto error;
        }
        //	printf("%s\n",m_head.head);
        break;

    default:
//		printf("obj->content_length=%d,path=%s\n",obj->content_length,obj->url.path);
        if(m_head.head) {
            if(rq->server->send(m_head.head,m_head.len)<0)
                goto error;
            if(create_select_pipe(rq->server,rq->client,conf.time_out[HTTP],0,-1)==-2)
                r=1;
        }
    }
error:
    IF_FREE(answer);
    IF_FREE(m_head.head);
    rq->client->close();
    destroy_obj(obj,0);
    return r;
done:
    IF_FREE(answer);
    IF_FREE(m_head.head);
    rq->client->close();
    if(!old_obj)
        stored_obj(obj);
    return r;
};
int send_not_cached(int so, struct request *rq, char *headers)
{
//	int			server_so = -1, r, received = 0, pass=0;, to_write;
    char			*answer = NULL;
//	struct	url		*url = &rq->url;
    char			*meth;
    int r;
//	int			have_code = 0;
//	unsigned int		sent = 0;
//	int			header_size = 0;
//	int			recode_request = FALSE, recode_answer = FALSE;
//	char			*table = NULL;
    ERRBUF ;
    int ret=CONNECT_ERR;

    //int client_left_recv=rq->content_length;
    if ( rq->meth == METH_GET ) meth="GET";
    else if ( rq->meth == METH_PUT ) meth="PUT";
    else if ( rq->meth == METH_POST ) meth="POST";
    else if ( rq->meth == METH_TRACE ) meth="TRACE";
    else if ( rq->meth == METH_HEAD ) meth="HEAD";
    else if ( rq->meth == METH_OPTIONS ) meth="OPTIONS";
    else if ( rq->meth == METH_PROPFIND ) meth="PROPFIND";
    else if ( rq->meth == METH_PROPPATCH ) meth="PROPPATCH";
    else if ( rq->meth == METH_DELETE ) meth="DELETE";
    else if ( rq->meth == METH_MKCOL ) meth="MKCOL";
    else if ( rq->meth == METH_COPY ) meth="COPY";
    else if ( rq->meth == METH_MOVE ) meth="MOVE";
    else if ( rq->meth == METH_LOCK ) meth="LOCK";
    else if ( rq->meth == METH_UNLOCK ) meth="UNLOCK";
    else
        return ret;
    if(srv_connect(rq)<=0)
        goto done;
    answer = build_direct_request(meth, &rq->url, NULL, rq, DONT_CHANGE_HTTPVER);
    // printf("send to server:\n%s",answer);
    if ( !answer )
        goto done;
//	r = writet(server_so, answer, strlen(answer), READ_ANSW_TIMEOUT);

    r=rq->client->send(answer);
    if ( r <= 0 ) {
        say_bad_request( "Can't send", "",
                         ERR_TRANSFER, rq);
        goto done;
    }
    /*
        answer = (char *)xmalloc(ANSW_SIZE+1, "send_not_cached(): 1");
        if ( !answer ) goto done;
      */  if ( rq->data ) {
        char	*cp = NULL;
        int	rest= 0;
        /* send whole content to server				*/

        if ( rq->data ) {
            cp  = rq->data->data;
            rest= rq->data->used;
        }
        cp[rq->data->used]=0;
        //client_left_recv-=rest;
        while ( rest > 0 ) {
            int to_send;
            to_send = MIN(2048, rest);
            /*
            r = writet(server_so, cp, to_send, 100);
            if ( r < 0 )
            	goto done;
            */
            //printf("to_send=%d\n",to_send);
            if((r=rq->client->send(cp,to_send))<=0)
                goto done;
            //printf("cp=%s,r=%d\n",cp,r);
            rest -= r;
            cp   += r;
        }
    }
    // printf("leave to read:%d bytes\n", rq->leave_to_read);
//	printf("content_length=%d\n",rq->content_length);
    //pump_data(rq->server->get_socket(),rq->client->get_socket());
    if(create_select_pipe(rq->server,rq->client,conf.time_out[HTTP],(rq->leave_to_read==0?0:-1),-1)<=0)
        ret=1;

done:
    // if ( server_so >0 ) CLOSE(server_so);
    // if ( answer ) xfree(answer);
    rq->client->close();
    IF_FREE(answer);
    return ret;
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
    int rc;

    srv_addr.sin_family = AF_INET;
    srv_addr.sin_port = htons(LISTEN_PORT);
    const char *hostname = (argc > 1) ? argv[1] : HOST;
    struct hostent *hp = gethostbyname(hostname);
    if (hp == NULL) {
        printf("Failed to lookup hostname %s\n", HOST);
        exit(-1);
    }
    memcpy(&srv_addr.sin_addr, hp->h_addr, hp->h_length);
    
    struct th_arg args;
#ifdef NOMULTISOCK
    shared_sock = socket(PF_INET, SOCK_STREAM, 0);
#else
    shared_sock = cmm_socket(PF_INET, SOCK_STREAM, 0);
#endif
    if (shared_sock < 0) {
        perror("socket");
        exit(-1);
    }

    rc = srv_connect(hostname, CMM_LABEL_ONDEMAND);
    if (rc < 0) {
#ifndef NOMULTISOCK
        if (rc == CMM_DEFERRED) {
            printf("Initial connection deferred\n");
        } else 
#endif
          {
            printf("Initial connection failed!\n");
#ifdef NOMULTISOCK
            close(shared_sock);
#else
            cmm_close(shared_sock);
#endif
            exit(-1);
        }
    }

    running = true;
    signal(SIGINT, handle_term);
    signal(SIGPIPE, SIG_IGN);

    pthread_t tid;
    rc = pthread_create(&tid, NULL, (void *(*)(void*)) BackgroundPing, &args);
    if (rc < 0) {
        printf("Failed to start background thread\n");
    }

    while (running) {
        struct th_arg *new_args = args.clone();

        if (!fgets(new_args->ch.data, sizeof(new_args->ch) - 1, stdin)) {
            if (errno == EINTR) {
                //printf("interrupted; trying again\n");
                continue;
            } else {
                printf("fgets failed!\n");
                running = false;
                break;
            }
        }

        PthreadScopedLock lock(&socket_lock);
        printf("Attempting to send message\n");
        struct timeval begin, end, diff;
        TIME(begin);
#ifdef NOMULTISOCK
        rc = send(shared_sock, new_args->ch.data, sizeof(new_args->ch), 0);
#else
        rc = cmm_send(shared_sock, new_args->ch.data, sizeof(new_args->ch), 0,
                      CMM_LABEL_ONDEMAND, 
                      (resume_handler_t)resume_ondemand, new_args);
        if (rc == CMM_DEFERRED) {
            printf("Deferred\n");
        } else 
#endif
        if (rc < 0) {
            perror("send");
            break;
        } else {
            delete new_args;
            TIME(end);
            TIMEDIFF(begin, end, diff);
            printf("[%lu.%06lu][testapp] ...message sent, took %lu.%06lu seconds\n",
                    end.tv_sec, end.tv_usec, diff.tv_sec, diff.tv_usec);
            rc = get_reply(shared_sock);
            if (rc < 0) {
                break;
            }
            struct timeval reply_end;
            TIME(reply_end);
            TIMEDIFF(begin, reply_end, diff);
            printf("Send-and-receive time: %lu.%06lu seconds\n", 
                    diff.tv_sec, diff.tv_usec);
        }
    }

#ifdef NOMULTISOCK
    shutdown(shared_sock, SHUT_RDWR);
#else
    cmm_shutdown(shared_sock, SHUT_RDWR);
#endif

    pthread_join(tid, NULL);

#ifdef NOMULTISOCK
    close(shared_sock);
#else
    cmm_close(shared_sock);
#endif    

    return 0;
}
Exemplo n.º 7
0
int
enqueue(int argc, char *argv[])
{
	int			 i, ch, tflag = 0, noheader;
	char			*fake_from = NULL, *buf;
	struct passwd		*pw;
	FILE			*fp, *fout;
	size_t			 len, envid_sz = 0;
	int			 fd;
	char			 sfn[] = "/tmp/smtpd.XXXXXXXXXX";
	char			*line;
	int			 dotted;
	int			 inheaders = 0;
	int			 save_argc;
	char			**save_argv;

	memset(&msg, 0, sizeof(msg));
	time(&timestamp);

	save_argc = argc;
	save_argv = argv;

	while ((ch = getopt(argc, argv,
	    "A:B:b:E::e:F:f:iJ::L:mN:o:p:qR:tvV:x")) != -1) {
		switch (ch) {
		case 'f':
			fake_from = optarg;
			break;
		case 'F':
			msg.fromname = optarg;
			break;
		case 'N':
			msg.dsn_notify = optarg;
			break;
		case 'R':
			msg.dsn_ret = optarg;
			break;
		case 't':
			tflag = 1;
			break;
		case 'v':
			verbose = 1;
			break;
		case 'V':
			msg.dsn_envid = optarg;
			break;
		/* all remaining: ignored, sendmail compat */
		case 'A':
		case 'B':
		case 'b':
		case 'E':
		case 'e':
		case 'i':
		case 'L':
		case 'm':
		case 'o':
		case 'p':
		case 'x':
			break;
		case 'q':
			/* XXX: implement "process all now" */
			return (EX_SOFTWARE);
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;

	if (getmailname(host, sizeof(host)) == -1)
		err(EX_NOHOST, "getmailname");
	if ((user = getlogin()) != NULL && *user != '\0')
		pw = getpwnam(user);
	else if ((pw = getpwuid(getuid())) == NULL)
		user = "******";
	user = xstrdup(pw ? pw->pw_name : user, "enqueue");

	build_from(fake_from, pw);

	while (argc > 0) {
		rcpt_add(argv[0]);
		argv++;
		argc--;
	}

	if ((fd = mkstemp(sfn)) == -1 ||
	    (fp = fdopen(fd, "w+")) == NULL) {
		int saved_errno = errno;
		if (fd != -1) {
			unlink(sfn);
			close(fd);
		}
		errc(EX_UNAVAILABLE, saved_errno, "mkstemp");
	}
	unlink(sfn);
	noheader = parse_message(stdin, fake_from == NULL, tflag, fp);

	if (msg.rcpt_cnt == 0)
		errx(EX_SOFTWARE, "no recipients");

	/* init session */
	rewind(fp);

	/* try to connect */
	/* If the server is not running, enqueue the message offline */

	if (!srv_connect())
		return (enqueue_offline(save_argc, save_argv, fp));

	if ((msg.fd = open_connection()) == -1)
		errx(EX_UNAVAILABLE, "server too busy");

	fout = fdopen(msg.fd, "a+");
	if (fout == NULL)
		err(EX_UNAVAILABLE, "fdopen");

	/* 
	 * We need to call get_responses after every command because we don't
	 * support PIPELINING on the server-side yet.
	 */

	/* banner */
	get_responses(fout, 1);

	send_line(fout, verbose, "EHLO localhost\n");
	get_responses(fout, 1);

	if (msg.dsn_envid != NULL)
		envid_sz = strlen(msg.dsn_envid);

	send_line(fout, verbose, "MAIL FROM:<%s> %s%s %s%s\n",
	    msg.from,
	    msg.dsn_ret ? "RET=" : "",
	    msg.dsn_ret ? msg.dsn_ret : "",
	    envid_sz ? "ENVID=" : "",
	    envid_sz ? msg.dsn_envid : "");
	get_responses(fout, 1);

	for (i = 0; i < msg.rcpt_cnt; i++) {
		send_line(fout, verbose, "RCPT TO:<%s> %s%s\n",
		    msg.rcpts[i],
		    msg.dsn_notify ? "NOTIFY=" : "",
		    msg.dsn_notify ? msg.dsn_notify : "");
		get_responses(fout, 1);
	}

	send_line(fout, verbose, "DATA\n");
	get_responses(fout, 1);

	/* add From */
	if (!msg.saw_from)
		send_line(fout, 0, "From: %s%s<%s>\n",
		    msg.fromname ? msg.fromname : "",
		    msg.fromname ? " " : "",
		    msg.from);

	/* add Date */
	if (!msg.saw_date)
		send_line(fout, 0, "Date: %s\n", time_to_text(timestamp));

	/* add Message-Id */
	if (!msg.saw_msgid)
		send_line(fout, 0, "Message-Id: <%"PRIu64".enqueue@%s>\n",
		    generate_uid(), host);

	if (msg.need_linesplit) {
		/* we will always need to mime encode for long lines */
		if (!msg.saw_mime_version)
			send_line(fout, 0, "MIME-Version: 1.0\n");
		if (!msg.saw_content_type)
			send_line(fout, 0, "Content-Type: text/plain; "
			    "charset=unknown-8bit\n");
		if (!msg.saw_content_disposition)
			send_line(fout, 0, "Content-Disposition: inline\n");
		if (!msg.saw_content_transfer_encoding)
			send_line(fout, 0, "Content-Transfer-Encoding: "
			    "quoted-printable\n");
	}

	/* add separating newline */
	if (noheader)
		send_line(fout, 0, "\n");
	else
		inheaders = 1;

	for (;;) {
		buf = fgetln(fp, &len);
		if (buf == NULL && ferror(fp))
			err(EX_UNAVAILABLE, "fgetln");
		if (buf == NULL && feof(fp))
			break;
		/* newlines have been normalized on first parsing */
		if (buf[len-1] != '\n')
			errx(EX_SOFTWARE, "expect EOL");

		dotted = 0;
		if (buf[0] == '.') {
			fputc('.', fout);
			dotted = 1;
		}

		line = buf;

		if (msg.saw_content_transfer_encoding || noheader ||
		    inheaders || !msg.need_linesplit) {
			if (inheaders)
				send_header(fout, line, len);
			else
				send_line(fout, 0, "%.*s", (int)len, line);
			if (inheaders && buf[0] == '\n')
				inheaders = 0;
			continue;
		}

		/* we don't have a content transfer encoding, use our default */
		do {
			if (len < LINESPLIT) {
				qp_encoded_write(fout, line, len);
				break;
			}
			else {
				qp_encoded_write(fout, line,
				    LINESPLIT - 2 - dotted);
				send_line(fout, 0, "=\n");
				line += LINESPLIT - 2 - dotted;
				len -= LINESPLIT - 2 - dotted;
			}
		} while (len);
	}
	send_line(fout, verbose, ".\n");
	get_responses(fout, 1);

	send_line(fout, verbose, "QUIT\n");
	get_responses(fout, 1);

	fclose(fp);
	fclose(fout);

	exit(EX_OK);
}