Пример #1
0
int RASocket::authenticate()
{
    if (send(std::string("Username: "******"Password: "******"Login attempt for user: %s", user.c_str());

    if (check_access_level(user) == -1)
        return -1;

    if (check_password(user, pass) == -1)
        return -1;

    TC_LOG_INFO(LOG_FILTER_REMOTECOMMAND, "User login: %s", user.c_str());

    return 0;
}
Пример #2
0
int RASocket::authenticate()
{
    if (send(std::string("Username: "******"Password: "******"Login attempt for user: %s", user.c_str());

    if (check_access_level(user) == -1)
        return -1;

    if (check_password(user, pass) == -1)
        return -1;

    sLog->outRemote("User login: %s", user.c_str());

    return 0;
}
Пример #3
0
int RASocket::svc(void)
{
    if (send("Authentication required\r\n") == -1)
        return -1;

    if (authenticate() == -1)
    {
        (void) send("Authentication failed\r\n");
        return -1;
    }

    // send motd
    if (send(std::string(sWorld->GetMotd()) + "\r\n") == -1)
        return -1;

    for(;;)
    {
        // show prompt
        const char* tc_prompt = "TC> ";
        if (size_t(peer().send(tc_prompt, strlen(tc_prompt))) != strlen(tc_prompt))
            return -1;

        std::string line;

        if (recv_line(line) == -1)
            return -1;

        if (process_command(line) == -1)
            return -1;
    }

    return 0;
}
Пример #4
0
int RASocket::recv_line(std::string& out_line)
{
    char buf[4096];

    ACE_Data_Block db(sizeof (buf),
            ACE_Message_Block::MB_DATA,
            buf,
            0,
            0,
            ACE_Message_Block::DONT_DELETE,
            0);

    ACE_Message_Block message_block(&db,
            ACE_Message_Block::DONT_DELETE,
            0);

    if (recv_line(message_block) == -1)
    {
        TC_LOG_DEBUG(LOG_FILTER_REMOTECOMMAND, "Recv error %s", ACE_OS::strerror(errno));
        return -1;
    }

    out_line = message_block.rd_ptr();

    return 0;
}
Пример #5
0
int RASocket::svc(void)
{
    //! Subnegotiation may differ per client - do not react on it
    subnegotiate();

    if (send("Authentication required\r\n") == -1)
        return -1;

    if (authenticate() == -1)
    {
        (void) send("Authentication failed\r\n");
        return -1;
    }

    // send motd
    if (send(std::string(sWorld->GetMotd()) + "\r\n") == -1)
        return -1;

    for (;;)
    {
        // show prompt
        if (send("TC> ") == -1)
            return -1;

        std::string line;

        if (recv_line(line) == -1)
            return -1;

        if (process_command(line) == -1)
            return -1;
    }

    return 0;
}
Пример #6
0
int RASocket::recv_line(std::string& out_line)
{
    char buf[4096];

    ACE_Data_Block db(sizeof (buf),
            ACE_Message_Block::MB_DATA,
            buf,
            0,
            0,
            ACE_Message_Block::DONT_DELETE,
            0);

    ACE_Message_Block message_block(&db,
            ACE_Message_Block::DONT_DELETE,
            0);

    if (recv_line(message_block) == -1)
    {
        sLog->outRemote("Recv error %s", ACE_OS::strerror(errno));
        return -1;
    }

    out_line = message_block.rd_ptr();

    return 0;
}
Пример #7
0
void take_connection(int sockfd) {

	int status;
	char *buff;

	/* chek for client ip */
	if (strcmp(client_ip, "127.0.0.1")) {
		close(sockfd);

		return;
	}

	send_line(sockfd, message(MSG_WELCOME), strlen(message(MSG_WELCOME)));

	if (helo_cmd(sockfd)) {
		close(sockfd);
		return;
	}

	buff = calloc(MAX_MSG_SIZE, sizeof(char));

	while (1) {
		memset(buff, '\0', MAX_MSG_SIZE);

		if (recv_line(sockfd, buff, MAX_MSG_SIZE - 1) <= 0) {
			free(buff);
			break;
		} else {
			status = lr_cmd(sockfd, buff);

			/* if something went wrong break */
			if (status <= -1) {
				break;
			/* if it went ok continue */
			} else if (status == 0) {
				continue;
			/* else: nothing happened, this command wasn't requested */
			} else {
				status = bye_cmd(sockfd, buff);

				if (status <= 0 ||
					send_line(
						sockfd,
						message(MSG_BAD_SYNTAX),
						strlen(message(MSG_BAD_SYNTAX))
					) < 0) {
					break;
				}
			}
		}
	}

	sleep(1);
	close(sockfd);
}
Пример #8
0
/* This function handles the connection on the passed socket from the 
 * passed client address and logs to the passed FD. The connection is 
 * processed as a web request and this function replies over the connected
 * socket.  Finally, the passed socket is closed at the end of the function. 
 */ 
void handle_connection(int sockfd, struct sockaddr_in *client_addr_ptr, int logfd) { 
   unsigned char *ptr, request[500], resource[500], log_buffer[500]; 
   int fd, length; 

   length = recv_line(sockfd, request); 
   
   sprintf(log_buffer, "From %s:%d \"%s\"\t", inet_ntoa(client_addr_ptr->sin_addr), ntohs(client_addr_ptr->sin_port), request); 

   ptr = strstr(request, " HTTP/"); // search for valid looking request 
   if(ptr == NULL) { // then this isn't valid HTTP 
      strcat(log_buffer, " NOT HTTP!\n"); 
   } else { 
      *ptr = 0; // terminate the buffer at the end of the URL 
      ptr = NULL; // set ptr to NULL (used to flag for an invalid request) 
      if(strncmp(request, "GET ", 4) == 0)  // get request 
         ptr = request+4; // ptr is the URL 
      if(strncmp(request, "HEAD ", 5) == 0) // head request 
         ptr = request+5; // ptr is the URL 
      if(ptr == NULL) { // then this is not a recognized request 
         strcat(log_buffer, " UNKNOWN REQUEST!\n"); 
      } else { // valid request, with ptr pointing to the resource name 
         if (ptr[strlen(ptr) - 1] == '/')  // for resources ending with '/' 
            strcat(ptr, "index.html");     // add 'index.html' to the end 
         strcpy(resource, WEBROOT);     // begin resource with web root path 
         strcat(resource, ptr);         //  and join it with resource path 
         fd = open(resource, O_RDONLY, 0); // try to open the file 
         if(fd == -1) { // if file is not found 
            strcat(log_buffer, " 404 Not Found\n"); 
            send_string(sockfd, "HTTP/1.0 404 NOT FOUND\r\n"); 
            send_string(sockfd, "Server: Tiny webserver\r\n\r\n"); 
            send_string(sockfd, "<html><head><title>404 Not Found</title></head>"); 
            send_string(sockfd, "<body><h1>URL not found</h1></body></html>\r\n"); 
         } else {      // otherwise, serve up the file 
            strcat(log_buffer, " 200 OK\n"); 
            send_string(sockfd, "HTTP/1.0 200 OK\r\n"); 
            send_string(sockfd, "Server: Tiny webserver\r\n\r\n"); 
            if(ptr == request + 4) { // then this is a GET request 
               if( (length = get_file_size(fd)) == -1) 
                  fatal("getting resource file size"); 
               if( (ptr = (unsigned char *) malloc(length)) == NULL) 
                  fatal("allocating memory for reading resource"); 
               read(fd, ptr, length); // read the file into memory 
               send(sockfd, ptr, length, 0);  // send it to socket 
               free(ptr); // free file memory 
            } 
            close(fd); // close the file 
         } // end if block for file found/not found 
      } // end if block for valid request 
   } // end if block for valid HTTP 
   timestamp(logfd); 
   length = strlen(log_buffer); 
   write(logfd, log_buffer, length); // write to the log 

   shutdown(sockfd, SHUT_RDWR); // close the socket gracefully
} 
Пример #9
0
int
send_recv(struct user *u, int child_no, struct user *users)
{
	//struct user *up = &u;
	char *buf;
	ssize_t len;

	(void) fprintf(stderr, "-----------------------------------\n");
	len = recv_line(u->socket, &buf);
	if (len == -1){ // 受信失敗。無視する
		(void) fprintf(stderr, "error");
		return(0);
	}
	if(len == 0){
		(void) fprintf(stderr, "recv:EOF\n");
		return(-1);
	}
	char *cmd, *body;
	client_cmd_parse(buf, &cmd, &body);

	if(strncmp(cmd, "JOIN", sizeof("JOIN")) == 0){
		fprintf(stderr, "JOIN CMD..\n");
		if(!set_name(u, body)){
			disconnect(u);
		}
		(void) fprintf(stderr, "name= '%s'\n", u->name);
	}else if(strncmp(cmd, "SAY", sizeof("SAY")) == 0){
		fprintf(stderr, "SAY CMD..\n");

		push_to_everybody(users, generate_sayed_cmd(u, body));
		/*
		int send_len = strlen(body);
		fprintf(stderr, "body...'%s', len=%d\n", body, send_len);
		generate_sayed_cmd(u, body);
		int i;
		for (i = 0; i < MAX_CHILD; i++) {
			if(users[i].socket != -1){
				fprintf(stderr, "sending....to [user:%d]\n", users[i].no);
				len = send(users[i].socket, body, (size_t) send_len, 0);
				if (len == -1) {
					perror("send");
					return(-1);
				}
			}
		}
		*/
	}else if(strncmp(cmd, "LEAVE", sizeof("LEAVE")) == 0){
		fprintf(stderr, "LEAVE CMD..\n");
	}
	//free(body);
	free(cmd);
	free(buf);
	return(0);
}
Пример #10
0
char* nrecv(int clientfd)
{
    int read = 0, nread = 0;
    char head_line[100];
    char content_len[] = "Content-Length: ";
    char *p = NULL;
    char *buf = NULL;
    int body_len = 0;
    /*printf("step into nrecv!\n");*/
    do {
        if (recv_line(clientfd,head_line) <= 0)
            return NULL;
    } while(strstr(head_line, content_len) == NULL);

    p = head_line + 16;
    while(*p != '\0') {
        body_len = body_len * 10 + *p - '0';
        p++;
    }
    /*printf("nrecv 85\n");*/
    do {
        if(recv_line(clientfd, head_line) < 0)
            return NULL;
        if(strlen(head_line) == 0)
            break;
    } while(1);
    /*printf("nrecv 92\n");*/
    if((buf = (char *) malloc((body_len+1) * sizeof(char))) == NULL)
        return NULL;
    do {
        read = recv(clientfd, buf + nread, body_len-nread, 0);
        if(read < 0) {
            return NULL;
        }
        nread += read;
    } while(read > 0);
    /*printf("nrecv 102\n");*/
    *(buf+body_len) = '\0';
    /*	printf("will out the nrecv\n");*/
    return buf;
}
Пример #11
0
int http_response_status(http_client_ptr_t http_client)/* 远程WEB服务器的http响应代码,如404*/
{
	//char *temp[5];
	int flag;
	char recvbuf[RECVSIZE+1];
	bzero(recvbuf,RECVSIZE+1);
	flag = recv_line(recvbuf, &(http_client->network));
	if(flag == -1) {
		fprintf(stderr, "Error in http_response_status(). recv error.\n");
		return flag;
	}
	else if (flag < 2) {
		fprintf(stderr, "Error in http_response_status(). recv error.\n");
		fprintf(stderr, "Now flag is %d, recvbuf is %s.\n",flag ,recvbuf);
		return -1;
	}
	//mysplit(temp, recvbuf, " ");
	http_client->status = get_status(recvbuf);
	bzero(recvbuf,RECVSIZE);
	flag = recv_line(recvbuf, &(http_client->network));
	if(flag <= -1){
		fprintf(stderr, "Error in http_response_status(). recv error.\n");
		return -1;
	}
	while(strcmp(recvbuf,"\r\n")!=0) {
//		mysplit(temp, recvbuf, ":");
//		if(strcasecmp(temp[0], "Content-Length")==0) {
//			http_client->content_length = atol(temp[1]);
//		}
//		bzero(recvbuf,RECVSIZE);
		flag = recv_line(recvbuf, &(http_client->network));
		if(flag <= -1){
			fprintf(stderr, "Error in http_response_status(). recv error.\n");
			return -1;
		}
	}
	//fprintf(stderr,"http get status success!\n");
	return http_client->status;
}
Пример #12
0
int ClientSocket::svc(void)
{
    for(;;)
    {
        std::string line;

        if (recv_line(line) == -1)
            return -1;

        if (process_command(line) == -1)
            return -1;
    }
    return 0;
}
Пример #13
0
static void
dump_residual (socket_descriptor_t sd,
	       int timeout,
	       volatile int *signal_received)
{
  char buf[256];
  while (true)
    {
      if (!recv_line (sd, buf, sizeof (buf), timeout, true, NULL, signal_received))
	return;
      chomp (buf);
      msg (D_PROXY, "PROXY HEADER: '%s'", buf);
    }
}
Пример #14
0
/**
 * Returns -1 if no socket, error or client asked to stop tests, 0 otherwise.
 */
static int
hosts_read_client (struct arglist *globals)
{
  struct timeval tv;
  int e;
  fd_set rd;
  int rsoc;

  if (g_soc == -1)
    return 0;


  rsoc = openvas_get_socket_from_connection (g_soc);
  if (rsoc == -1)
    return -1;

  FD_ZERO (&rd);
  FD_SET (rsoc, &rd);

  for (;;)
    {
      tv.tv_sec = 0;
      tv.tv_usec = 1000;
      e = select (rsoc + 1, &rd, NULL, NULL, &tv);
      if (e < 0 && errno == EINTR)
        continue;
      else
        break;
    }

  if (e > 0 && FD_ISSET (rsoc, &rd) != 0)
    {
      int f, n;
      char buf[4096];
      n = recv_line (g_soc, buf, sizeof (buf) - 1);
      if (n <= 0)
        return -1;

      f = ntp_parse_input (globals, buf);
      if (f == NTP_STOP_WHOLE_TEST)
        return -1;
      else if (f == NTP_PAUSE_WHOLE_TEST)
        hosts_pause_all ();
      else if (f == NTP_RESUME_WHOLE_TEST)
        hosts_resume_all ();
    }

  return 0;
}
Пример #15
0
static int read_version(conn_t *conn)
{
	char buf[1024];
	unsigned i;
	if(!recv_line(conn, buf, sizeof(buf)))
	    return -1;
	if (!strcmp(buf, "UNKNOWN COMMAND\n"))
	    return -2;

	conn->version = strdup(buf);
	OOM_CHECK(conn->version);
	for (i=0;i<strlen(conn->version);i++)
		    if (conn->version[i] == '\n')
			conn->version[i] = ' ';
	return 0;
}
Пример #16
0
/*
 * Extract the Proxy-Authenticate header from the stream.
 * Consumes all headers.
 */
static int
get_proxy_authenticate (socket_descriptor_t sd,
		        int timeout,
			char **data,
			struct gc_arena *gc,
		        volatile int *signal_received)
{
  char buf[256];
  int ret = HTTP_AUTH_NONE;
  while (true)
    {
      if (!recv_line (sd, buf, sizeof (buf), timeout, true, NULL, signal_received))
	{
	  *data = NULL;
	  return HTTP_AUTH_NONE;
	}
      chomp (buf);
      if (!strlen(buf))
	return ret;
      if (ret == HTTP_AUTH_NONE && !strncmp(buf, "Proxy-Authenticate: ", 20))
	{
	  if (!strncmp(buf+20, "Basic ", 6))
	    {
	      msg (D_PROXY, "PROXY AUTH BASIC: '%s'", buf);
	      *data = string_alloc(buf+26, gc);
	      ret = HTTP_AUTH_BASIC;
	    }
#if PROXY_DIGEST_AUTH
	  else if (!strncmp(buf+20, "Digest ", 7))
	    {
	      msg (D_PROXY, "PROXY AUTH DIGEST: '%s'", buf);
	      *data = string_alloc(buf+27, gc);
	      ret = HTTP_AUTH_DIGEST;
	    }
#endif
#if NTLM
	  else if (!strncmp(buf+20, "NTLM", 4))
	    {
	      msg (D_PROXY, "PROXY AUTH HTLM: '%s'", buf);
	      *data = NULL;
	      ret = HTTP_AUTH_NTLM;
	    }
#endif
	}
    }
}
Пример #17
0
int main(int argc, char *argv[]){

	int sockfd;
	struct hostent *host_info;
	struct sockaddr_in target_addr;
	unsigned char buffer[4096];
	
	if (argc < 2){
		printf("Usage: %s <hostname>\n",argv[1]);
	}

	/* tries to resolve the hostname. if it failes, a null pointer is returned */
	if((host_info=gethostbyname(argv[1]))==NULL){
		printf("Could not resolve hostname %s",argv[1]);
	}

	/* creates a usual tcp socket for internet protocol family */
	if((sockfd=socket(PF_INET, SOCK_STREAM,0))==0){
		printf("Error creating socket\n");
	}
	
	target_addr.sin_family=AF_INET;		/* sets the host byte order */
	target_addr.sin_port=htons(80);		/* changes the integer port number from host byte order into network byte order */
	target_addr.sin_addr = *((struct in_addr *) host_info->h_addr);		/* sets the address we are trying to connect. the information is received from hostent struct */
	memset(&(target_addr.sin_zero),'\0',8);		/* padding to zero */

	/* connect function call on socket tries to connect 
	see http://linux.die.net/man/2/connect */
	if(connect(sockfd, (struct sockaddr *)&target_addr, sizeof(struct sockaddr)) == -1){
		printf("Error when connecting to the remote server\n");
	}

	send_string(sockfd, "HEAD / HTTP/1.0\r\n\r\n");

	while(recv_line(sockfd, buffer)){
		/* strncasecmü is a string comparsion functon from string.h that compares the first n bytes of the two strings, ignoring capit. 
		   it retunrs 0 on success. If it found that string, it will remove that and print out everything after that */
		if(strncasecmp(buffer, "Server:",7)==0){
			printf("The webserver for the hostname %s is %s\n", argv[1], buffer+8);
			exit(0);
		}
	}
	printf("Server line not found\n");
	exit(1);

}
Пример #18
0
static void parse_queue(conn_t *conn, char* buf, size_t len, unsigned idx)
{
	do {
		double tim;
		const char *t = strchr(buf, ' ');
		if(!t)
			continue;
		if(sscanf(t,"%lf", &tim) != 1)
			continue;
		++global.n;
		global.tasks = realloc(global.tasks, sizeof(*global.tasks)*global.n);
		OOM_CHECK(global.tasks);
		global.tasks[global.n-1].line = strdup(buf);
		OOM_CHECK(global.tasks[global.n-1].line);
		global.tasks[global.n-1].tim  = tim;
		global.tasks[global.n-1].clamd_no = idx + 1;
	} while (recv_line(conn, buf, len) && buf[0] == '\t' && strcmp("END\n", buf) != 0);
}
Пример #19
0
/**
* Main - Run through the steps of configuring, greeting, getting a name, thanking,
* and then quitting
*/
int main(void) {
	char buff[BUFF_LENGTH];

	// Setup the hardware
	init_hardware();

	// Wait until the USB port is configured and ready to go
	draw_centred(17, "Waiting for");
	draw_centred(24, "computer...");
	show_screen();
	while (!usb_configured() || !usb_serial_get_control());

	// Prompt the user for their name, and wait until they enter it
	clear_screen();
	draw_centred(17, "Waiting for");
	draw_centred(24, "username...");
	show_screen();
	send_line("Hello!");
	send_line("Could you please tell me your name:");
	recv_line(buff, BUFF_LENGTH);
	usb_serial_putchar('\n');

	// Display their name on the Teensy and prompt them to exit
	char buff2[BUFF_LENGTH + 8];
	sprintf(buff2, "Thanks %s!", buff);
	clear_screen();
	draw_centred(21, buff2);
	show_screen();
	send_line("Press 'q' to exit...");
	while (usb_serial_getchar() != 'q');

	// Display the finished information
	clear_screen();
	draw_centred(21, "Goodbye!");
	show_screen();
	send_line("\r");
	send_line("Done! Goodbye!");
	while (1);

	// We'll never get here...
	return 0;
}
Пример #20
0
int RASocket::svc(void)
{
    //! Subnegotiation may differ per client - do not react on it
    subnegotiate();

    if (send("Authentication required\r\n") == -1)
        return -1;

    if (authenticate() == -1)
    {
        (void) send("Authentication failed\r\n");
        return -1;
    }

    // send motd
    if (send(std::string(sWorld->GetMotd()) + "\r\n") == -1)
        return -1;

    for (;;)
    {
        // show prompt
        const char* tc_prompt = "QUANTUMCORE SERVER DAEMON> ";
        if (size_t(peer().send(tc_prompt, strlen(tc_prompt))) != strlen(tc_prompt))
            return -1;

        std::string line;

        if (recv_line(line) == -1)
            return -1;

        if (process_command(line) == -1)
            return -1;
    }

    return 0;
}
Пример #21
0
bool
establish_http_proxy_passthru (struct http_proxy_info *p,
			       socket_descriptor_t sd, /* already open to proxy */
			       const char *host,       /* openvpn server remote */
			       const int port,         /* openvpn server port */
			       struct buffer *lookahead,
			       volatile int *signal_received)
{
  struct gc_arena gc = gc_new ();
  char buf[256];
  char buf2[128];
  char get[80];
  int status;
  int nparms;
  bool ret = false;

  /* get user/pass if not previously given or if --auto-proxy is being used */
  if (p->auth_method == HTTP_AUTH_BASIC
      || p->auth_method == HTTP_AUTH_NTLM)
    get_user_pass_http (p, false);

  /* format HTTP CONNECT message */
  openvpn_snprintf (buf, sizeof(buf), "CONNECT %s:%d HTTP/%s\r\nHOST: %s:%d",
		    host,
		    port,
		    p->options.http_version,
		    host,
		    port);

  msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);

  /* send HTTP CONNECT message to proxy */
  if (!send_line_crlf (sd, buf))
    goto error;

  /* send User-Agent string if provided */
  if (p->options.user_agent)
    {
      openvpn_snprintf (buf, sizeof(buf), "User-Agent: %s",
			p->options.user_agent);
      if (!send_line_crlf (sd, buf))
	goto error;
    }

  /* auth specified? */
  switch (p->auth_method)
    {
    case HTTP_AUTH_NONE:
      break;

    case HTTP_AUTH_BASIC:
      openvpn_snprintf (buf, sizeof(buf), "Proxy-Authorization: Basic %s",
			username_password_as_base64 (p, &gc));
      msg (D_PROXY, "Attempting Basic Proxy-Authorization");
      dmsg (D_SHOW_KEYS, "Send to HTTP proxy: '%s'", buf);
      openvpn_sleep (1);
      if (!send_line_crlf (sd, buf))
	goto error;
      break;

#if NTLM
    case HTTP_AUTH_NTLM:
    case HTTP_AUTH_NTLM2:
      /* keep-alive connection */
      openvpn_snprintf (buf, sizeof(buf), "Proxy-Connection: Keep-Alive");
      if (!send_line_crlf (sd, buf))
	goto error;

      openvpn_snprintf (buf, sizeof(buf), "Proxy-Authorization: NTLM %s",
			ntlm_phase_1 (p, &gc));
      msg (D_PROXY, "Attempting NTLM Proxy-Authorization phase 1");
      dmsg (D_SHOW_KEYS, "Send to HTTP proxy: '%s'", buf);
      openvpn_sleep (1);
      if (!send_line_crlf (sd, buf))
	goto error;
      break;
#endif

    default:
      ASSERT (0);
    }

  /* send empty CR, LF */
  openvpn_sleep (1);
  if (!send_crlf (sd))
    goto error;

  /* receive reply from proxy */
  if (!recv_line (sd, buf, sizeof(buf), p->options.timeout, true, NULL, signal_received))
    goto error;

  /* remove trailing CR, LF */
  chomp (buf);

  msg (D_PROXY, "HTTP proxy returned: '%s'", buf);

  /* parse return string */
  nparms = sscanf (buf, "%*s %d", &status);

  /* check for a "407 Proxy Authentication Required" response */
  if (nparms >= 1 && status == 407)
    {
      msg (D_PROXY, "Proxy requires authentication");

      /* check for NTLM */
      if (p->auth_method == HTTP_AUTH_NTLM || p->auth_method == HTTP_AUTH_NTLM2)
        {
#if NTLM
          /* look for the phase 2 response */

          while (true)
            {
              if (!recv_line (sd, buf, sizeof(buf), p->options.timeout, true, NULL, signal_received))
                goto error;
              chomp (buf);
              msg (D_PROXY, "HTTP proxy returned: '%s'", buf);

              openvpn_snprintf (get, sizeof get, "%%*s NTLM %%%ds", (int) sizeof (buf2) - 1);
              nparms = sscanf (buf, get, buf2);
              buf2[127] = 0; /* we only need the beginning - ensure it's null terminated. */

              /* check for "Proxy-Authenticate: NTLM TlRM..." */
              if (nparms == 1)
                {
                  /* parse buf2 */
                  msg (D_PROXY, "auth string: '%s'", buf2);
                  break;
                }
            }
          /* if we are here then auth string was got */
          msg (D_PROXY, "Received NTLM Proxy-Authorization phase 2 response");

          /* receive and discard everything else */
          while (recv_line (sd, NULL, 0, p->options.timeout, true, NULL, signal_received))
            ;

          /* now send the phase 3 reply */

          /* format HTTP CONNECT message */
          openvpn_snprintf (buf, sizeof(buf), "CONNECT %s:%d HTTP/%s",
			    host,
			    port,
			    p->options.http_version);

          msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);

          /* send HTTP CONNECT message to proxy */
          if (!send_line_crlf (sd, buf))
            goto error;

          /* keep-alive connection */
          openvpn_snprintf (buf, sizeof(buf), "Proxy-Connection: Keep-Alive");
          if (!send_line_crlf (sd, buf))
            goto error;

          
          /* send HOST etc, */
          openvpn_sleep (1);
          openvpn_snprintf (buf, sizeof(buf), "Host: %s", host);
          msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);
          if (!send_line_crlf (sd, buf))
            goto error;

          msg (D_PROXY, "Attempting NTLM Proxy-Authorization phase 3");
	  {
	    const char *np3 = ntlm_phase_3 (p, buf2, &gc);
	    if (!np3)
	      {
		msg (D_PROXY, "NTLM Proxy-Authorization phase 3 failed: received corrupted data from proxy server");
		goto error;
	      }
	    openvpn_snprintf (buf, sizeof(buf), "Proxy-Authorization: NTLM %s", np3);
	  }

          msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);
          openvpn_sleep (1);
          if (!send_line_crlf (sd, buf))
	    goto error;
          /* ok so far... */
          /* send empty CR, LF */
          openvpn_sleep (1);
          if (!send_crlf (sd))
            goto error;

          /* receive reply from proxy */
          if (!recv_line (sd, buf, sizeof(buf), p->options.timeout, true, NULL, signal_received))
            goto error;

          /* remove trailing CR, LF */
          chomp (buf);

          msg (D_PROXY, "HTTP proxy returned: '%s'", buf);

          /* parse return string */
          nparms = sscanf (buf, "%*s %d", &status);
#else
	  ASSERT (0); /* No NTLM support */
#endif
	}
      else if (p->auth_method == HTTP_AUTH_NONE && p->options.auth_retry)
	{
	  /*
	   * Proxy needs authentication, but we don't have a user/pass.
	   * Now we will change p->auth_method and return true so that
	   * our caller knows to call us again on a newly opened socket.
	   * JYFIXME: This code needs to check proxy error output and set
	   * JYFIXME: p->auth_method = HTTP_AUTH_NTLM if necessary.
	   */
	  p->auth_method = HTTP_AUTH_BASIC;
	  ret = true;
	  goto done;
	}
      else
	goto error;
    }


  /* check return code, success = 200 */
  if (nparms < 1 || status != 200)
    {
      msg (D_LINK_ERRORS, "HTTP proxy returned bad status");
#if 0
      /* DEBUGGING -- show a multi-line HTTP error response */
      while (true)
	{
	  if (!recv_line (sd, buf, sizeof (buf), p->options.timeout, true, NULL, signal_received))
	    goto error;
	  chomp (buf);
	  msg (D_PROXY, "HTTP proxy returned: '%s'", buf);
	}
#endif
      goto error;
    }

  /* receive line from proxy and discard */
  if (!recv_line (sd, NULL, 0, p->options.timeout, true, NULL, signal_received))
    goto error;

  /*
   * Toss out any extraneous chars, but don't throw away the
   * start of the OpenVPN data stream (put it in lookahead).
   */
  while (recv_line (sd, NULL, 0, 2, false, lookahead, signal_received))
    ;

#if 0
  if (lookahead && BLEN (lookahead))
    msg (M_INFO, "HTTP PROXY: lookahead: %s", format_hex (BPTR (lookahead), BLEN (lookahead), 0));
#endif

 done:
  gc_free (&gc);
  return ret;

 error:
  /* on error, should we exit or restart? */
  if (!*signal_received)
    *signal_received = (p->options.retry ? SIGUSR1 : SIGTERM); /* SOFT-SIGUSR1 -- HTTP proxy error */
  gc_free (&gc);
  return ret;
}
Пример #22
0
// sending email
void sendemail(char *email, char *body)
{
    int sockfd;
    int retval = 0;
    int err;
    char *host_name = "smtp.fakessh.eu";
    struct sockaddr_in their_addr;
    struct hostent *hent;
    char buf[1500] = {0};
    char rbuf[1500] = {0};
    char login[128] = {0};
    char pass[128] = {0};

    //initialize SSL
    SSL_CTX *ctx;
    SSL *ssl;
    SSL_METHOD *meth;

    SSLeay_add_ssl_algorithms();
    meth = SSLv23_method();
    SSL_load_error_strings();
    SSL_library_init();
    ctx = SSL_CTX_new(meth);
    CHK_NULL(ctx);

    fd_set readfds;
    struct timeval timeout;

    //Define a timeout for resending data.
    timeout.tv_sec = 2;
    timeout.tv_usec = 0;

#ifdef WIN32
    WSADATA WSAData;
    WSAStartup(MAKEWORD(2, 2), &WSAData);
#endif

    hent = gethostbyname(host_name);
    memset(&their_addr, 0, sizeof(their_addr));
    their_addr.sin_family = AF_INET;
    their_addr.sin_port = htons(587);
    their_addr.sin_addr = *((struct in_addr *)hent->h_addr);

    //connecting mail server and reconnecting if no response in 2 seconds
    sockfd = open_socket((struct sockaddr *)&their_addr);
    memset(rbuf,0,1500);
    FD_ZERO(&readfds);
    FD_SET(sockfd, &readfds);
    retval = select(sockfd+1, &readfds, NULL, NULL, &timeout);
    while(retval <= 0)
    {
        printf("reconnect...\n");
        sleep(2);
        close(sockfd);
        sockfd = open_socket((struct sockaddr *)&their_addr);
        memset(rbuf,0,1500);
        FD_ZERO(&readfds);
        FD_SET(sockfd, &readfds);
        retval = select(sockfd+1, &readfds, NULL, NULL, &timeout);
    }

    memset(rbuf, 0, 1500);
    recv(sockfd, rbuf, 1500, 0);
    printf("%s\n", rbuf);

    //EHLO
    memset(buf, 0, 1500);
    sprintf(buf, "EHLO localhost\r\n");
    send(sockfd, buf, strlen(buf), 0);
    memset(rbuf, 0, 1500);
    recv(sockfd, rbuf, 1500, 0);
    printf("%s\n", rbuf);

    //START_TLS with OPENSSL
    memset(buf,0, 1500);
    sprintf(buf, "STARTTLS\r\n");
    send(sockfd, buf, strlen(buf), 0);
    memset(rbuf, 0, 1500);
    recv(sockfd, rbuf, 1500, 0);
    printf("%s\n", rbuf);


    //AUTH LOGIN
    ssl   =   SSL_new(ctx);
    CHK_NULL(ssl);
    SSL_set_fd   (ssl,   sockfd);
    err   =   SSL_connect(ssl);
    CHK_SSL(err);

    memset(buf,0, 1500);
    sprintf(buf, "EHLO localhost\r\n");
    send_line(ssl,buf);
    recv_line(ssl);


    memset(buf,0, 1500);
    sprintf(buf, "AUTH LOGIN\r\n");
    send_line(ssl,buf);
    recv_line(ssl);

    //USER
    memset(buf, 0, 1500);
    sprintf(buf,"fakessh");
    memset(login, 0, 128);
    base64(login, buf, strlen(buf));
    sprintf(buf, "%s\r\n", login);
    send_line(ssl,buf);
    recv_line(ssl);

    //PASSWORD
    memset(buf, 0, 1500);
    sprintf(buf, "----");
    memset(pass, 0, 128);
    base64(pass, buf, strlen(buf));
    sprintf(buf, "%s\r\n", pass);
    send_line(ssl,buf);
    recv_line(ssl);

    //MAIL FROM
    memset(buf,0, 1500);
    sprintf(buf, "MAIL FROM:<*****@*****.**>\r\n");
    send_line(ssl,buf);
    recv_line(ssl);

    //RCPT TO first receiver
    memset(buf, 0, 1500);
    sprintf(buf, "RCPT TO:<*****@*****.**>\r\n");
    send_line(ssl,buf);
    recv_line(ssl);

    //RCPT TO second receiver and more receivers can be added
    //memset(buf, 0, 1500);
    //sprintf(buf, "RCPT TO:<*****@*****.**>\r\n");
    //send_line(ssl,buf);
    //recv_line(ssl);

    //DATA ready to send mail content
    send_line(ssl,"DATA\r\n");
    recv_line(ssl);

    //send mail content£¬"\r\n.\r\n" is the end mark of content
    memset(buf, 0, 1500);
    sprintf(buf, "%s\r\n.\r\n", body);
    send_line(ssl,buf);
    recv_line(ssl);
    printf("mail send!\n");

    //QUIT
    send_line(ssl,"QUIT\r\n");
    recv_line(ssl);

    //free SSL and close socket
    SSL_shutdown (ssl);
    close(sockfd);
    SSL_free (ssl);
    SSL_CTX_free (ctx);

#ifdef WIN32
    WSACleanup();
#endif

    return;
}
Пример #23
0
int
ftp_log_in (int soc, char *username, char *passwd)
{
  char buf[1024];
  int n;
  int counter;

  buf[sizeof (buf) - 1] = '\0';
  n = recv_line (soc, buf, sizeof (buf) - 1);
  if (n <= 0)
    return (1);

  if (strncmp (buf, "220", 3) != 0)
    {
      return 1;
    }

  counter = 0;
  while (buf[3] == '-' && n > 0 && counter < 1024)
    {
      n = recv_line (soc, buf, sizeof (buf) - 1);
      counter++;
    }

  if (counter >= 1024)
    return 1;                   /* Rogue FTP server */

  if (n <= 0)
    return 1;


  snprintf (buf, sizeof (buf), "USER %s\r\n", username);        /* RATS: ignore */
  write_stream_connection (soc, buf, strlen (buf));
  n = recv_line (soc, buf, sizeof (buf) - 1);
  if (n <= 0)
    return 1;
  if (strncmp (buf, "230", 3) == 0)
    {
      counter = 0;
      while (buf[3] == '-' && n > 0 && counter < 1024)
        {
          n = recv_line (soc, buf, sizeof (buf) - 1);
          counter++;
        }
      return 0;
    }

  if (strncmp (buf, "331", 3) != 0)
    {
      return 1;
    }

  counter = 0;
  n = 1;
  while (buf[3] == '-' && n > 0 && counter < 1024)
    {
      n = recv_line (soc, buf, sizeof (buf) - 1);
      counter++;
    }

  if (counter >= 1024)
    return 1;


  snprintf (buf, sizeof (buf), "PASS %s\r\n", passwd);  /* RATS: ignore */
  write_stream_connection (soc, buf, strlen (buf));
  n = recv_line (soc, buf, sizeof (buf) - 1);
  if (n <= 0)
    return 1;

  if (strncmp (buf, "230", 3) != 0)
    {
      return 1;
    }

  counter = 0;
  n = 1;
  while (buf[3] == '-' && n > 0 && counter < 1024)
    {
      n = recv_line (soc, buf, sizeof (buf) - 1);
      counter++;
    }

  return 0;
}
Пример #24
0
bool
establish_http_proxy_passthru (struct http_proxy_info *p,
			       socket_descriptor_t sd, /* already open to proxy */
			       const char *host,       /* openvpn server remote */
			       const int port,         /* openvpn server port */
			       struct buffer *lookahead,
			       volatile int *signal_received)
{
  struct gc_arena gc = gc_new ();
  char buf[512];
  char buf2[128];
  char get[80];
  int status;
  int nparms;
  bool ret = false;
  bool processed = false;

  /* get user/pass if not previously given */
  if (p->auth_method == HTTP_AUTH_BASIC
      || p->auth_method == HTTP_AUTH_DIGEST
      || p->auth_method == HTTP_AUTH_NTLM)
    get_user_pass_http (p, false);

  /* are we being called again after getting the digest server nonce in the previous transaction? */
  if (p->auth_method == HTTP_AUTH_DIGEST && p->proxy_authenticate)
    {
      nparms = 1;
      status = 407;
    }
  else
    {
      /* format HTTP CONNECT message */
      openvpn_snprintf (buf, sizeof(buf), "CONNECT %s:%d HTTP/%s",
			host,
			port,
			p->options.http_version);

      msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);

      /* send HTTP CONNECT message to proxy */
      if (!send_line_crlf (sd, buf))
	goto error;

      openvpn_snprintf(buf, sizeof(buf), "Host: %s", host);
      if (!send_line_crlf(sd, buf))
        goto error;

      /* send User-Agent string if provided */
      if (p->options.user_agent)
	{
	  openvpn_snprintf (buf, sizeof(buf), "User-Agent: %s",
			    p->options.user_agent);
	  if (!send_line_crlf (sd, buf))
	    goto error;
	}

      /* auth specified? */
      switch (p->auth_method)
	{
	case HTTP_AUTH_NONE:
	  break;

	case HTTP_AUTH_BASIC:
	  openvpn_snprintf (buf, sizeof(buf), "Proxy-Authorization: Basic %s",
			    username_password_as_base64 (p, &gc));
	  msg (D_PROXY, "Attempting Basic Proxy-Authorization");
	  dmsg (D_SHOW_KEYS, "Send to HTTP proxy: '%s'", buf);
	  if (!send_line_crlf (sd, buf))
	    goto error;
	  break;

#if NTLM
	case HTTP_AUTH_NTLM:
	case HTTP_AUTH_NTLM2:
	  /* keep-alive connection */
	  openvpn_snprintf (buf, sizeof(buf), "Proxy-Connection: Keep-Alive");
	  if (!send_line_crlf (sd, buf))
	    goto error;

	  openvpn_snprintf (buf, sizeof(buf), "Proxy-Authorization: NTLM %s",
			    ntlm_phase_1 (p, &gc));
	  msg (D_PROXY, "Attempting NTLM Proxy-Authorization phase 1");
	  dmsg (D_SHOW_KEYS, "Send to HTTP proxy: '%s'", buf);
	  if (!send_line_crlf (sd, buf))
	    goto error;
	  break;
#endif

	default:
	  ASSERT (0);
	}

      /* send empty CR, LF */
      if (!send_crlf (sd))
	goto error;

      /* receive reply from proxy */
      if (!recv_line (sd, buf, sizeof(buf), p->options.timeout, true, NULL, signal_received))
	goto error;

      /* remove trailing CR, LF */
      chomp (buf);

      msg (D_PROXY, "HTTP proxy returned: '%s'", buf);

      /* parse return string */
      nparms = sscanf (buf, "%*s %d", &status);

    }

  /* check for a "407 Proxy Authentication Required" response */
  while (nparms >= 1 && status == 407)
    {
      msg (D_PROXY, "Proxy requires authentication");

      if (p->auth_method == HTTP_AUTH_BASIC && !processed)
	{
	  processed = true;
	}
      else if ((p->auth_method == HTTP_AUTH_NTLM || p->auth_method == HTTP_AUTH_NTLM2) && !processed) /* check for NTLM */
        {
#if NTLM
          /* look for the phase 2 response */

          while (true)
            {
              if (!recv_line (sd, buf, sizeof(buf), p->options.timeout, true, NULL, signal_received))
                goto error;
              chomp (buf);
              msg (D_PROXY, "HTTP proxy returned: '%s'", buf);

              openvpn_snprintf (get, sizeof get, "%%*s NTLM %%%ds", (int) sizeof (buf2) - 1);
              nparms = sscanf (buf, get, buf2);
              buf2[127] = 0; /* we only need the beginning - ensure it's null terminated. */

              /* check for "Proxy-Authenticate: NTLM TlRM..." */
              if (nparms == 1)
                {
                  /* parse buf2 */
                  msg (D_PROXY, "auth string: '%s'", buf2);
                  break;
                }
            }
          /* if we are here then auth string was got */
          msg (D_PROXY, "Received NTLM Proxy-Authorization phase 2 response");

          /* receive and discard everything else */
          while (recv_line (sd, NULL, 0, 2, true, NULL, signal_received))
            ;

          /* now send the phase 3 reply */

          /* format HTTP CONNECT message */
          openvpn_snprintf (buf, sizeof(buf), "CONNECT %s:%d HTTP/%s",
			    host,
			    port,
			    p->options.http_version);

          msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);

          /* send HTTP CONNECT message to proxy */
          if (!send_line_crlf (sd, buf))
            goto error;

          /* keep-alive connection */
          openvpn_snprintf (buf, sizeof(buf), "Proxy-Connection: Keep-Alive");
          if (!send_line_crlf (sd, buf))
            goto error;

          
          /* send HOST etc, */
          openvpn_snprintf (buf, sizeof(buf), "Host: %s", host);
          msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);
          if (!send_line_crlf (sd, buf))
            goto error;

          msg (D_PROXY, "Attempting NTLM Proxy-Authorization phase 3");
	  {
	    const char *np3 = ntlm_phase_3 (p, buf2, &gc);
	    if (!np3)
	      {
		msg (D_PROXY, "NTLM Proxy-Authorization phase 3 failed: received corrupted data from proxy server");
		goto error;
	      }
	    openvpn_snprintf (buf, sizeof(buf), "Proxy-Authorization: NTLM %s", np3);
	  }

          msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);
          if (!send_line_crlf (sd, buf))
	    goto error;
          /* ok so far... */
          /* send empty CR, LF */
          if (!send_crlf (sd))
            goto error;

          /* receive reply from proxy */
          if (!recv_line (sd, buf, sizeof(buf), p->options.timeout, true, NULL, signal_received))
            goto error;

          /* remove trailing CR, LF */
          chomp (buf);

          msg (D_PROXY, "HTTP proxy returned: '%s'", buf);

          /* parse return string */
          nparms = sscanf (buf, "%*s %d", &status);
	  processed = true;
#endif
	}
#if PROXY_DIGEST_AUTH
      else if (p->auth_method == HTTP_AUTH_DIGEST && !processed)
	{
	  char *pa = p->proxy_authenticate;
	  const int method = p->auth_method;
	  ASSERT(pa);

	  if (method == HTTP_AUTH_DIGEST)
	    {
	      const char *http_method = "CONNECT";
	      const char *nonce_count = "00000001";
	      const char *qop = "auth";
	      const char *username = p->up.username;
	      const char *password = p->up.password;
	      char *opaque_kv = "";
	      char uri[128];
	      uint8_t cnonce_raw[8];
	      uint8_t *cnonce;
	      HASHHEX session_key;
	      HASHHEX response;

	      const char *realm = get_pa_var("realm", pa, &gc);
	      const char *nonce = get_pa_var("nonce", pa, &gc);
	      const char *algor = get_pa_var("algorithm", pa, &gc);
	      const char *opaque = get_pa_var("opaque", pa, &gc);

	      /* generate a client nonce */
	      ASSERT(rand_bytes(cnonce_raw, sizeof(cnonce_raw)));
	      cnonce = make_base64_string2(cnonce_raw, sizeof(cnonce_raw), &gc);


	      /* build the digest response */
	      openvpn_snprintf (uri, sizeof(uri), "%s:%d",
				host,
				port);

	      if (opaque)
		{
		  const int len = strlen(opaque)+16;
		  opaque_kv = gc_malloc(len, false, &gc);
		  openvpn_snprintf (opaque_kv, len, ", opaque=\"%s\"", opaque);
		}

	      DigestCalcHA1(algor,
			    username,
			    realm,
			    password,
			    nonce,
			    (char *)cnonce,
			    session_key);
	      DigestCalcResponse(session_key,
				 nonce,
				 nonce_count,
				 (char *)cnonce,
				 qop,
				 http_method,
				 uri,
				 NULL,
				 response);

	      /* format HTTP CONNECT message */
	      openvpn_snprintf (buf, sizeof(buf), "%s %s HTTP/%s",
				http_method,
				uri,
				p->options.http_version);

	      msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);

	      /* send HTTP CONNECT message to proxy */
	      if (!send_line_crlf (sd, buf))
		goto error;

	      /* send HOST etc, */
	      openvpn_snprintf (buf, sizeof(buf), "Host: %s", host);
	      msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);
	      if (!send_line_crlf (sd, buf))
		goto error;

	      /* send digest response */
	      openvpn_snprintf (buf, sizeof(buf), "Proxy-Authorization: Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", qop=%s, nc=%s, cnonce=\"%s\", response=\"%s\"%s",
				username,
				realm,
				nonce,
				uri,
				qop,
				nonce_count,
				cnonce,
				response,
				opaque_kv
				);
	      msg (D_PROXY, "Send to HTTP proxy: '%s'", buf);
	      if (!send_line_crlf (sd, buf))
		goto error;
	      if (!send_crlf (sd))
		goto error;

	      /* receive reply from proxy */
	      if (!recv_line (sd, buf, sizeof(buf), p->options.timeout, true, NULL, signal_received))
		goto error;

	      /* remove trailing CR, LF */
	      chomp (buf);

	      msg (D_PROXY, "HTTP proxy returned: '%s'", buf);

	      /* parse return string */
	      nparms = sscanf (buf, "%*s %d", &status);
	      processed = true;
	    }
	  else
	    {
	      msg (D_PROXY, "HTTP proxy: digest method not supported");
	      goto error;
	    }
	}
#endif
      else if (p->options.auth_retry)
	{
	  /* figure out what kind of authentication the proxy needs */
	  char *pa = NULL;
	  const int method = get_proxy_authenticate(sd,
						    p->options.timeout,
						    &pa,
						    NULL,
						    signal_received);
	  if (method != HTTP_AUTH_NONE)
	    {
	      if (pa)
		msg (D_PROXY, "HTTP proxy authenticate '%s'", pa);
	      if (p->options.auth_retry == PAR_NCT && method == HTTP_AUTH_BASIC)
		{
		  msg (D_PROXY, "HTTP proxy: support for basic auth and other cleartext proxy auth methods is disabled");
		  goto error;
		}
	      p->auth_method = method;
	      store_proxy_authenticate(p, pa);
	      ret = true;
	      goto done;
	    }
	  else
	    {
	      msg (D_PROXY, "HTTP proxy: do not recognize the authentication method required by proxy");
	      free (pa);
	      goto error;
	    }
	}
      else
	{
	  if (!processed)
	    msg (D_PROXY, "HTTP proxy: no support for proxy authentication method");
	  goto error;
	}

      /* clear state */
      if (p->options.auth_retry)
	clear_user_pass_http();
      store_proxy_authenticate(p, NULL);
    }

  /* check return code, success = 200 */
  if (nparms < 1 || status != 200)
    {
      msg (D_LINK_ERRORS, "HTTP proxy returned bad status");
#if 0
      /* DEBUGGING -- show a multi-line HTTP error response */
      dump_residual(sd, p->options.timeout, signal_received);
#endif
      goto error;
    }

  /* SUCCESS */

  /* receive line from proxy and discard */
  if (!recv_line (sd, NULL, 0, p->options.timeout, true, NULL, signal_received))
    goto error;

  /*
   * Toss out any extraneous chars, but don't throw away the
   * start of the OpenVPN data stream (put it in lookahead).
   */
  while (recv_line (sd, NULL, 0, 2, false, lookahead, signal_received))
    ;

  /* reset queried_creds so that we don't think that the next creds request is due to an auth error */
  p->queried_creds = false;

#if 0
  if (lookahead && BLEN (lookahead))
    msg (M_INFO, "HTTP PROXY: lookahead: %s", format_hex (BPTR (lookahead), BLEN (lookahead), 0));
#endif

 done:
  gc_free (&gc);
  return ret;

 error:
  /* on error, should we exit or restart? */
  if (!*signal_received)
    *signal_received = (p->options.retry ? SIGUSR1 : SIGTERM); /* SOFT-SIGUSR1 -- HTTP proxy error */
  gc_free (&gc);
  return ret;
}
Пример #25
0
void * do_crawler(void *item)
{
	char *url_ptr;
	int clientfd ;
	static int pages = 0;
	static int error = 0;
	char *buf = NULL;
	urlq_t *url_list_head = NULL, *p, *p_pre;
	char cur_dir[256];
	hash_table *hash_in, *hash_out;
/*	int tid = pthread_self();*/
	int j = 0;
	int i= 0;
	int pos_found = 0;
	char temp[256];
	int status = 0;
	static int a = 0;
	static int b = 0;
	static int c = 0;
	static int d = 0;
	static int e = 0;
	static int f = 0;
	static int g = 0;
	while(1){	
		pthread_mutex_lock(&mutex);
		while (urlqueue.head_ptr->next == NULL){
			pthread_cond_wait(&ready, &mutex);
		}

		pthread_mutex_lock(&((threadpool_item *)item)->waitlock);
		((threadpool_item *)item)->idle = 0;
		pthread_mutex_unlock(&((threadpool_item *)item)->waitlock);	
		url_ptr = queue_pop(&urlqueue);
		g++;
		pthread_mutex_unlock(&mutex);
		

		pthread_mutex_lock(&mutex);
		/*if not visited, set flag = 1*/
		if(has_visited(hash, url_ptr) == 1){
			pthread_mutex_unlock(&mutex);
			free(url_ptr); 
			pthread_mutex_lock(&((threadpool_item *)item)->waitlock);	
			((threadpool_item *)item)->idle =1;
			pthread_mutex_unlock(&((threadpool_item *)item)->waitlock);
			d++;	
			continue;	
		}
		hash_out = has_url(hash, url_ptr);
		e++;
		pthread_mutex_unlock(&mutex);
		if (hash_out == NULL){
			printf("error\n");
			getchar();
		}
		*temp = '\0';
		cur_dir[0] = '\0';
		strcpy(cur_dir, url_ptr);
		j = strlen(cur_dir);
		for (;cur_dir[j] != '/' && j != 0; j--) ;
		if(j == 0)
			cur_dir[j] = '\0';
		else
			cur_dir[j+1] = '\0';

		for (i = 0; i < 3; i++){
			if((clientfd = open_tcp("127.0.0.1", 80)) < 0){
				close_fd(clientfd);
				continue;
			}

			if( http_do_get(clientfd, rootdir, "127.0.0.1", url_ptr) < 0){
				close_fd(clientfd);
				continue;
			}

			if(recv_line(clientfd, temp) <= 0){
				close_fd(clientfd);
				continue;
			}
			if((status = http_response_status(temp))  == 4){
				printf("%s error %d\n",url_ptr, error++);
				pthread_mutex_lock(&mutex);
				set_status(hash, url_ptr, 4);
				set_webg_status(webg, hash_out, 4);
				pthread_mutex_unlock(&mutex);
			
				pthread_mutex_lock(&((threadpool_item *)item)->waitlock);	
				((threadpool_item *)item)->idle =1;
				pthread_mutex_unlock(&((threadpool_item *)item)->waitlock);	
				close_fd(clientfd);
				break;	
			}
			buf = http_response_body(clientfd);
			close_fd(clientfd);
			break;
		}
		if (status == 4)
			continue;
		if(i == 3){
			pthread_mutex_lock(&((threadpool_item *)item)->waitlock);	
			((threadpool_item *)item)->idle =1;
			pthread_mutex_unlock(&((threadpool_item *)item)->waitlock);	
			close_fd(clientfd);
			continue;	
		}
		if (buf == NULL){
			pthread_mutex_lock(&((threadpool_item *)item)->waitlock);	
			((threadpool_item *)item)->idle =1;
			pthread_mutex_unlock(&((threadpool_item *)item)->waitlock);	
			continue;
		}
		printf("%s pages %d\n", url_ptr,pages++);
		extract_link(buf, cur_dir, &url_list_head);
		free(buf);
		buf = NULL;	
		p = url_list_head->next;
		p_pre = url_list_head;
		while (p != NULL){
			
			if(strcmp(url_ptr, p->url_ptr) == 0){
				p_pre->next = p->next;
				free(p->url_ptr);
				free(p);
				a++;
				p = p_pre->next;
				printf("a= %d, b= %d, c= %d, d= %d, e= %d, f= %d, g= %d\n", a,b,c,d,e,f,g);
				continue;	
			}			
			pthread_mutex_lock(&mutex);
			hash_in = has_url(hash, p->url_ptr);	
			if (hash_in != NULL ){
				insert_edge(webg, hash_in, hash_out);
				pthread_mutex_unlock(&mutex);
				p_pre->next = p->next;
				free(p->url_ptr);
				free(p);
				p = p_pre->next;
				b++;
				printf("a= %d, b= %d, c= %d, d= %d, e= %d, f= %d, g= %d\n", a,b,c,d,e,f,g);
				continue;
			}
			else{
				pos_found = insert_vertex(webg, hash_out, p->url_ptr);
				insert_hash_item(hash, p->url_ptr, pos_found, 0);	
				pthread_mutex_unlock(&mutex);
				c++;
				p_pre = p;
				p = p->next;
				printf("a= %d, b= %d, c= %d, d= %d, e= %d, f= %d, g= %d\n", a,b,c,d,e,f,g);
			}
		}
		
		if(p_pre != url_list_head){
			pthread_mutex_lock(&mutex);
			queue_push(&urlqueue, url_list_head->next, p_pre);
			f++;
			pthread_mutex_unlock(&mutex);
		}
		free(url_list_head);
		p = p_pre = url_list_head = NULL;
	
		pthread_mutex_lock(&((threadpool_item *)item)->waitlock);	
		((threadpool_item *)item)->idle = 1;
		pthread_mutex_unlock(&((threadpool_item *)item)->waitlock);	
/*printf("next time!\n");*/
	}
/*printf("over!\n");*/
	return NULL;	
}
Пример #26
0
int recv_file (int sock) {
    int          recv_len;      // The number of bytes received from a recv
    char        *filename;
    FILE        *fp;            // The local file to write
    uint32_t     file_length;   // The length of the incoming file in bytes
    unsigned int i;
    byte         current_byte;  // The current byte received

    filename = (char *) malloc (MAX_LINE);

    // receive filename
    if (recv_line(sock, filename, MAX_LINE) <= 0) {
        return -1;
    }

    // Receive the incoming file length
    if (recv_uint32(sock, &file_length) <= 0)
        return -1;

    // Ensure that the file exists
    if (file_length == 0) {
        fprintf(stderr, "[!!] Remote file does not exist or is empty\n");
        return -1;
    }

#if DEBUG
    printf("Receiving %s | %d bytes | ... ", filename, file_length);
    fflush(stdout);
#endif

    // If it does exist, open a local copy as binary
    fp = fopen(filename, "wb+");
    if (!fp) {
        return -1;
    }

    // Loop over each byte and write the received byte to the local file
    for (i = 0; i < file_length; ++i) {
        recv_len = recv_byte(sock, &current_byte);
        if (recv_len <= 0) {
            fclose(fp);
            return -1;
        }

#if DEBUG
        printf("\rReceiving %s | %d bytes | %d%%... ", filename, file_length,
                (int) (100 * floor((i + 1) / file_length)));
        fflush(stdout);
#endif
        fwrite(&current_byte, 1, 1, fp);
    }

    // Close the local file when finished
    fclose(fp);
    free(filename);

#if DEBUG
    printf("Done.\n");
#endif
    return 0;
}
int do_communicate (const struct sockaddr_in *sock_addr_p, socklen_t addrlen, enum comm_complexity how)
{
  int result = 0;
  char *buf;
  static const size_t buf_size = 10 * 1024;

  buf = malloc (buf_size + 1); /* Extra byte for null-termination */
  if (NULL == buf)
  {
    result = 99;
    fprintf (stderr, "Error allocating memory for buffer.\n");
  }
  else
  {
    SYS_socket clnt_s;
    if (!sock_addr_p)
      return 99;
    clnt_s = socket (AF_INET, SOCK_STREAM, 0);
    if (SYS_INVALID_SOCKET == clnt_s)
    {
      fprintf (stderr, "Can't create socket: %u\n",
               (unsigned)SYS_sock_errno);
      result = 99;
    }
    else
    {
      char *str_addr;
      printf ("\nTrying communication sequence with server_part %s.\n", str_complexity (how));
      str_addr = inet_ntoa (sock_addr_p->sin_addr);
      if (!str_addr)
        str_addr = "server_part";

      printf ("Connecting to %s...\n", str_addr);
      if (connect (clnt_s, (const struct sockaddr*)sock_addr_p, addrlen) < 0)
      {
        fprintf (stderr, "Failed to connect: %u\n",
                 (unsigned)SYS_sock_errno);
        result = 99;
      }
      else
      {
        static const char data1[] = "FIRST PING\n";
        printf ("Connected. Sending \"FIRST PING\".\n");
        if (!send_str (clnt_s, data1, sizeof (data1) - 1))
        {
          result = 1;
          fprintf (stderr, "Error sending data.\n");
        }
        else
        {
          char *rcv_ptr;
          char *processed_ptr;
          const char *nl_ptr;

          rcv_ptr = buf;
          processed_ptr = buf;
          printf ("Sent. Waiting for receive \"FIRST PONG\".\n");
          nl_ptr = recv_line (clnt_s, &rcv_ptr, buf_size - (rcv_ptr - buf));
          if (!nl_ptr)
          {
            result = 1;
            fprintf (stderr, "Error receiving \"FIRST PONG\".\n");
          }
          else
          {
            rcv_ptr[0] = 0; /* Null-terminate for safety */
            printf ("Received: %*.*s\n", (int)(nl_ptr - processed_ptr), (int)(nl_ptr - processed_ptr), processed_ptr);
            if (!cmp_to_lower (processed_ptr, nl_ptr - processed_ptr, "first pong"))
            {
              result = 1;
              fprintf (stderr, "Expected marker not found in received data.\n");
            }
            else
            {
              static const char data2[] = "SECOND PING\n";
              processed_ptr = rcv_ptr;
              printf ("Sending \"SECOND PING\".\n");
              if (!send_str (clnt_s, data2, sizeof (data2) - 1))
              {
                result = 1;
                fprintf (stderr, "Error sending data.\n");
              }
              else
              {
                printf ("Sent.\n");
                if (how == COMM_DELAY || how == COMM_DELAY_ADD_DATA)
                {
                  printf ("Idling for delayed response receive...\n");
                  local_sleep (1500);
                }
                if (how == COMM_ADD_DATA || how == COMM_DELAY_ADD_DATA ||
                    how == COMM_ADD_DATA_TCPNDL || how == COMM_ADD_DATA_DELAY)
                {
                  static const char data_ign[] = "Additional data to be ignored.\n";
                  int on_val, off_val;

                  on_val = 1;
                  off_val = 0;
                  if (how == COMM_ADD_DATA_TCPNDL &&
                      0 != setsockopt (clnt_s, IPPROTO_TCP, TCP_NODELAY, (void*)&on_val, sizeof (on_val)))
                  {
                    result = 99;
                    fprintf(stderr,"Can't set TCP_ONDELAY option: %d.\n",
                            (unsigned)SYS_sock_errno);
                  }
                  printf ("Sending additional ignorable data.\n");
                  if (!send_str (clnt_s, data_ign, sizeof (data_ign) - 1))
                  {
                    printf ("Sending data failed.\n");
                  }
                  else
                  {
                    printf ("Sent.\n");
                  }
                }
                if (how == COMM_ADD_DATA_DELAY)
                {
                  printf ("Idling after additional sending for delayed response receive...\n");
                  local_sleep (1500);
                }
                printf ("Waiting for \"SECOND PONG\".\n");
                SYS_reset_sock_errno ();
                nl_ptr = recv_line (clnt_s, &rcv_ptr, buf_size - (rcv_ptr - buf));
                if (!nl_ptr)
                {
                  int err = SYS_sock_errno;
                  result = 1;
                  fprintf (stderr, "Error receiving \"SECOND PONG\".\n");
                  if (SYS_ECONNABORTED == err || SYS_ECONNRESET == err)
                    fprintf (stderr, "Looks like any received data was lost in system on this host after this system detected that connection was closed by remote side.\n");
                }
                else
                {
                  rcv_ptr[0] = 0; /* Null-terminate for safety */
                  printf ("Received: %*.*s\n", (int)(nl_ptr - processed_ptr), (int)(nl_ptr - processed_ptr), processed_ptr);
                  if (!cmp_to_lower (processed_ptr, nl_ptr - processed_ptr, "second pong"))
                  {
                    result = 1;
                    fprintf (stderr, "Expected marker not found in received data.\n");
                  }
                  else
                  {
                    printf ("Sequence completed.\n");
                  }
                }
              }
            }
          }
        }
      }
    }

    printf ("Closing connection.\n");
    SYS_socket_close_ (clnt_s);
  }

  if (result)
    fprintf (stderr, "Completed with some error.\n");
  else
    printf ("Completed without errors.\n");

  return result;
}
Пример #28
0
static void parse_stats(conn_t *conn, struct stats *stats, unsigned idx)
{
	char buf[1025];
	size_t j;
	struct timeval tv;
	unsigned conn_dt;
	int primary = 0;
	const char *pstart, *p, *vstart;

	if (conn->tcp)
		stats->remote = conn->remote;
	else
		stats->remote = "local";

	if (!conn->version) {
		stats->engine_version = strdup("???");
		return;
	}
	p = pstart = vstart = strchr(conn->version, ' ');
	if (!vstart) {
	    stats->engine_version = strdup("???");
	    return;
	}
	/* find digit in version */
	while (*p && !isdigit(*p))
		p++;
	/* rewind to first space or dash */
	while (p > pstart && *p && *p != ' ' && *p != '-')
		p--;
	if (*p) p++;
	/* keep only base version, and cut -exp, and -gittags */
	pstart = p;
	while (*p && *p != '-' && *p != '/')
		p++;

	stats->engine_version = malloc(p - pstart+1);
	OOM_CHECK(stats->engine_version);

	memcpy(stats->engine_version, pstart, p-pstart);
	stats->engine_version[p-pstart] = '\0';

	pstart = strchr(p, '/');
	if (!pstart)
		stats->db_version = strdup("????");
	else {
		pstart++;
		p = strchr(pstart, '/');
		if (!p)
			p = pstart + strlen(pstart);
		stats->db_version = malloc(p - pstart + 1);
		OOM_CHECK(stats->db_version);
		memcpy(stats->db_version, pstart, p-pstart);
		stats->db_version[p-pstart] = '\0';
		if(*p) p++;
		if (!*p || !strptime(p,"%a %b  %d %H:%M:%S %Y", &stats->db_time)) {
			memset(&stats->db_time, 0, sizeof(stats->db_time));
		}
	}
	if (maxx > 61 && strlen(stats->db_version) > (maxx-61)) {
		stats->db_version[maxx-61] = '\0';
	}

	stats->version = vstart; /* for details view */
	gettimeofday(&tv, NULL);
	tv.tv_sec -= conn->tv_conn.tv_sec;
	tv.tv_usec -= conn->tv_conn.tv_usec;
	conn_dt = tv.tv_sec + tv.tv_usec/1e6;

	stats->live = stats->idle = stats->max = 0;
	stats->conn_hr = conn_dt/3600;
	stats->conn_min = (conn_dt/60)%60;
	stats->conn_sec = conn_dt%60;
	stats->current_q = 0;
	buf[sizeof(buf) - 1] = 0x0;
	while(recv_line(conn, buf, sizeof(buf)-1) && strcmp("END\n",buf) != 0) {
		char *val = strchr(buf, ':');

		if(buf[0] == '\t') {
			parse_queue(conn, buf, sizeof(buf)-1, idx);
			continue;
		} else if(val)
			*val++ = '\0';
		if(!strcmp("MEMSTATS", buf)) {
			parse_memstats(val, stats);
			continue;
		}
		if(!strncmp("UNKNOWN COMMAND", buf, 15)) {
			stats->stats_unsupp = 1;
			break;
		}
		for(j=1;j<strlen(buf);j++)
			buf[j] = tolower(buf[j]);
	/*	mvwprintw(win, i, 0, "%s", buf);
		if(!val) {
			i++;
			continue;
		}
		waddch(win, ':');
		print_colored(win, val);
		i++;*/
		if(!strncmp("State",buf,5)) {
			if(strstr(val, "PRIMARY")) {
				/* primary thread pool */
				primary = 1;
			} else {
				/* multiscan pool */
				primary = 0;
			}
		}
		if(!strcmp("Threads",buf)) {
			unsigned live, idle, max;
			if(sscanf(val, " live %u idle %u max %u", &live, &idle, &max) != 3)
				continue;
			if (primary) {
				stats->prim_live = live;
				stats->prim_idle = idle;
				assert(!stats->prim_max && "There can be only one primary pool!");
				stats->prim_max = max;
			}
			stats->live += live;
			stats->idle += idle;
			stats->max += max;
		} else if (!strcmp("Queue",buf)) {
			unsigned len;
			if(sscanf(val, "%u", &len) != 1)
				continue;
			stats->current_q += len;
		}
	}
}
Пример #29
0
void handle_connection(int sockfd, struct sockaddr_in *client_addr_ptr) {
	unsigned char *ptr, request[500], resource[500];
	int fd, length;
	
	length = recv_line(sockfd, request);

	printf("Got request from %s:%d \"%s\"\n", inet_ntoa(client_addr_ptr->sin_addr),
			ntohs(client_addr_ptr->sin_port), request);
			
	ptr = strstr(request, " HTTP/"); // Search for valid-looking request.
	if(ptr == NULL) { // Then this isn't valid HTTP.
		printf(" NOT HTTP!\n");
	} else {
		*ptr = 0; // Terminate the buffer at the end of the URL.
		ptr = NULL; // Set ptr to NULL (used to flag for an invalid request).

		if(strncmp(request, "GET ", 4) == 0) // GET request
			ptr = request+4; // ptr is the URL.
		
		if(strncmp(request, "HEAD ", 5) == 0) // HEAD request
			ptr = request+5; // ptr is the URL.
			
		if(ptr == NULL) { // Then this is not a recognized request.
			printf("\tUNKNOWN REQUEST!\n");
		} else { /* valid request, with ptr pointing to resource name */
			if (ptr[strlen(ptr) - 1] == '/') // For resources ending with '/',
				strcat(ptr, "index.html"); // add 'index.html' to the end.
			strcpy(resource, WEBROOT); // Begin resource with web root path
			strcat(resource, ptr); // and join it with resource path.
			fd = open(resource, O_RDONLY, 0); // Try to open the file.
			printf("\tOpening \'%s\'\t", resource);
			
			if (fd == -1) { /* If file is not found */
				printf(" 404 Not Found\n");
				send_string(sockfd, "HTTP/1.0 404 NOT FOUND\r\n");
				send_string(sockfd, "Server: Ironman HTTP Server\r\n\r\n");
				send_string(sockfd, "<html><head><title>Error: 404 File Not Found on the server</title></head>");
				send_string(sockfd, "<body><h1>URL not found</h1></body></html>\r\n");
				send_string(sockfd, "<body><h2>Ironman HTTP Server\r\n\r\n");
			} else { /* Otherwise, serve up the file */
				printf(" 200 OK\n");
				send_string(sockfd, "HTTP/1.0 200 OK\r\n");
				send_string(sockfd, "Server: Ironman HTTP Server\r\n\r\n");
				
				if(ptr == request + 4) { // Then this is a GET request
					if( (length = get_file_size(fd)) == -1)
						error("getting resource file size", 1);
					
					if( (ptr = (unsigned char *) malloc(length)) == NULL)
						error("allocating memory for reading resource", 2);

					read(fd, ptr, length); // Read the file into memory.
					send(sockfd, ptr, length, 0); // Send it to socket.
					free(ptr); /* Free file memory. */
				}
				
				close(fd); /* Close the file. */
			} /* End if block for file found/not found. */
		} /* End if block for valid request. */
	} /* End if block for valid HTTP. */
	
	shutdown(sockfd, SHUT_RDWR); /* Close the socket gracefully. */
}
Пример #30
0
int main(void) {
	int sockfd, new_sockfd;  // listen on sock_fd, new connection on new_fd
	struct sockaddr_in host_addr, client_addr;	// my address information
	socklen_t sin_size;
	int recv_length=1, yes=1;
	char buffer[1024]; /* pour recevoir le lux streaming */
	char buf1[256];  /* Pour recevoir les données information */
	int longueur;
	int j, nbpaquets,cptpaquets;
 
		

	if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
		fatal("in socket");

	if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
		fatal("setting socket option SO_REUSEADDR");
	
	host_addr.sin_family = AF_INET;		 // host byte order
	host_addr.sin_port = htons(PORT);	 // short, network byte order
	host_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
	memset(&(host_addr.sin_zero), '\0', 8); // zero the rest of the struct

	if (bind(sockfd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1)
		fatal("binding to socket");

	if (listen(sockfd, 5) == -1)
		fatal("listening on socket");

	while(1) {    // Accept loop
		sin_size = sizeof(struct sockaddr_in);
		new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);
		if(new_sockfd == -1)
			fatal("accepting connection");
		printf("server: got connection from %s port %d\n",inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
		
		
		
		send_string(new_sockfd, "Hello World! Quel fichier audio, please?\r\n");
		
		/*************************************************************/
		/*  VOUS INTERVENEZ ICI                                      */
		/*  Cette partie du programme doit                           */
		/*      - receptionner le nom du fichier audio envoye par    */
		/*        client_audio                                       */
		/*      - afficher le nom du fichier audio demande           */
		/*      - lancer main_wave(new_sockfd,nom_fichier_audio) pour lire les paquets */
		/*        jusqu'a la fin du fichier audio ou bien la         */
		/*        la deconnexion du client                           */
		/*************************************************************/
		printf("On attend la demande\n");
		//réception du fichier audio
		recv_line(new_sockfd, buffer);
		//on affiche le fichier demandé
		printf("Vous avez demande : %s\n", buffer);

		main_wave(new_sockfd,buffer);
	
		
		}
		
		close(new_sockfd);
	
	return 0;
}