Example #1
1
int main(int argc, char *argv[])
{
     //Validate the input
     if (argc < 2) 
     {
          printf("\nUsage: %s port.", argv[0]);
          goto error;
     }
     
     // Initialize Winsock
     WSADATA wsaData;
     
     int nResult;
     
     nResult = WSAStartup(MAKEWORD(2,2), &wsaData);
     
     if (NO_ERROR != nResult)
     {
          printf("\nError occurred while executing WSAStartup().");
          return 1; //error
     }
     else
     {
          printf("\nWSAStartup() successful.");
     }
     
     SOCKET ListenSocket, RemoteSocket; 
     int    nPortNo, nClientLength;
     
     char szBuffer[256];
     struct sockaddr_in ServerAddress, ClientAddress;
     
     //Create a socket
     ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
     
     if (INVALID_SOCKET == ListenSocket) 
     {
          printf("\nError occurred while opening socket: %ld.", WSAGetLastError());
          goto error;
     }
     else
     {
          printf("\nsocket() successful.");
     }
     
     //Cleanup and Init with 0 the ServerAddress
     ZeroMemory((char *)&ServerAddress, sizeof(ServerAddress));
     
     //Port number will be supplied as a commandline argument
     nPortNo = atoi(argv[1]);
     
     
     //Fill up the address structure
     ServerAddress.sin_family = AF_INET;
     ServerAddress.sin_addr.s_addr = INADDR_ANY; //WinSock will supply address
     ServerAddress.sin_port = htons(nPortNo);    //comes from commandline
     
     //Assign local address and port number
     if (SOCKET_ERROR == bind(ListenSocket, (struct sockaddr *) &ServerAddress, sizeof(ServerAddress))) 
     {
          closesocket(ListenSocket);
          
          printf("\nError occurred while binding.");
          goto error;
     }
     else
     {
          printf("\nbind() successful.");
     }
     
     //Make the socket a listening socket
     if (SOCKET_ERROR == listen(ListenSocket,SOMAXCONN))
     {
          closesocket(ListenSocket);
          
          printf("\nError occurred while listening.");
          goto error;
     }
     else
     {
          printf("\nlisten() successful.");
     }
     
     nClientLength = sizeof(ClientAddress);
     
     //Accept remote connection attempt from the client
     RemoteSocket = accept(ListenSocket, (struct sockaddr *) &ClientAddress, &nClientLength);
     
     if (INVALID_SOCKET == RemoteSocket)
     {
          closesocket(ListenSocket);
          
          printf("\nError occurred while accepting socket: %ld.", WSAGetLastError());
          goto error;
     }
     else
     {
          printf("\naccept() successful.");
     }
     
     //Display Client's IP
     printf("\nClient connected from: %s", inet_ntoa(ClientAddress.sin_addr));
     
     //Cleanup and Init with 0 the szBuffer
     ZeroMemory(szBuffer,256);
     
     int nBytesSent;
     int nBytesRecv;
     
     //Receive data from a connected or bound socket
     nBytesRecv = recv(RemoteSocket, szBuffer, 255, 0 );
     
     if (SOCKET_ERROR == nBytesRecv)
     {
          closesocket(ListenSocket);
          closesocket(RemoteSocket);
          
          printf("\nError occurred while receiving from socket.");
          goto error;
     }
     else
     {
          printf("\nrecv() successful.");
     }
     
     //Display the message received on console
     printf("\nThe following message was received: %s", szBuffer);
     
     //Send data on a connected socket to the client
     nBytesSent = send(RemoteSocket, ACK_MESG_RECV , strlen(ACK_MESG_RECV), 0);
     
     if (SOCKET_ERROR == nBytesSent) 
     {
          closesocket(ListenSocket);
          closesocket(RemoteSocket);
          
          printf("\nError occurred while writing to socket.");
          goto error;
     }
     else
     {
          printf("\nsend() successful.");
     }
     
     //Close open sockets
     closesocket(ListenSocket);
     closesocket(RemoteSocket);
     
     //Cleanup Winsock
     WSACleanup();
     return 0; //success
     
error:
     // Cleanup Winsock
     WSACleanup();
     return 1; //error
}
Example #2
1
/* Display an Internet socket address. */
static char *INET_print(unsigned char *ptr)
{
    return (inet_ntoa((*(struct in_addr *) ptr)));
}
Example #3
1
int main(void)
{
	signal(SIGCHLD, SigchldHandler);
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (-1 == sockfd) {
		perror("Socket error:\n");
		return -1;
	}
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(SERVER_PORT);
	addr.sin_addr.s_addr = inet_addr(SERVER_IP);
	int optval = 1;
	if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) {
		perror("Set socket option error:\n");
	}
	if (-1 == bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))) {
		perror("Bind error:\n");
		return -1;
	}
	if (-1 == listen(sockfd, SOMAXCONN)) {
		perror("Listen error:\n");
		return -1;
	}
	while (1) {
		struct sockaddr_in clientaddr;
		socklen_t socklen = sizeof(clientaddr);
		int connfd = accept(sockfd, (struct sockaddr *)&clientaddr, &socklen);
		pid_t pid = fork();
		if (-1 == pid) {
			perror("Create process error:\n");
			exit(-1);	
		}
		else if (0 == pid) { //child process
			if (-1 == connfd) {
				perror("Accept error:\n");
				return -1;
			}
			printf("child process.\n");
			printf("client address %s.\n", inet_ntoa(clientaddr.sin_addr));
			while (1) {
				char recbuffer[1024] = {0};
				int readlen = read(connfd, recbuffer, sizeof(recbuffer));	
				if (-1 == readlen) {
					if (EINTR == errno) {
						continue;
					}
					//return - 1;
					exit(-1);
				}
				else if (0 == readlen) {
					printf("Client close.\n");
					close(connfd);
					exit(0);
				}
				else {
//					if (recbuffer[0] == 'c') {
//						close(connfd);
//						exit(0);
//					}
					printf("recv %s.\n", recbuffer);
					int writelen = write(connfd, recbuffer, strlen(recbuffer));
					if (-1 == writelen) {
						if (EINTR == errno) {
							continue;
						}
						close(connfd);
						//shutdown(connfd, SHUT_RDWR);
						exit(-1);
					}
					else if (writelen > 0) {
						//TODO something
					}
					else {
					}
					memset(recbuffer, 0, sizeof(recbuffer));
				}
			}
		}
		else if (pid > 0) { //parent process
			close(connfd);
		}
	}
	return 0;
}
Example #4
0
int server(uint16_t port) 
{
	struct sockaddr_in client_addr;
	struct sockaddr_in server_addr; 
	char msg[MAX_MSG_LENGTH], reply[MAX_MSG_LENGTH];
	int server_socket;
	int new_socket;
	int len;

	/* Configuring the server_addr */
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);
	server_addr.sin_addr.s_addr = INADDR_ANY;

	/* Creating the server socket using SOCK_STREAM and TCP PROTOCOL */
	if ((server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
		perror("Create socket error (server):");
		return 1;
	}
	printf("Server's Socket created!\n");

	/* Binding the socket to the server's address */
	if ((bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr))) < 0) {
		perror("Error binding socket to client address in server");
		exit(1);
	}
	printf("Server's Bind successful!\n");
	
	/* Allowing the server to listen to a max of MAX_CLIENTS = 1 */
	if (listen(server_socket, MAX_CLIENTS) < 0) {
		perror("Error setting up listen");
	}

	memset(&client_addr.sin_addr, 0, sizeof(client_addr.sin_addr));
	len = sizeof(client_addr);

	/* Listening for a connection from a client */
	if ((new_socket = accept(server_socket, (struct sockaddr *)&client_addr, &len)) < 0) {
		perror("Error w/ server accepting connection");
		exit(1);				
	} else {
		printf("Accepted connection from: %s\n", inet_ntoa(client_addr.sin_addr));
	}

	while (1) {
		len = sizeof(client_addr);

		/* recv() is the method that gets the input from the client, we store return value so we know the status */
		int recv_len = recv(new_socket, reply, MAX_MSG_LENGTH, 0);

		if (recv_len <= 0) { /* Only called when client receives error or client disconnected */
			if (recv_len == 0) {
				printf("Client disconnected\n");
				/* Upon client disconnecting, server waits to accept the next client */
				if ((new_socket = accept(server_socket, (struct sockaddr *)&client_addr, &len)) < 0) {
					perror("Error w/ server accepting connection");
					exit(1);				
				} else {
					printf("Accepted connection from: %s\n", inet_ntoa(client_addr.sin_addr));
				}
			} else {
				perror("Recv error:");
				return 1;				
			}
		} else { 
			/* This is the case when recv_len > 0, which signals the server received a valid reply from client */
			printf("Received message from client: %s\n", reply);
		}

		/* This is part of the "echo" server where server returns the client's message */
		if (send(new_socket, reply, strnlen(reply, MAX_MSG_LENGTH), 0) < 0) {
			perror("Send error:");
			return 1;
		}

		/* Clearing the reply buffer with 0's for the next reply */
		memset(&reply[0], 0, sizeof(reply));
	}

	return 0;
}
Example #5
0
/*------------------------------------------------------------------------
 * MAIN PROGRAM
 *------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
    int                server_fd, client_fd;
    struct sockaddr_in remote_address;
    socklen_t          remote_length = sizeof(struct sockaddr_in);
    ttp_parameter_t    parameter;
    ttp_session_t      session;
    pid_t              child_pid;

    /* initialize our parameters */
    memset(&session, 0, sizeof(session));
    reset_server(&parameter);

    /* process our command-line options */
    process_options(argc, argv, &parameter);

    /* obtain our server socket */
    server_fd = create_tcp_socket(&parameter);
    if (server_fd < 0) {
        sprintf(g_error, "Could not create server socket on port %d", parameter.tcp_port);
        return error(g_error);
    }

    /* install a signal handler for our children */
    signal(SIGCHLD, reap);

    /* now show version / build information */
    #ifdef VSIB_REALTIME
    fprintf(stderr, "Tsunami Realtime Server for protocol rev %X\nRevision: %s\nCompiled: %s %s\n"
                    "   /dev/vsib VSIB accesses mode=%d, sample skip=%d, gigabit=%d, 1pps embed=%d\n"
                    "Waiting for clients to connect.\n",
            PROTOCOL_REVISION, TSUNAMI_CVS_BUILDNR, __DATE__ , __TIME__,
            vsib_mode, vsib_mode_skip_samples, vsib_mode_gigabit, vsib_mode_embed_1pps_markers);
    #else
    fprintf(stderr, "Tsunami Server for protocol rev %X\nRevision: %s\nCompiled: %s %s\n"
                    "Waiting for clients to connect.\n",
            PROTOCOL_REVISION, TSUNAMI_CVS_BUILDNR, __DATE__ , __TIME__);
    #endif

    /* while our little world keeps turning */
    while (1) {

        /* accept a new client connection */
        client_fd = accept(server_fd, (struct sockaddr *) &remote_address, &remote_length);
        if (client_fd < 0) {
            warn("Could not accept client connection");
            continue;
        } else {
            fprintf(stderr, "New client connecting from %s...\n", inet_ntoa(remote_address.sin_addr));
        }

        /* and fork a new child process to handle it */
        child_pid = fork();
        if (child_pid < 0) {
            warn("Could not create child process");
            continue;
        }
        session.session_id++;

        /* if we're the child */
        if (child_pid == 0) {

            /* close the server socket */
            close(server_fd);

            /* set up the session structure */
            session.client_fd = client_fd;
            session.parameter = &parameter;
            memset(&session.transfer, 0, sizeof(session.transfer));
            session.transfer.ipd_current = 0.0;

            /* and run the client handler */
            client_handler(&session);
            return 0;

        /* if we're the parent */
        } else {

            /* close the client socket */
            close(client_fd);
        }
    }
}
Example #6
0
int main (int argc, char *argv[])
{
	ROT *my_rot;		/* handle to rot (instance) */
	rot_model_t my_model = ROT_MODEL_DUMMY;

	int retcode;		/* generic return code from functions */

	int verbose = 0;
	int show_conf = 0;
	int dump_caps_opt = 0;
	const char *rot_file=NULL;
	int serial_rate = 0;
	char conf_parms[MAXCONFLEN] = "";

	struct addrinfo hints, *result;
	int sock_listen;
	int reuseaddr = 1;

	while(1) {
		int c;
		int option_index = 0;

		c = getopt_long (argc, argv, SHORT_OPTIONS,
			long_options, &option_index);
		if (c == -1)
			break;

		switch(c) {
			case 'h':
				usage();
				exit(0);
			case 'V':
				version();
				exit(0);
			case 'm':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				my_model = atoi(optarg);
				break;
			case 'r':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				rot_file = optarg;
				break;
			case 's':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				serial_rate = atoi(optarg);
				break;
			case 'C':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				if (*conf_parms != '\0')
					strcat(conf_parms, ",");
				strncat(conf_parms, optarg, MAXCONFLEN-strlen(conf_parms));
				break;
			case 't':
				if (!optarg) {
					usage();        /* wrong arg count */
					exit(1);
				}
				portno = optarg;
				break;
			case 'T':
				if (!optarg) {
					usage();	/* wrong arg count */
					exit(1);
				}
				src_addr = optarg;
				break;
			case 'v':
				verbose++;
				break;
			case 'L':
				show_conf++;
				break;
			case 'l':
				list_models();
				exit(0);
			case 'u':
				dump_caps_opt++;
				break;
			case 'e':
				opt_end = 1;
				fprintf(stderr, "-e|--end-marker option is deprecated!\nPlease consider using the Extended Response protocol instead.\n");
				break;
			default:
				usage();	/* unknown option? */
				exit(1);
		}
	}

	rig_set_debug(verbose);

	rig_debug(RIG_DEBUG_VERBOSE, "rotctld, %s\n", hamlib_version);
	rig_debug(RIG_DEBUG_VERBOSE, "Report bugs to "
			"<*****@*****.**>\n\n");

  	my_rot = rot_init(my_model);

	if (!my_rot) {
		fprintf(stderr, "Unknown rot num %d, or initialization error.\n",
						my_model);
		fprintf(stderr, "Please check with --list option.\n");
		exit(2);
	}

	retcode = set_conf(my_rot, conf_parms);
	if (retcode != RIG_OK) {
		fprintf(stderr, "Config parameter error: %s\n", rigerror(retcode));
		exit(2);
	}

	if (rot_file)
		strncpy(my_rot->state.rotport.pathname, rot_file, FILPATHLEN - 1);

	/* FIXME: bound checking and port type == serial */
	if (serial_rate != 0)
		my_rot->state.rotport.parm.serial.rate = serial_rate;

	/*
	 * print out conf parameters
	 */
	if (show_conf) {
		rot_token_foreach(my_rot, print_conf_list, (rig_ptr_t)my_rot);
	}

	/*
	 * print out conf parameters, and exits immediately
	 * We may be interested only in only caps, and rig_open may fail.
	 */
	if (dump_caps_opt) {
		dumpcaps_rot(my_rot, stdout);
		rot_cleanup(my_rot); /* if you care about memory */
		exit(0);
	}

	retcode = rot_open(my_rot);
	if (retcode != RIG_OK) {
	  	fprintf(stderr,"rot_open: error = %s \n", rigerror(retcode));
		exit(2);
	}

	if (verbose > 0)
		printf("Opened rot model %d, '%s'\n", my_rot->caps->rot_model,
						my_rot->caps->model_name);

	rig_debug(RIG_DEBUG_VERBOSE, "Backend version: %s, Status: %s\n",
			my_rot->caps->version, rig_strstatus(my_rot->caps->status));

#ifdef __MINGW32__
# ifndef SO_OPENTYPE
#  define SO_OPENTYPE     0x7008
# endif
# ifndef SO_SYNCHRONOUS_NONALERT
#  define SO_SYNCHRONOUS_NONALERT 0x20
# endif
# ifndef INVALID_SOCKET
#  define INVALID_SOCKET -1
# endif

	WSADATA wsadata;
	if (WSAStartup(MAKEWORD(1,1), &wsadata) == SOCKET_ERROR) {
		fprintf(stderr,"WSAStartup socket error\n");
		exit(1);
	}

	int sockopt = SO_SYNCHRONOUS_NONALERT;
	setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&sockopt, sizeof(sockopt));
#endif

	/*
	 * Prepare listening socket
	 */
	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
	hints.ai_socktype = SOCK_STREAM;/* TCP socket */
	hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
	hints.ai_protocol = 0;          /* Any protocol */

	retcode = getaddrinfo(src_addr, portno, &hints, &result);
	if (retcode != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(retcode));
		exit(2);
	}

	sock_listen = socket(result->ai_family, result->ai_socktype,
			result->ai_protocol);
	if (sock_listen < 0)  {
		perror("ERROR opening socket");
		exit(1);
	}

	if (setsockopt(sock_listen, SOL_SOCKET, SO_REUSEADDR,
				(char *)&reuseaddr,sizeof(reuseaddr)) < 0) {
		rig_debug(RIG_DEBUG_ERR, "setsockopt: %s\n", strerror(errno));
		exit (1);
	}
	if (bind(sock_listen, result->ai_addr, result->ai_addrlen) < 0) {
		rig_debug(RIG_DEBUG_ERR, "binding: %s\n", strerror(errno));
		exit (1);
	}

	freeaddrinfo(result);           /* No longer needed */

	if (listen(sock_listen,4) < 0) {
		rig_debug(RIG_DEBUG_ERR, "listening: %s\n", strerror(errno));
		exit (1);
	}

	/*
	 * main loop accepting connections
	 */
	do {
#ifdef HAVE_PTHREAD
		pthread_t thread;
		pthread_attr_t attr;
#endif
		struct handle_data *arg;

		arg = malloc(sizeof(struct handle_data));
		if (!arg) {
			rig_debug(RIG_DEBUG_ERR, "malloc: %s\n", strerror(errno));
			exit (1);
		}

		arg->rot = my_rot;
		arg->clilen = sizeof(arg->cli_addr);
		arg->sock = accept(sock_listen, (struct sockaddr *) &arg->cli_addr,
				&arg->clilen);
		if (arg->sock < 0) {
			rig_debug(RIG_DEBUG_ERR, "accept: %s\n", strerror(errno));
			break;
		}

		rig_debug(RIG_DEBUG_VERBOSE, "Connection opened from %s:%d\n",
				inet_ntoa(arg->cli_addr.sin_addr),
				ntohs(arg->cli_addr.sin_port));

#ifdef HAVE_PTHREAD
		pthread_attr_init(&attr);
		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

		retcode = pthread_create(&thread, &attr, handle_socket, arg);
		if (retcode != 0) {
			rig_debug(RIG_DEBUG_ERR, "pthread_create: %s\n", strerror(retcode));
			break;
		}
#else
		handle_socket(arg);
#endif
	}
	while (retcode == 0);

	rot_close(my_rot); /* close port */
	rot_cleanup(my_rot); /* if you care about memory */

#ifdef __MINGW32__
	WSACleanup();
#endif

	return 0;
}
Example #7
0
static void mca_btl_tcp_endpoint_dump(mca_btl_base_endpoint_t* btl_endpoint, const char* msg)
{
    char src[64];
    char dst[64];
    int sndbuf,rcvbuf,nodelay,flags;
#if OPAL_WANT_IPV6
    struct sockaddr_storage inaddr;
#else
    struct sockaddr_in inaddr;
#endif
    opal_socklen_t obtlen;
    opal_socklen_t addrlen = sizeof(inaddr);

    getsockname(btl_endpoint->endpoint_sd, (struct sockaddr*)&inaddr, &addrlen);
#if OPAL_WANT_IPV6
    {
        char *address;
        address = (char *) opal_net_get_hostname((struct sockaddr*) &inaddr);
        if (NULL != address) {
            sprintf(src, "%s", address);
        }
    }
#else
    sprintf(src, "%s", inet_ntoa(inaddr.sin_addr));
#endif
    getpeername(btl_endpoint->endpoint_sd, (struct sockaddr*)&inaddr, &addrlen);
#if OPAL_WANT_IPV6
    {
        char *address;
        address = (char *) opal_net_get_hostname ((struct sockaddr*) &inaddr);
        if (NULL != address) {
            sprintf(dst, "%s", address);
        }
    }
#else
    sprintf(dst, "%s", inet_ntoa(inaddr.sin_addr));
#endif

    if((flags = fcntl(btl_endpoint->endpoint_sd, F_GETFL, 0)) < 0) {
        BTL_ERROR(("fcntl(F_GETFL) failed: %s (%d)", 
                   strerror(opal_socket_errno), opal_socket_errno));
    }

#if defined(SO_SNDBUF)
    obtlen = sizeof(sndbuf);
    if(getsockopt(btl_endpoint->endpoint_sd, SOL_SOCKET, SO_SNDBUF, (char *)&sndbuf, &obtlen) < 0) {
        BTL_ERROR(("SO_SNDBUF option: %s (%d)",
                   strerror(opal_socket_errno), opal_socket_errno));
    }
#else
    sndbuf = -1;
#endif
#if defined(SO_RCVBUF)
    obtlen = sizeof(rcvbuf);
    if(getsockopt(btl_endpoint->endpoint_sd, SOL_SOCKET, SO_RCVBUF, (char *)&rcvbuf, &obtlen) < 0) {
        BTL_ERROR(("SO_RCVBUF option: %s (%d)", 
                   strerror(opal_socket_errno), opal_socket_errno));
    }
#else
    rcvbuf = -1;
#endif
#if defined(TCP_NODELAY)
    obtlen = sizeof(nodelay);
    if(getsockopt(btl_endpoint->endpoint_sd, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, &obtlen) < 0) {
        BTL_ERROR(("TCP_NODELAY option: %s (%d)", 
                   strerror(opal_socket_errno), opal_socket_errno));
    }
#else
    nodelay = 0;
#endif

    BTL_VERBOSE(("%s: %s - %s nodelay %d sndbuf %d rcvbuf %d flags %08x", 
        msg, src, dst, nodelay, sndbuf, rcvbuf, flags));
}
Example #8
0
int main(void){
    
    int server_Socket, accept_Socket;
    unsigned int length, count;
    struct sockaddr_in server_Struct, client_Struct;
    char got_charachter[1000];
    char web_Site[]="HTTP/1.1 200 OK\r\n\r\n";
    unsigned short int port_No=5000;
    char *position_of_GET,*position_of_HTTP;
    char nameof_File[100];
    
    server_Socket=socket(AF_INET,SOCK_STREAM,0);
    
    
    server_Struct.sin_family=AF_INET;
    server_Struct.sin_addr.s_addr=htonl(INADDR_ANY);
    server_Struct.sin_port=htons(port_No);
    length=sizeof(server_Struct);
   
    
    printf("\n Server is now binding....");
    bind(server_Socket,(struct sockaddr *)&server_Struct,length);
   
    printf("\n Server listen....");
    //printf("\n Server mit IP %s on port %d ",ip_Adress,port_No);
    listen(server_Socket,5);
    
    while(1){
        
        printf("\n Server accept.....");
        fflush(stdout);
        accept_Socket=accept(server_Socket,(struct sockaddr *)&client_Struct, &length);
      
        printf(" connected to %s",inet_ntoa(client_Struct.sin_addr));
        
        count=read(accept_Socket,got_charachter,sizeof(got_charachter));
        got_charachter[count]=0;
        printf("server got the charachters %s",got_charachter);
        
        
       if(position_of_GET=strstr(got_charachter,"GET"))
       {
         printf("\n GET command start at char %ld\n\n",(position_of_GET-got_charachter)+1);
              if(position_of_HTTP=strstr(got_charachter,"HTTP"))
              {
                printf("\n GET command start at char %ld\n\n",(position_of_HTTP-got_charachter)+1);
                length=position_of_HTTP-position_of_GET-6;
                strncpy(nameof_File,position_of_GET+4,length+1);
                nameof_File[length+1]=0;
                printf("\n The name of File you asked for %s is not available at this moment",nameof_File);
              }
                else
              {
                      printf("\n HTTP has no HTTP \n\n");
              }
       }
       else
       {
           printf("\n HTTP has no GET \n\n");
       }
       
       printf("\n\n\n");
        write(accept_Socket,web_Site,sizeof(web_Site));
        printf("\n\n server close()....");
        close(accept_Socket);
    
        
        
        
    }

    
    
    
    
    return (0);
}
Example #9
0
int main(int argc, char **argv)
{
	/* The following things are used for getopt: */
	extern char *optarg;
	extern int optind;
	extern int opterr;
	int ch;

        in_addr_t dest;
        struct sockaddr_in destaddr,fromaddr,servaddr;
        socklen_t fromlen;
        int sockfd_r;
        struct hostent *hp;
        char *buf;
        char dest_str[16];
#define RBLEN 500
        char recbuf[RBLEN+1];
        ssize_t recmegslen;


        fromlen = sizeof(fromaddr); // this is important otherwise recvfrom will return "Invalid argument"
	opterr = 0;
	while ((ch = getopt(argc, argv, "hp:")) != -1) {
		switch (ch) {
			case 'p':
				sscanf(optarg,"%d",&portnum);
				break;
			case 'h':
				help();
			case '?':
				fprintf(stderr, "ERROR: No such option. -h for help.\n");
				exit(1);
			/*no default action for case */
			}
	}
	if (optind != argc -2){
		/* exactly two arguments must be given */
		help();
	}
        if (strlen(argv[optind])>45){
                fprintf(stderr,"Error: command too long. Max is 45\n");
                exit(1);
        }
        buf=argv[optind];
        //
        hp=gethostbyname(argv[optind+1]);
        if (hp==NULL){
                fprintf(stderr,"Error: %s is not a IP address and not a resolvable hostname\n",argv[optind+1]);
                exit(1);
        }
        // take the first address:
        strncpy(dest_str,inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]),sizeof(dest_str));
        dest_str[sizeof(dest_str)-1]='\0';
        dest=inet_addr(dest_str);
        if (dest==INADDR_NONE){
                fprintf(stderr,"Error: IP addr. not valid\n");
                exit(1);
        }
        //
        printf("II: data: %s, ip: %s port: %d\n",argv[optind],dest_str,portnum);
        /* initialize the socket address for the destination: */
        destaddr.sin_family = AF_INET;
        destaddr.sin_addr.s_addr = dest;
        destaddr.sin_port = htons(portnum); // dest port
        /* initialize the socket address for this server: */
        servaddr.sin_family = AF_INET;
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 
        servaddr.sin_port = htons(portnum); // source port
	memset(&servaddr.sin_zero, 0, sizeof(servaddr.sin_zero)); // zero fill

        if ((sockfd_r = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
        {
                perror("open socket failed");
                exit(1);
        }
        if (bind(sockfd_r, (struct sockaddr *)&servaddr, sizeof(servaddr))){
                perror("bind socket failed");
                exit(1);
        }
        // we are bound. The parent will get the message even if the sender
	// sends it before we call recvfrom
	/* the closing \0 will be sent as well: */
	if(sendto(sockfd_r,buf,strlen(buf)+1,0,(struct sockaddr *)&destaddr,sizeof(destaddr)) == -1){
		perror("sendto failed");
		exit(1);
	}
        // we will timeout if there is no answer after a few sec
        signal(SIGALRM, &timeout_handler);
        alarm(3);
        recmegslen=recvfrom(sockfd_r,recbuf,RBLEN-1,0,(struct sockaddr *)&fromaddr,&fromlen);
        if(recmegslen == -1){
                perror("recvfrom failed");
                exit(1);
        }
        close(sockfd_r);
        recbuf[recmegslen]='\0';
        printf("OK: %s: %s\n",inet_ntoa(fromaddr.sin_addr),recbuf);
        //
        return(0);
}
Example #10
0
int
main(int argc, char **argv)
{
    struct rk_dns_reply *r;
    struct rk_resource_record *rr;
    int optidx = 0;

    setprogname (argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage (0);

    if(version_flag){
	printf("some version\n");
	exit(0);
    }

    argc -= optidx;
    argv += optidx;

    if (argc != 2)
	usage(1);

    r = rk_dns_lookup(argv[0], argv[1]);
    if(r == NULL){
	printf("No reply.\n");
	return 1;
    }
    if(r->q.type == rk_ns_t_srv)
	rk_dns_srv_order(r);

    for(rr = r->head; rr;rr=rr->next){
	printf("%-30s %-5s %-6d ", rr->domain, rk_dns_type_to_string(rr->type), rr->ttl);
	switch(rr->type){
	case rk_ns_t_ns:
	case rk_ns_t_cname:
	case rk_ns_t_ptr:
	    printf("%s\n", (char*)rr->u.data);
	    break;
	case rk_ns_t_a:
	    printf("%s\n", inet_ntoa(*rr->u.a));
	    break;
	case rk_ns_t_mx:
	case rk_ns_t_afsdb:{
	    printf("%d %s\n", rr->u.mx->preference, rr->u.mx->domain);
	    break;
	}
	case rk_ns_t_srv:{
	    struct rk_srv_record *srv = rr->u.srv;
	    printf("%d %d %d %s\n", srv->priority, srv->weight,
		   srv->port, srv->target);
	    break;
	}
	case rk_ns_t_txt: {
	    printf("%s\n", rr->u.txt);
	    break;
	}
	case rk_ns_t_sig : {
	    struct rk_sig_record *sig = rr->u.sig;
	    const char *type_string = rk_dns_type_to_string (sig->type);

	    printf ("type %u (%s), algorithm %u, labels %u, orig_ttl %u, sig_expiration %u, sig_inception %u, key_tag %u, signer %s\n",
		    sig->type, type_string ? type_string : "",
		    sig->algorithm, sig->labels, sig->orig_ttl,
		    sig->sig_expiration, sig->sig_inception, sig->key_tag,
		    sig->signer);
	    break;
	}
	case rk_ns_t_key : {
	    struct rk_key_record *key = rr->u.key;

	    printf ("flags %u, protocol %u, algorithm %u\n",
		    key->flags, key->protocol, key->algorithm);
	    break;
	}
	case rk_ns_t_sshfp : {
	    struct rk_sshfp_record *sshfp = rr->u.sshfp;
	    size_t i;

	    printf ("alg %u type %u length %lu data ", sshfp->algorithm,
		    sshfp->type,  (unsigned long)sshfp->sshfp_len);
	    for (i = 0; i < sshfp->sshfp_len; i++)
		printf("%02X", sshfp->sshfp_data[i]);
	    printf("\n");

	    break;
	}
	case rk_ns_t_ds : {
	    struct rk_ds_record *ds = rr->u.ds;
	    size_t i;

	    printf ("key tag %u alg %u type %u length %lu data ",
		    ds->key_tag, ds->algorithm, ds->digest_type,
		    (unsigned long)ds->digest_len);
	    for (i = 0; i < ds->digest_len; i++)
		printf("%02X", ds->digest_data[i]);
	    printf("\n");

	    break;
	}
	default:
	    printf("\n");
	    break;
	}
    }

    return 0;
}
Example #11
0
File: hw3.c Project: azyth/security
void print_entry(list_t* list) {
  	struct in_addr src_ip;
  	src_ip.s_addr = list->source->ip;
  	printf("Source IP      : %s\n", inet_ntoa(src_ip));

  	struct in_addr dest_ip;
  	dest_ip.s_addr = list->source->dest_ip;
  	printf("Destination IP : %s\n", inet_ntoa(dest_ip));

  	printf("Number of scans: %u\n", list->source->dest_ports->size);

  	printf("Scan type      : ");
  	switch(list->source->portscanner) {
  	case SYN_SCAN:
	  	printf("SYN scan, random order of ports\n");
  		break;
  	case FIN_SCAN:
  		printf("FIN scan, random order of ports\n");
  		break;
  	case XMAS_SCAN:
  		printf("XMAS scan, random order of ports\n");
  		break;
	case NUL_SCAN:
  		printf("Null scan, random order of ports\n");
  		break;
	case CONN_SCAN:
  		printf("TCP Connect scan, random order of ports\n");
    	break;
  	case HORIZ_SCAN:
  		printf("Horizonal scan, random order of ports\n");
  		break;

  	default:
  		break;
  	}


  	// char ts_start[64]; 
  	// time_t start_time = list->source->first_packet_time.tv_sec; //make first_packet_time field
  	// struct tm* start_time_struc = localtime(&start_time);
  	// strftime(ts_start, sizeof(ts_start), "%H:%M:%S", start_time_struc);
  	// int us_start = (int)list->source->first_packet_time.tv_usec;
  	// printf("First Packet: %s.%06d, ", ts_start, us_start); //I think this format may be off? check his comments for hw2

  	// char ts_end[64]; 
  	// time_t end_time = list->source->last_packet_time.tv_sec; 
  	// struct tm* end_time_struc = localtime(&end_time);
  	// strftime(ts_end, sizeof(ts_end), "%H:%M:%S", end_time_struc);
  	// int us_end = (int)list->source->last_packet_time.tv_usec;
  	// printf("Last Packet: %s.%06d, ", ts_end, us_end); //I think this format may be off? check his comments for hw2
  	
  	double sec_start = list->source->first_packet_time.tv_sec;
  	double usec_start = list->source->first_packet_time.tv_usec;
  	double sec_end = list->source->last_packet_time.tv_sec;
  	double usec_end = list->source->last_packet_time.tv_usec;

  	// double sec_diff = sec_end - sec_start;
  	// double usec_diff = (double_(usec_end - usec_start)/1000000);
  	//printf("%f\n", usec_start);
  	double total_start = sec_start + usec_start/1000000;
  	double total_end = sec_end + usec_end/1000000;
  	//printf("%f, %f\n", total_start, total_end);
  	double diff = total_end-total_start;
  	printf("Time taken     : %.4f\n", diff);
  	//printf("%f, %f, %f, %f\n", sec_start, usec_start, sec_end, usec_end);
  	//printf("start time: %.4f  end time: %.4f\n", (double)sec_end-sec_start, (double)usec_end-usec_start);

}
Example #12
0
static int packet_to_data(Packet *p, Event *event, idmef_alert_t *alert)
{
        int i;

        if ( ! p )
            return 0;

        add_int_data(alert, "snort_rule_sid", event->sig_id);
        add_int_data(alert, "snort_rule_rev", event->sig_rev);

        if ( IPH_IS_VALID(p) ) {
                add_int_data(alert, "ip_ver", GET_IPH_VER(p));
                add_int_data(alert, "ip_hlen", GET_IPH_HLEN(p));
                add_int_data(alert, "ip_tos", GET_IPH_TOS(p));
                add_int_data(alert, "ip_len", ntohs(GET_IPH_LEN(p)));
#ifdef SUP_IP6
// XXX-IPv6 need fragmentation ID
#else
                add_int_data(alert, "ip_id", ntohs(p->iph->ip_id));
#endif
#ifdef SUP_IP6
// XXX-IPv6 need fragmentation offset
#else
                add_int_data(alert, "ip_off", ntohs(p->iph->ip_off));
#endif
                add_int_data(alert, "ip_ttl", GET_IPH_TTL(p));
                add_int_data(alert, "ip_proto", GET_IPH_PROTO(p));
#ifdef SUP_IP6
// XXX-IPv6 need checksum
#else
                add_int_data(alert, "ip_sum", ntohs(p->iph->ip_csum));
#endif

                for ( i = 0; i < p->ip_option_count; i++ ) {
                        add_int_data(alert, "ip_option_code", p->ip_options[i].code);
                        add_byte_data(alert, "ip_option_data",
                            p->ip_options[i].data, p->ip_options[i].len);
                }
        }

        if ( p->tcph ) {
                add_int_data(alert, "tcp_seq", ntohl(p->tcph->th_seq));
                add_int_data(alert, "tcp_ack", ntohl(p->tcph->th_ack));

                add_int_data(alert, "tcp_off", TCP_OFFSET(p->tcph));
                add_int_data(alert, "tcp_res", TCP_X2(p->tcph));
                add_int_data(alert, "tcp_flags", p->tcph->th_flags);

                add_int_data(alert, "tcp_win", ntohs(p->tcph->th_win));
                add_int_data(alert, "tcp_sum", ntohs(p->tcph->th_sum));
                add_int_data(alert, "tcp_urp", ntohs(p->tcph->th_urp));


                for ( i = 0; i < p->tcp_option_count; i++ ) {
                        add_int_data(alert, "tcp_option_code", p->tcp_options[i].code);
                        add_byte_data(alert, "tcp_option_data", p->tcp_options[i].data, p->tcp_options[i].len);
                }
        }

        else if ( p->udph ) {
                add_int_data(alert, "udp_len", ntohs(p->udph->uh_len));
                add_int_data(alert, "udp_sum", ntohs(p->udph->uh_chk));
        }

        else if ( p->icmph ) {
                add_int_data(alert, "icmp_type", p->icmph->type);
                add_int_data(alert, "icmp_code", p->icmph->code);
                add_int_data(alert, "icmp_sum", ntohs(p->icmph->csum));

                switch ( p->icmph->type ) {

                case ICMP_ECHO:
                case ICMP_ECHOREPLY:
                case ICMP_INFO_REQUEST:
                case ICMP_INFO_REPLY:
                case ICMP_ADDRESS:
                case ICMP_TIMESTAMP:
                        add_int_data(alert, "icmp_id", ntohs(p->icmph->s_icmp_id));
                        add_int_data(alert, "icmp_seq", ntohs(p->icmph->s_icmp_seq));
                        break;

                case ICMP_ADDRESSREPLY:
                        add_int_data(alert, "icmp_id", ntohs(p->icmph->s_icmp_id));
                        add_int_data(alert, "icmp_seq", ntohs(p->icmph->s_icmp_seq));
                        add_int_data(alert, "icmp_mask", (uint32_t) ntohl(p->icmph->s_icmp_mask));
                        break;

                case ICMP_REDIRECT:
#ifndef SUP_IP6
                        add_string_data(alert, "icmp_gwaddr", inet_ntoa(p->icmph->s_icmp_gwaddr));
#else
                        {
                            sfip_t gwaddr;
                            sfip_set_raw(&gwaddr, (void *)&p->icmph->s_icmp_gwaddr.s_addr, AF_INET);
                            add_string_data(alert, "icmp_gwaddr", inet_ntoa(&gwaddr));
                        }
#endif
                        break;

                case ICMP_ROUTER_ADVERTISE:
                        add_int_data(alert, "icmp_num_addrs", p->icmph->s_icmp_num_addrs);
                        add_int_data(alert, "icmp_wpa", p->icmph->s_icmp_wpa);
                        add_int_data(alert, "icmp_lifetime", ntohs(p->icmph->s_icmp_lifetime));
                        break;

                case ICMP_TIMESTAMPREPLY:
                        add_int_data(alert, "icmp_id", ntohs(p->icmph->s_icmp_id));
                        add_int_data(alert, "icmp_seq", ntohs(p->icmph->s_icmp_seq));
                        add_int_data(alert, "icmp_otime", p->icmph->s_icmp_otime);
                        add_int_data(alert, "icmp_rtime", p->icmph->s_icmp_rtime);
                        add_int_data(alert, "icmp_ttime", p->icmph->s_icmp_ttime);
                        break;
                }
        }

        add_byte_data(alert, "payload", p->data, p->dsize);

        return 0;
}
Example #13
0
static int event_to_source_target(Packet *p, idmef_alert_t *alert)
{
        int ret;
        idmef_node_t *node;
        idmef_source_t *source;
        idmef_target_t *target;
        idmef_address_t *address;
        idmef_service_t *service;
        prelude_string_t *string;
        static char saddr[128], daddr[128];

        if ( !p )
            return 0;

        if ( ! IPH_IS_VALID(p) )
                return 0;

        ret = idmef_alert_new_source(alert, &source, IDMEF_LIST_APPEND);
        if ( ret < 0 )
                return ret;

        ret = idmef_source_new_interface(source, &string);
        if ( ret < 0 )
            return ret;
        prelude_string_set_ref(string, PRINT_INTERFACE(DAQ_GetInterfaceSpec()));

        ret = idmef_source_new_service(source, &service);
        if ( ret < 0 )
                return ret;

        if ( p->tcph || p->udph )
                idmef_service_set_port(service, p->sp);

        idmef_service_set_ip_version(service, GET_IPH_VER(p));
        idmef_service_set_iana_protocol_number(service, GET_IPH_PROTO(p));

        ret = idmef_source_new_node(source, &node);
        if ( ret < 0 )
                return ret;

        ret = idmef_node_new_address(node, &address, IDMEF_LIST_APPEND);
        if ( ret < 0 )
                return ret;

        ret = idmef_address_new_address(address, &string);
        if ( ret < 0 )
                return ret;

        SnortSnprintf(saddr, sizeof(saddr), "%s", inet_ntoa(GET_SRC_ADDR(p)));
        prelude_string_set_ref(string, saddr);

        ret = idmef_alert_new_target(alert, &target, IDMEF_LIST_APPEND);
        if ( ret < 0 )
                return ret;

        ret = idmef_target_new_interface(target, &string);
        if ( ret < 0 )
            return ret;
        prelude_string_set_ref(string, PRINT_INTERFACE(DAQ_GetInterfaceSpec()));

        ret = idmef_target_new_service(target, &service);
        if ( ! ret < 0 )
                return ret;

        if ( p->tcph || p->udph )
                idmef_service_set_port(service, p->dp);

        idmef_service_set_ip_version(service, GET_IPH_VER(p));
        idmef_service_set_iana_protocol_number(service, GET_IPH_PROTO(p));

        ret = idmef_target_new_node(target, &node);
        if ( ret < 0 )
                return ret;

        ret = idmef_node_new_address(node, &address, IDMEF_LIST_APPEND);
        if ( ret < 0 )
                return ret;

        ret = idmef_address_new_address(address, &string);
        if ( ret < 0 )
                return ret;

        SnortSnprintf(daddr, sizeof(daddr), "%s", inet_ntoa(GET_DST_ADDR(p)));
        prelude_string_set_ref(string, daddr);

        return 0;
}
/*
 * dissect/print packet
 */
void
got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{

	static int count = 1;                   /* packet counter */
	
	/* declare pointers to packet headers */
	const struct sniff_ethernet *ethernet;  /* The ethernet header [1] */
	const struct sniff_ip *ip;              /* The IP header */
	const struct sniff_tcp *tcp;            /* The TCP header */
	const char *payload;                    /* Packet payload */

	int size_ip;
	int size_tcp;
	int size_payload;
	
	printf("\nPacket number %d:\n", count);
	count++;
	
	/* define ethernet header */
	ethernet = (struct sniff_ethernet*)(packet);
	
	/* define/compute ip header offset */
	ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
	size_ip = IP_HL(ip)*4;
	if (size_ip < 20) {
		printf("   * Invalid IP header length: %u bytes\n", size_ip);
		return;
	}

	/* print source and destination IP addresses */
	printf("       From: %s\n", inet_ntoa(ip->ip_src));
	printf("         To: %s\n", inet_ntoa(ip->ip_dst));
	
	/* determine protocol */	
	switch(ip->ip_p) {
		case IPPROTO_TCP:
			printf("   Protocol: TCP\n");
			break;
		case IPPROTO_UDP:
			printf("   Protocol: UDP\n");
			return;
		case IPPROTO_ICMP:
			printf("   Protocol: ICMP\n");
			return;
		case IPPROTO_IP:
			printf("   Protocol: IP\n");
			return;
		default:
			printf("   Protocol: unknown\n");
			return;
	}
	
	/*
	 *  OK, this packet is TCP.
	 */
	
	/* define/compute tcp header offset */
	tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
	size_tcp = TH_OFF(tcp)*4;
	if (size_tcp < 20) {
		printf("   * Invalid TCP header length: %u bytes\n", size_tcp);
		return;
	}
	
	printf("   Src port: %d\n", ntohs(tcp->th_sport));
	printf("   Dst port: %d\n", ntohs(tcp->th_dport));
	
	/* define/compute tcp payload (segment) offset */
	payload = (u_char *)(packet + SIZE_ETHERNET + size_ip + size_tcp);
	
	/* compute tcp payload (segment) size */
	size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp);
	
	/*
	 * Print payload data; it might be binary, so don't just
	 * treat it as a string.
	 */
	if (size_payload > 0) {
		printf("   Payload (%d bytes):\n", size_payload);
		print_payload(payload, size_payload);
	}

return;
}
Example #15
0
/*
 * Returns a list of network interfaces and their ipv4 address.
 * <interface>:<address>\n
 */
int sys_cmd_ip_info(sysh_ctx_t syshc, char *value, uint16_t *out_rc, char **out_str){
    int sys_rc = MOD_OK;
    int rc = 0;
    int sock = -1;
    struct ifreq *ifreqs = NULL;
    size_t ifreqs_len = 4 * sizeof(struct ifreq);
    struct ifconf ic;
    int i;
    size_t buf_len = 1024;
    size_t buf_used = 0;

    if ( !( (*out_str) = (char*)malloc(buf_len)) ){
        if ( asprintf(out_str, "malloc: %s", strerror(errno)) == -1 ){
            err("asprintf: %s\n", strerror(errno));
            *out_str = NULL;
        }
        goto done;
    }

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    while ( true ){
        if ( !(ifreqs = (struct ifreq *)malloc(ifreqs_len)) ){
            sys_rc = errno;
            if ( asprintf(out_str, "malloc: %s", strerror(errno)) == -1 ){
                err("asprintf: %s\n", strerror(errno));
                *out_str = NULL;
            }
            goto done;
        }
        ic.ifc_len = ifreqs_len;
        ic.ifc_req = ifreqs;
        ioctl(sock, SIOCGIFCONF, &ic);
        if ( ic.ifc_len == ifreqs_len ) {
            free(ifreqs);
            ifreqs_len += 4 * sizeof(struct ifreq);
            continue;
        }
        break;
    }
    close(sock);
    sock = -1;

    **out_str = '\0';
    for ( i = 0; i < ic.ifc_len/sizeof(struct ifreq); i++ ) {
        if ( buf_len - buf_used - strlen(ifreqs[i].ifr_name) - 16 ) {
            if ( !((*out_str) = realloc((*out_str), buf_len + 1024)) ){
                sys_rc = errno;
                free((*out_str));
                if ( asprintf(out_str, "realloc: %s", strerror(errno)) == -1 ){
                    err("asprintf: %s\n", strerror(errno));
                    *out_str = NULL;
                }
                goto done;
            }
        }
        sprintf( (*out_str) + strlen((*out_str)), "%s:%s\n",
            ifreqs[i].ifr_name,
            inet_ntoa( ((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr ) );
        buf_used = strlen((*out_str)) + 1;
    }

done:
    if ( sock > 0 )
        close(sock);
    if ( ifreqs )
        free(ifreqs);
    (*out_rc) = (uint16_t)sys_rc;
    return rc;
}
Example #16
0
/*
	returns info about a contact as a string
*/
TCHAR* getContactInfoT(BYTE type, MCONTACT hContact)
{
	/* returns dynamic allocated buffer with info, or NULL if failed */
	if (hContact == NULL)
		return NULL;

	char *szProto = GetContactProto(hContact);
	if (szProto == NULL)
		return NULL;

	TCHAR *res = NULL;
	switch (type) {
	case CCNF_PROTOID:
		return mir_a2t(szProto);

	case CCNF_ACCOUNT:
		{
			PROTOACCOUNT *pa = Proto_GetAccount(szProto);
			return pa ? mir_tstrdup(pa->tszAccountName) : NULL;
		}

	case CCNF_PROTOCOL:
		{
			char protoname[128];
			if (CallProtoService(szProto, PS_GETNAME, (WPARAM)sizeof(protoname), (LPARAM)protoname))
				return NULL;
			return mir_a2t(protoname);
		}

	case CCNF_STATUS:
		return mir_tstrdup(pcli->pfnGetStatusModeDescription(db_get_w(hContact, szProto, "Status", ID_STATUS_OFFLINE), 0));

	case CCNF_INTERNALIP:
	case CCNF_EXTERNALIP:
		{
			DWORD ip = db_get_dw(hContact, szProto, (type == CCNF_INTERNALIP) ? "RealIP" : "IP", 0);
			if (ip == 0)
				return NULL;

			struct in_addr in;
			in.s_addr = htonl(ip);
			return mir_a2t(inet_ntoa(in));
		}

	case CCNF_GROUP:
		if ((res = db_get_tsa(hContact, "CList", "Group")) != NULL)
			return res;
		break;

	case CNF_UNIQUEID:
		//UID for ChatRoom
		if (db_get_b(hContact, szProto, "ChatRoom", 0) == 1)
			if ((res = db_get_tsa(hContact, szProto, "ChatRoomID")) != NULL)
				return res;

		//UID for other contact
		break;
	}

	CONTACTINFO ci = { sizeof(ci) };
	ci.hContact = hContact;
	ci.dwFlag = type | CNF_UNICODE;
	CallService(MS_CONTACT_GETCONTACTINFO, 0, (LPARAM)&ci);

	char szVal[16];
	memset(szVal, '\0', sizeof(szVal));
	switch (ci.type) {
	case CNFT_BYTE:
		if (type == CNF_GENDER) {
			szVal[0] = (char)ci.bVal; szVal[1] = 0;
			return mir_a2t(szVal);
		}
		return itot(ci.bVal);

	case CNFT_WORD:
		return itot(ci.wVal);

	case CNFT_DWORD:
		return itot(ci.dVal);

	case CNFT_ASCIIZ:
		return ci.pszVal;
	}

	return NULL;
}
int Manager::Report_TCP( Target_Spec *tcp_spec )
{
	int c, scanCount, i, skfd, count = 0;
	char ifname[32];
	FILE *netInfo;
	struct ifreq ifr;

	cout << "Reporting TCP network information..." << endl;
	
	netInfo = fopen("/proc/net/dev", "r");
	assert(netInfo != NULL);
	skfd = socket(PF_INET, SOCK_DGRAM, 0);
	if (skfd < 0) {
		cerr << "Can not create socket in Manager::Report_TCP" << endl;
		return -1;
	}

	// Pull out the first two lines of the file. These two lines contain
	// labels for the columns.
	for (i = 0; i < 2; ++i) {
		do {
			c = getc(netInfo);
		} while ((c != '\n') && (c != EOF));
	}

	for (i = 0; i < MAX_NUM_INTERFACES; ++i) {
		// grab the interface names (if there are leading blanks,
		// then they are removed using the Strip() function)
		scanCount = fscanf(netInfo, "%[^:]: %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d", ifname);
		if (scanCount == EOF) {
			break;
		}
		assert(scanCount == 1);
		Strip(ifname);

		// get ip address for the interface
		strcpy(ifr.ifr_name, ifname);
		ifr.ifr_addr.sa_family = AF_INET;
		if (ioctl(skfd, SIOCGIFADDR, &ifr) == 0) {
			strncpy ( tcp_spec[count].name, inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr), 
					sizeof(tcp_spec[count].name) - 1 );
			tcp_spec[count].type = TCPClientType;	// interface to access a client

			#if _DEBUG
				cout << "   Found " << tcp_spec[count].name << "." << endl;
			#endif
			count++;
		}
		else {
#if _DEBUG
			cerr << "ioctl fail in Manager::Report_TCP()" << endl;
#endif
		}
		// Skip to the next line.
		do {
			c = getc(netInfo);
		} while ((c != '\n') && (c != EOF));
	}
	fclose(netInfo);
	close(skfd);
	// All done.
	cout << "   done." << endl;
	return count;
}
Example #18
0
int main(int argc, char *argv[])
{
	int pid1, pid2;
	pid1 = fork();
	if(pid1 == 0) {
		struct sockaddr_in si_other;
		int s, i, slen=sizeof(si_other);
		char buf[BUFLEN];

		if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
		  diep("socket");

		memset((char *) &si_other, 0, sizeof(si_other));
		si_other.sin_family = AF_INET;
		si_other.sin_port = htons(PORT);
		if (inet_aton(SRV_IP, &si_other.sin_addr)==0) {
		  fprintf(stderr, "inet_aton() failed\n");
		  exit(1);
		}

		for (i=0; i<NPACK; i++) {
			//sleep(1);
		  printf("Child1: Sending packet %d\n", i);
		  sprintf(buf, "This is packet %d\n", i);
		  if (sendto(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, slen)==-1)
			diep("sendto()");
		}

		close(s);
 		printf("Child Exiting.\n");
		_exit(0);
	} else {
		pid2 = fork();
		if(pid2 == 0) {
			struct sockaddr_in si_other;
			int s, i, slen=sizeof(si_other);
			char buf[BUFLEN];

			if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
			  diep("socket");

			memset((char *) &si_other, 0, sizeof(si_other));
			si_other.sin_family = AF_INET;
			si_other.sin_port = htons(PORT);
			if (inet_aton(SRV_IP, &si_other.sin_addr)==0) {
			  fprintf(stderr, "inet_aton() failed\n");
			  exit(1);
			}

			for (i=0; i<NPACK; i++) {
				//sleep(1);
			  printf("Child2: Sending packet %d\n", (i+10));
			  sprintf(buf, "This is packet %d\n", (i+10));
			  if (sendto(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, slen)==-1)
				diep("sendto()");
			}

			close(s);
	 		printf("Child Exiting.\n");
			_exit(0);
		} else {
			struct sockaddr_in si_me, si_other;
			int s, i, slen=sizeof(si_other);
			char buf[BUFLEN];

			if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
			  diep("socket");

			memset((char *) &si_me, 0, sizeof(si_me));
			si_me.sin_family = AF_INET;
			si_me.sin_port = htons(PORT);
			si_me.sin_addr.s_addr = htonl(INADDR_ANY);
			if (bind(s, (struct sockaddr *) &si_me, sizeof(si_me))==-1)
				diep("bind");

			for (i=0; i<NPACK*2; i++) {
			  if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)==-1)
				diep("recvfrom()");
			  printf("Received packet from %s:%d\nData: %s\n\n",
					 inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
			}

			close(s);
			return 0;
			printf("Parent Exiting.\n");
		}
	}
}
Example #19
0
/**
* @brief tcpserver accept tcp connect receive data and output on debug thermal.
* @param void* parameter :unused.
*/
static void tcpserv(void* parameter)
{
   char *recv_data; /* 用于接收的指针,后面会做一次动态分配以请求可用内存 */
   u32_t sin_size;
   int sock, connected, bytes_received;
   struct sockaddr_in server_addr, client_addr;
   bool stop = FALSE; /* 停止标志 */

   recv_data = mem_malloc(RECV_BUFFER_SIZE); /* 分配接收用的数据缓冲 */
   if (recv_data == NULL)
   {
       printf("No memory\n");
       return;
   }

   /* 一个socket在使用前,需要预先创建出来,指定SOCK_STREAM为TCP的socket */
   if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
   {
       /* 创建失败的错误处理 */
       printf("Socket error\n");

       /* 释放已分配的接收缓冲 */
       mem_free(recv_data);
       return;
   }

   /* 初始化服务端地址 */
   server_addr.sin_family = AF_INET;
   server_addr.sin_port = htons(TCPSERVER_PORT_NO); /* 服务端工作的端口 */
   server_addr.sin_addr.s_addr = INADDR_ANY;
   memset(&(server_addr.sin_zero),8, sizeof(server_addr.sin_zero));

   /* 绑定socket到服务端地址 */
   if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
   {
       /* 绑定失败 */
       printf("Unable to bind\n");

       /* 释放已分配的接收缓冲 */
       mem_free(recv_data);
       return;
   }

   /* 在socket上进行监听 */
   if (listen(sock, 5) == -1)
   {
       printf("Listen error\n");

       /* release recv buffer */
       mem_free(recv_data);
       return;
   }

   printf("\nTCPServer Waiting for client on port %d...\n", TCPSERVER_PORT_NO);
   while(stop != TRUE)
   {
       sin_size = sizeof(struct sockaddr_in);

       /* 接受一个客户端连接socket的请求,这个函数调用是阻塞式的 */
       connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size);
       /* 返回的是连接成功的socket */

       /* 接受返回的client_addr指向了客户端的地址信息 */
       printf("I got a connection from (%s , %d)\n",
                  inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));

       /* 客户端连接的处理 */
       while (1)
       {
           /* 发送数据到connected socket */
           //send(connected, send_data, strlen(send_data), 0);

           /* 从connected socket中接收数据,接收buffer是1024大小,但并不一定能够收到1024大小的数据 */
           bytes_received = recv(connected,recv_data, RECV_BUFFER_SIZE, 0);
           if (bytes_received <= 0)
           {
               if(bytes_received == 0)
                   printf("client close connection.\n");
               else
                   printf("received failed, server close connection.\n");
               
               /* 接收失败,关闭这个connected socket */
               lwip_close(connected);
               break;
           }

           /* 有接收到数据,把末端清零 */
           recv_data[bytes_received] = '\0';
           if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
           {
               /* 如果是首字母是q或Q,关闭这个连接 */
               printf("receive \"q\" command, close connection.\n");
               lwip_close(connected); // close socket
               break;
           }
           else if (strcmp(recv_data, "exit") == 0)
           {
               /* 如果接收的是exit,则关闭整个服务端 */
               printf("receive \"exit\" command, exit tcpserver task.\n");
               lwip_close(connected); // close socket
               stop = TRUE;
               break;
           }
           else
           {
               /* 在控制终端显示收到的数据 */
               printf("RECIEVED DATA = %s \n" , recv_data);
           }
       } // end of while(1)
   } // end of while(stop != TRUE)

   /* 释放接收缓冲 */
   mem_free(recv_data);

   return ;
}
Example #20
0
AddressList* get_addresses() {

    AddressList *al = malloc(sizeof(AddressList));
    AddressList *head = al;

    pcap_if_t *devlist, *curr;
    pcap_addr_t *addr;
    char errbuf[PCAP_ERRBUF_SIZE];

    if (pcap_findalldevs(&devlist, errbuf)) {
        dump(L_ERR, "pcap: %s\n", errbuf);
        return NULL;
    }
    
    for (curr = devlist; curr; curr = curr->next) {
        //if (curr->flags & PCAP_IF_LOOPBACK)
        //  continue;

        /*
         dev_name: eth0         desc:(null)     flags:0
         dev_name: bond0        desc:(null)     flags:0
                10.249.252.65
                10.249.252.71
                0.0.0.0
         dev_name: eth1         desc:(null)     flags:0
         dev_name: any  desc:Pseudo-device that captures on all interfaces      flags:0
         dev_name: lo   desc:(null)     flags:1
                127.0.0.1
                0.0.0.0
        */

        dump(L_OK, "dev_name: %s\t desc:%s\t flags:%d", curr->name, curr->description, 
            curr->flags);

        for (addr = curr->addresses; addr; addr = addr->next) {
            struct sockaddr *realaddr;

            if (addr->addr)
                realaddr = addr->addr;
            else if (addr->dstaddr)
                realaddr = addr->dstaddr;
            else
                continue;

            if (realaddr->sa_family == AF_INET || 
                realaddr->sa_family == AF_INET6) {

                struct sockaddr_in *sin;
                
                sin = (struct sockaddr_in *) realaddr;
            
                if (0 == sin->sin_addr.s_addr)
                    continue;
                dump(L_OK, "\t %s ", inet_ntoa(sin->sin_addr));

                al->next = malloc(sizeof(AddressList));
                if (!al->next)
                    abort();
                
                al->next->in_addr = sin->sin_addr;
                al->next->next = NULL;
                al= al->next;
            }
        }
    }
    
    pcap_freealldevs(devlist);
    
    return head;
}
Example #21
0
/* numeric: & 0x8000: default instead of *, 
 *	    & 0x4000: host instead of net, 
 *	    & 0x0fff: don't resolve
 */
static int INET_rresolve(char *name, size_t len, struct sockaddr_in *sin, 
			 int numeric, unsigned int netmask)
{
    struct hostent *ent;
    struct netent *np;
    struct addr *pn;
    u_int32_t ad, host_ad;
    int host = 0;

    /* Grmpf. -FvK */
    if (sin->sin_family != AF_INET) {
#ifdef DEBUG
	fprintf(stderr, _("rresolve: unsupport address family %d !\n"), sin->sin_family);
#endif
	errno = EAFNOSUPPORT;
	return (-1);
    }
    ad = sin->sin_addr.s_addr;
#ifdef DEBUG
    fprintf (stderr, "rresolve: %08lx, mask %08x, num %08x \n", ad, netmask, numeric);
#endif
    if (ad == INADDR_ANY) {
	if ((numeric & 0x0FFF) == 0) {
	    if (numeric & 0x8000)
		safe_strncpy(name, "default", len);
	    else
	        safe_strncpy(name, "*", len);
	    return (0);
	}
    }
    if (numeric & 0x0FFF) {
        safe_strncpy(name, inet_ntoa(sin->sin_addr), len);
	return (0);
    }

    if ((ad & (~netmask)) != 0 || (numeric & 0x4000))
	host = 1;
#if 0
    INET_nn = NULL;
#endif
    pn = INET_nn;
    while (pn != NULL) {
	if (pn->addr.sin_addr.s_addr == ad && pn->host == host) {
	    safe_strncpy(name, pn->name, len);
#ifdef DEBUG
	    fprintf (stderr, "rresolve: found %s %08lx in cache\n", (host? "host": "net"), ad);
#endif
	    return (0);
	}
	pn = pn->next;
    }

    host_ad = ntohl(ad);
    np = NULL;
    ent = NULL;
    if (host) {
#ifdef DEBUG
	fprintf (stderr, "gethostbyaddr (%08lx)\n", ad);
#endif
	ent = gethostbyaddr((char *) &ad, 4, AF_INET);
	if (ent != NULL)
	    safe_strncpy(name, ent->h_name, len);
    } else {
#ifdef DEBUG
	fprintf (stderr, "getnetbyaddr (%08lx)\n", host_ad);
#endif
	np = getnetbyaddr(host_ad, AF_INET);
	if (np != NULL)
	    safe_strncpy(name, np->n_name, len);
    }
    if ((ent == NULL) && (np == NULL))
	safe_strncpy(name, inet_ntoa(sin->sin_addr), len);
    pn = (struct addr *) malloc(sizeof(struct addr));
    pn->addr = *sin;
    pn->next = INET_nn;
    pn->host = host;
    pn->name = (char *) malloc(strlen(name) + 1);
    strcpy(pn->name, name);
    INET_nn = pn;

    return (0);
}
Example #22
0
const char *convertToIpv4(unsigned char *addr)
{
    struct in_addr in;
    memcpy(&in,addr,4);
    return inet_ntoa(in);
}
Example #23
0
int main()
{
    int                  sock_fd, conn_fd;
    int                  optval;
    int                  flag_recv = USERNAME;
    int                  ret;
    int                  name_num;
    pid_t                pid;
    socklen_t            cli_len;
    struct sockaddr_in   cli_addr, serv_addr;
    char                 recv_buf[128];

    sock_fd = socket(AF_INET, SOCK_STREAM, 0);          //创建一个TCP套接字
    if(sock_fd < 0)
    {
        my_err("socket", __LINE__);
    }

    optval = 1;                                         //设置该套接字使之可以重新绑定端口
    if(setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&optval, sizeof(int)) < 0)
    {
        my_err("setsocketopt", __LINE__);
    }

    memset(&serv_addr, 0, sizeof(struct sockaddr_in));   //初始化服务器端地址结构
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(SERV_PORT);
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr_in)) < 0)                        //将套接字绑定到本地端口
    {
        my_err("bind", __LINE__);
    }

    if(listen(sock_fd, LISTENQ) < 0)                    //将套接字转化为监听套接字
    {
        my_err("listen", __LINE__);
    }

    cli_len = sizeof(struct sockaddr_in);
    while(1)
    {
        conn_fd = accept(sock_fd, (struct sockaddr *)&cli_addr, &cli_len);
        if(conn_fd < 0)
        {
            my_err("accept", __LINE__);
        }

        printf("accept a new client, ip: %s\n", inet_ntoa(cli_addr.sin_addr));
        if((pid = fork()) == 0)                         //创建子进程处理刚刚接收的连接请求
        {
            while(1)                                    //子进程
            {
                if((ret = recv(conn_fd, recv_buf, sizeof(recv_buf), 0)) < 0)
                {
                    perror("recv");
                    exit(1);
                }
                recv_buf[ret - 1] = '\0';               //将数据结束标志'\n'替换成字符串结束标志

                if(flag_recv == USERNAME)               //接收到的是用户名
                {
                    name_num = find_name(recv_buf);
                    switch (name_num)
                    {
                        case -1:
                            send_data(conn_fd, "n\n");
                            break;
                        case -2:
                            exit(1);
                            break;
                        default:
                            send_data(conn_fd, "y\n");
                            flag_recv = PASSWORD;
                            break;
                    }
                }
                else if(flag_recv == PASSWORD)          //接收到的是密码 
                {
                    if (strcmp(users[name_num].password, recv_buf) == 0)
                    {
                        send_data(conn_fd, "y\n");
                        send_data(conn_fd, "welcome login my tcp server\n");
                        printf("%s login \n", users[name_num].username);
                        break;
                    }
                    else 
                    {
                        send_data(conn_fd, "n\n");
                    }
                }
            }
            close(sock_fd);
            close(sock_fd);
            exit(0);                                    //结束子进程            
        }
        else
        {
            close(conn_fd);                             //父进程关闭刚刚接收的连接请求,执行accept等待其他连接请求
        }
    }
    return 0;
}
Example #24
0
static void *do_resolve(void *hostname)
{

	slogi("do_resolve hostname[%s]",hostname);
	#if 0
	/*
[/home/st/toffaletti/armhf/key.c_114__st_thread_cleanup]key [110876]  key_max[0]
do_resolve hostname[www.baidu.com]
after strcpy  strcpy(host,hostname)[www.baidu.com] hostname[www.baidu.com]
[/home/st/toffaletti/armhf/event.c_421__st_select_fd_new]_st_select_fd_new osfd[7] ok
[/home/st/toffaletti/armhf/io.c_749_st_sendto]sendto get n [31]
[/home/st/toffaletti/armhf/io.c_730_st_recvfrom]recvfrom get n [90]
[/home/st/toffaletti/armhf/examples/res.c_278_dns_getaddr]query_domain return 0
[/home/st/toffaletti/armhf/io.c_212_st_netfd_close]JUST TEST st_netfd_close

Program received signal SIGSEGV, Segmentation fault.
0x00000000 in ?? ()
(gdb) bt
#0  0x00000000 in ?? ()
#1  0x0000b06e in dns_getaddr (
    host=<error reading variable: Cannot access memory at address 0xc>,
    addr=<error reading variable: Cannot access memory at address 0x8>,
    timeout=<error reading variable: Cannot access memory at address 0x0>)
    at /home/st/toffaletti/armhf/examples/res.c:281
Backtrace stopped: previous frame inner to this frame (corrupt stack?)
(gdb)
	*/
	char host[128];
	memset(host,0,128);
	//strcpy(host,hostname);
	slogi("after strcpy  strcpy(host,hostname)[%s] hostname[%s]",strcpy(host,hostname),hostname);
	#else
	char *host=malloc(128);
	memset(host,0,128);
	slogi("sizeof(hostname)[%d] strlen(hostname)[%d]",sizeof(hostname),strlen(hostname));
	memcpy(host,hostname,strlen(hostname)+1);
	slogi("host is [%s]",host);
	#endif

  struct in_addr addr;

#if 1
  /* Use dns_getaddr() instead of gethostbyname(3) to get IP address */
  #if 1
    int ret=-99;
     dns_getaddr(host, &addr, TIMEOUT);
    LOGD("dns_getaddr RET");
    if ( ret< 0) {
  #else
    if ( dns_getaddr(host, &addr, TIMEOUT)< 0) {
  #endif
// #endif
  	/*PCÉÏ»áÊä³öСÓÚ0£¬tvboxÉÏɶ¶¼Ã»ÓÐÊä³ö°¡*/
    fprintf(stderr, "dns_getaddr: can't resolve %s: ", (char *)host);
    if (h_errno == NETDB_INTERNAL)
      perror("");
    else
      herror("");
  } else /*ÕâÖÖÇé¿ö¾ÍÊÇÕÒµ½ÁË*/
      printf("%-40s %s\n", (char *)host, inet_ntoa(addr));
#else //Ö±½Ó²âÊÔÏ̺߳¯Êý
/* http://m.blog.chinaunix.net/uid-28595538-id-4923606.html
inet_ntoa º¯Êý API ÃèÊö
#include
#include
char * inet_ntoa( struct in_addr_in ) ;

²ÎÊý£º
   in : ¸Ã²ÎÊý´æ·ÅÓÃÀ´×ª»»µÄ16½øÖÆÍøÂç˳ÐòµÄIPµØÖ·½á¹¹Ìå
·µ»ØÖµ£º
   Èç¹ûº¯Êý Inet_ntoa ³É¹¦½« 16½øÖÆÍøÂç˳ÐòµÄ IPµØַת»»Îª×Ö·û´®ÀàÐ͵ĵã·ÖIP µØÖ·£¬
   Ôò½«¸Ã×Ö·û´®×÷Ϊ·µ»ØÖµ·µ»Ø£¬×ª»»Ê§°Ü£¬·µ»Ø NULL

*/
	int count=20;
	while(count--)
    {
		LOGD("just for test thread func ....");
		//ÕâÀïÊä³öµÄaddrÊÇ´íÎóµÄ
		printf("%-40s %s\n", (char *)host, inet_ntoa(addr));
	}
#endif
//20150923
   free(host);
  return NULL;
}


/*
 * Asynchronous DNS host name resolution. This program creates one
 * ST thread for each host name (specified as command line arguments).
 * All threads do host name resolution concurrently.
 */
int main(int argc, char *argv[])
{
	slogi("argc[%d]",argc);
  int i;

  if (argc < 2) {
    fprintf(stderr, "Usage: %s <hostname1> [<hostname2>] ...\n", argv[0]);
    exit(1);
  }

  if (st_init() < 0) {
    perror("st_init");
    exit(1);
  }

	slogi("---before for--argc[%d]",argc);
  for (i = 1; i < argc; i++) {
  	slogi("====%d=[%s]=",i,argv[i]);
    /* Create a separate thread for each host name */
    if (st_thread_create(do_resolve, argv[i], 0, 0) == NULL) {
      perror("st_thread_create");
      exit(1);
    }
  }

  st_thread_exit(NULL); //Ôõôֱ½Óµ½ÁËÕâÀïÄØ

  /* NOTREACHED ÍøÂç²»¿É´ïå */
  return 1; //òËÆÕâÀïÊdzɹ¦?
}
Example #25
0
hiya_reply_t*
hiya_6_svc(
        prod_class_t *offered,
        struct svc_req *rqstp)
{
    const char* const pqfname = getQueuePath();
    static hiya_reply_t reply;
    SVCXPRT * const xprt = rqstp->rq_xprt;
    struct sockaddr_in *upAddr = (struct sockaddr_in*) svc_getcaller(xprt);
    const char *upName = hostbyaddr(upAddr);
    int error;
    int isPrimary;
    unsigned int maxHereis;
    static prod_class_t *accept;

    /*
     * Open the product-queue for writing.  It will be closed by cleanup()
     * during process termination.
     */
    if (pq) {
        (void) pq_close(pq);
        pq = NULL;
    }
    error = pq_open(pqfname, PQ_DEFAULT, &pq);
    if (error) {
        err_log_and_free(ERR_NEW2(error, NULL,
                "Couldn't open product-queue \"%s\" for writing: %s",
                pqfname,
                PQ_CORRUPT == error
                ? "The product-queue is inconsistent"
                : strerror(error)), ERR_FAILURE);
        svcerr_systemerr(xprt);
        svc_destroy(xprt);
        exit(error);
    }

    /* else */

    error = down6_init(upName, upAddr, pqfname, pq);
    if (error) {
        uerror("Couldn't initialize downstream LDM");
        svcerr_systemerr(xprt);
        svc_destroy(xprt);
        exit(error);
    }
    else {
        uinfo("Downstream LDM initialized");
    }

    /*
     * The previous "accept" is freed here -- rather than freeing the
     * soon-to-be-allocated "accept" at the end of its block -- because it can
     * be used in the reply.
     */
    if (accept) {
        free_prod_class(accept); /* NULL safe */
        accept = NULL;
    }

    error = acl_check_hiya(upName, inet_ntoa(upAddr->sin_addr), offered,
            &accept, &isPrimary);

    maxHereis = isPrimary ? UINT_MAX : 0;

    if (error) {
        serror("Couldn't validate HIYA");
        svcerr_systemerr(xprt);
        svc_destroy(xprt);
        exit(error);
    }
    else {
        if (ulogIsDebug())
            udebug("intersection: %s", s_prod_class(NULL, 0, accept));

        if (accept->psa.psa_len == 0) {
            uwarn("Empty intersection of HIYA offer from %s (%s) and ACCEPT "
                    "entries", upName, s_prod_class(NULL, 0, offered));
            svcerr_weakauth(xprt);
            svc_destroy(xprt);
            exit(0);
        }
        else {
            error = down6_set_prod_class(accept);

            if (error) {
                if (DOWN6_SYSTEM_ERROR == error) {
                    serror("Couldn't set product class: %s",
                            s_prod_class(NULL, 0, accept));
                }
                else {
                    uerror("Couldn't set product class: %s",
                            s_prod_class(NULL, 0, accept));
                }

                svcerr_systemerr(xprt);
                svc_destroy(xprt);
                exit(EXIT_FAILURE);
            }

            /* else */

            if (clss_eq(offered, accept)) {
                unotice("hiya6: %s", s_prod_class(NULL, 0, offered));

                reply.code = OK;
                reply.hiya_reply_t_u.max_hereis = maxHereis;
            }
            else {
                if (ulogIsVerbose()) {
                    char off[512];
                    char acc[512];

                    (void) s_prod_class(off, sizeof(off), offered), (void) s_prod_class(
                            acc, sizeof(acc), accept);

                    uinfo("hiya6: RECLASS: %s -> %s", off, acc);
                }

                reply.code = RECLASS;
                reply.hiya_reply_t_u.feedPar.prod_class = accept;
                reply.hiya_reply_t_u.feedPar.max_hereis = maxHereis;
            }
        } /* product-intersection != empty set */
    } /* successful acl_check_hiya() */

    return &reply;
}
Example #26
0
static int stun_test(const char *server_ip, uint16_t server_port,
		     uint16_t tun_port)
{
	int ret, sock, set = 1;
	uint8_t pkt[256];
	uint8_t rpkt[256];
	size_t len, off, max;
	struct in_addr in;
	struct timeval timeout;
	struct stun_header *hdr, *rhdr;
	struct stun_attrib *attr;
	struct stun_mapped_addr *addr;
	struct sockaddr_in saddr, daddr;
	fd_set fdset;

	if (!server_ip)
		return -EINVAL;

	sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (sock < 0)
		panic("Cannot obtain socket!\n");

	ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set));
	if (ret)
		panic("Cannot set socket option!\n");

	saddr.sin_family = PF_INET;
	saddr.sin_port = htons(tun_port);
	saddr.sin_addr.s_addr = INADDR_ANY;

	ret = bind(sock, (struct sockaddr *) &saddr, sizeof(saddr));
	if (ret)
		panic("Cannot bind udp socket!\n");

	len = REQUEST_LEN;
	hdr = (struct stun_header *) pkt;
	hdr->type = htons(BINDING_REQUEST);
	hdr->len = 0;
	hdr->magic_cookie = ID_COOKIE_FIELD;
	hdr->transid[0] = htonl(rand());
	hdr->transid[1] = htonl(rand());
	hdr->transid[2] = htonl(rand());

	daddr.sin_family = PF_INET;
	daddr.sin_port = htons(server_port);
	daddr.sin_addr.s_addr = inet_addr(server_ip);

	ret = sendto(sock, pkt, len, 0, (struct sockaddr *) &daddr,
		     sizeof(daddr));
	if (ret != len) {
		whine("Error sending request (%s)!\n", strerror(errno));
		return -EIO;
	}

	set_timeout(&timeout, TIMEOUT);

	FD_ZERO(&fdset);
	FD_SET(sock, &fdset);

	ret = select(sock + 1, &fdset, NULL, NULL, &timeout);
	if (ret <= 0) {
		whine("STUN server timeout!\n");
		return -EIO;
	}

	memset(rpkt, 0, sizeof(rpkt));
	len = read(sock, rpkt, sizeof(rpkt));

	close(sock);

	if (len < REQUEST_LEN) {
		whine("Bad STUN response (%s)!\n", strerror(errno));
		return -EIO;
	}

	rhdr = (struct stun_header *) rpkt;
	if (ntohs(rhdr->type) != BINDING_RESPONSE) {
		whine("Wrong STUN response type!\n");
		return -EIO;
	}

	if (rhdr->len == 0) {
		whine("No attributes in STUN response!\n");
		return -EIO;
	}

	if (rhdr->magic_cookie != hdr->magic_cookie ||
	    rhdr->transid[0] != hdr->transid[0] ||
	    rhdr->transid[1] != hdr->transid[1] ||
	    rhdr->transid[2] != hdr->transid[2]) {
		whine("Got wrong STUN transaction id!\n");
		return -EIO;
	}

	off = REQUEST_LEN;
	max = ntohs(rhdr->len) + REQUEST_LEN;

	while (off + 8 < max) {
		attr = (struct stun_attrib *) (rpkt + off);
		if (ntohs(attr->type) != MAPPED_ADDRESS)
			goto next;

		addr = (struct stun_mapped_addr *) (rpkt + off + 4);
		if (addr->family != 0x1)
			break;

		in.s_addr = addr->ip;
		info("Public mapping %s:%u!\n", inet_ntoa(in), ntohs(addr->port));
		break;
next:
		off += 4;
		off += ntohs(attr->len);
	}

	return 0;
}
/**
 * From gnutls and spice red_peer.c
 * TODO: switch to gnutls and get rid of this
 *
 * This function will check if the given certificate's subject matches
 * the given hostname.  This is a basic implementation of the matching
 * described in RFC2818 (HTTPS), which takes into account wildcards,
 * and the DNSName/IPAddress subject alternative name PKIX extension.
 *
 * Returns: 1 for a successful match, and 0 on failure.
 **/
static int verify_hostname(X509* cert, const char *hostname)
{
    GENERAL_NAMES* subject_alt_names;
    int found_dns_name = 0;
    struct in_addr addr;
    int addr_len = 0;
    int cn_match = 0;

    if (!cert) {
        SPICE_DEBUG("warning: no cert!");
        return 0;
    }

    // only IpV4 supported
    if (inet_aton(hostname, &addr)) {
        addr_len = sizeof(struct in_addr);
    }

    /* try matching against:
     *  1) a DNS name as an alternative name (subjectAltName) extension
     *     in the certificate
     *  2) the common name (CN) in the certificate
     *
     *  either of these may be of the form: *.domain.tld
     *
     *  only try (2) if there is no subjectAltName extension of
     *  type dNSName
     */

    /* Check through all included subjectAltName extensions, comparing
     * against all those of type dNSName.
     */
    subject_alt_names = (GENERAL_NAMES*)X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);

    if (subject_alt_names) {
        int num_alts = sk_GENERAL_NAME_num(subject_alt_names);
        int i;
        for (i = 0; i < num_alts; i++) {
            const GENERAL_NAME* name = sk_GENERAL_NAME_value(subject_alt_names, i);
            if (name->type == GEN_DNS) {
                found_dns_name = 1;
                if (_gnutls_hostname_compare((char *)ASN1_STRING_data(name->d.dNSName),
                                             ASN1_STRING_length(name->d.dNSName),
                                             hostname)) {
                    SPICE_DEBUG("alt name match=%s", ASN1_STRING_data(name->d.dNSName));
                    GENERAL_NAMES_free(subject_alt_names);
                    return 1;
                }
            } else if (name->type == GEN_IPADD) {
                int alt_ip_len = ASN1_STRING_length(name->d.iPAddress);
                found_dns_name = 1;
                if ((addr_len == alt_ip_len)&&
                    !memcmp(ASN1_STRING_data(name->d.iPAddress), &addr, addr_len)) {
                    SPICE_DEBUG("alt name IP match=%s",
                                inet_ntoa(*((struct in_addr*)ASN1_STRING_data(name->d.dNSName))));
                    GENERAL_NAMES_free(subject_alt_names);
                    return 1;
                }
            }
        }
        GENERAL_NAMES_free(subject_alt_names);
    }

    if (found_dns_name) {
        SPICE_DEBUG("warning: SubjectAltName mismatch");
        return 0;
    }

    /* extracting commonNames */
    X509_NAME* subject = X509_get_subject_name(cert);
    if (subject) {
        int pos = -1;
        X509_NAME_ENTRY* cn_entry;
        ASN1_STRING* cn_asn1;

        while ((pos = X509_NAME_get_index_by_NID(subject, NID_commonName, pos)) != -1) {
            cn_entry = X509_NAME_get_entry(subject, pos);
            if (!cn_entry) {
                continue;
            }
            cn_asn1 = X509_NAME_ENTRY_get_data(cn_entry);
            if (!cn_asn1) {
                continue;
            }

            if (_gnutls_hostname_compare((char*)ASN1_STRING_data(cn_asn1),
                                         ASN1_STRING_length(cn_asn1),
                                         hostname)) {
                SPICE_DEBUG("common name match=%s", (char*)ASN1_STRING_data(cn_asn1));
                cn_match = 1;
                break;
            }
        }
    }

    if (!cn_match)
        SPICE_DEBUG("warning: common name mismatch");

    return cn_match;
}
Example #28
0
void *recv_thread(void *arg)
{
    int ret = EXIT_SUCCESS;

    char *message;
    int length = 0;

    fd_set fd_connect_set;
    struct timeval tv_connect_timeout;

    int addr_len = sizeof(struct sockaddr_in);

    message = recv_buffer;

    log(LOG_GENERIC, "recv thread created");

    while (1)
    {
        init_socket();

        while (1)
        {
            // try to bind local port
            log(LOG_GENERIC, "bind %s:%d...", 
                inet_ntoa(local_sck_addr.sin_addr), ntohs(local_sck_addr.sin_port));

            ret = bind(sck_fd, (struct sockaddr *)&local_sck_addr, sizeof(struct sockaddr_in));
            if (ret == 0)
            {
                log(LOG_GENERIC, "bind success");
            }
            else
            {
                log(LOG_ERROR, "bind err %d", ret);
            }

            // try to connect remote:
            log(LOG_GENERIC, "trying to connect %s:%d...",
                inet_ntoa(remote_sck_addr.sin_addr), ntohs(remote_sck_addr.sin_port));

            // force socket as non-blocking
            set_socket_blocking_enabled(sck_fd, false);

            ret = connect(sck_fd, (struct sockaddr *)&remote_sck_addr, sizeof(struct sockaddr_in));
            if (ret < 0)
            {
                if (WSAGetLastError() == WSAEWOULDBLOCK)	//EINPROGRESS
                {
                    tv_connect_timeout.tv_sec = 1; 
                    tv_connect_timeout.tv_usec = 0;

                    FD_ZERO(&fd_connect_set); 
                    FD_SET(sck_fd, &fd_connect_set);

                    // wait 1 seconds:
                    ret = select(sck_fd + 1, NULL, &fd_connect_set, NULL, &tv_connect_timeout);

                    if (ret <= 0)
                    {
                        log(LOG_GENERIC, "connect too slow, reinit socket");
                        deinit_socket();
                        init_socket();
                    }
                    else
                    { // connected
                        break;
                    }
                }
                else
                {
                    log(LOG_ERROR, "connect err %d", ret);
                }
            }
            else if (ret == 0)
            {
                break;
            }

            usleep(CONNECT_RETRY_DELAY);
        }

        // force socket as blocking
        set_socket_blocking_enabled(sck_fd, true);

        log(LOG_GENERIC, "connected");
        usleep(CONNECTED_DELAY);

        send_hunter_message(HUNT_MSG_CONNECTED);

        while (1)
        {
            // blocking socket:
            ret = recv(sck_fd, recv_buffer, MAX_SOCK_BUFFER, 0);
            if (ret > 0)
            {
                length = ret;
            }
            else if (ret == 0)
            {
                // orderly shutdown
                log(LOG_ERROR, "recv shutdown");
                break;
            }
            else
            { // ret < 0, typically -1
                // an error occurred
                log(LOG_ERROR, "recv error %d", ret);
            }

#ifdef sock_DEBUG
            log(LOG_GENERIC, "Receive %d:%s", length, message);
#endif // sock_DEBUG

            // once received, we call handler:
            sock_receive(message, length);

            // check how much time is wasted on receive module
        }

        log(LOG_GENERIC, "disconnect");

        // we should gently close socket, and try to connect again
        closesocket(sck_fd);
    }

    log(LOG_GENERIC, "recv thread exit");
}
main()
{
	longword seq,ping_who,tmp_seq,time_out;
	char	buffer[100];


	brdInit();				//initialize board for this demo
	seq=0;

	sock_init();			// Initialize wifi interface

   // Make sure wifi IF is down to do ifconfig's functions
	printf("\nBringing interface down (disassociate)...\n");
   ifdown(IF_WIFI0);
   while (ifpending(IF_WIFI0) != IF_DOWN) {
     	printf(".");
     	tcp_tick(NULL);
   }
	printf("...Done.\n");

   // Enable 802.11d country information capability
   // Note: Access Point must have 802.11d enabled with proper country selected
   ifconfig(IF_WIFI0, IFS_WIFI_MULTI_DOMAIN, 1, IFS_END);

   // Startup the  wireless interface here...
	printf("Bringing interface back up (associate)...\n");
   ifup(IF_WIFI0);
   while (ifpending(IF_WIFI0) == IF_COMING_UP) {
      tcp_tick(NULL);
   }
	printf("...Done.\n");
	if (ifpending(IF_WIFI0) != IF_UP) {
		printf("Unfortunately, it failed to associate :-(\n");
		exit(1);
	}
   // End of regional setting section, from this point on do standard tcp/ip
   // protocol.


   /*
   // Here is where we gather the statistics...
	// Note that if you get a compile error here, it is because you are not running
	// this sample on a Wifi-equipped board.

	/* Print who we are... */
	printf( "My IP address is %s\n\n", inet_ntoa(buffer, gethostid()) );

	/*
	 *		Get the binary ip address for the target of our
	 *		pinging.
	 */

#ifdef PING_WHO
	/* Ping a specific IP addr: */
	ping_who=resolve(PING_WHO);
	if(ping_who==0) {
		printf("ERROR: unable to resolve %s\n",PING_WHO);
		exit(2);
	}
#else
	/* Examine our configuration, and ping the default router: */
	tmp_seq = ifconfig( IF_ANY, IFG_ROUTER_DEFAULT, & ping_who, IFS_END );
	if( tmp_seq != 0 ) {
		printf( "ERROR: ifconfig() failed --> %d\n", (int) tmp_seq );
		exit(2);
	}
	if(ping_who==0) {
		printf("ERROR: unable to resolve IFG_ROUTER_DEFAULT\n");
		exit(2);
	}
#endif

	for(;;) {
		/*
		 *		It is important to call tcp_tick here because
		 *		ping packets will not get processed otherwise.
		 *
		 */

		tcp_tick(NULL);

		/*
		 *		Send one ping every PING_DELAY ms.
		 */

		costate {
			waitfor(DelayMs(PING_DELAY));
			pingoutled(LEDON);					// flash transmit LED
			waitfor(DelayMs(50));
			pingoutled(LEDOFF);
			_ping(ping_who,seq++);
		}

		/*
		 *		Has a ping come in?  time_out!=0xfffffff->yes.
		 */

		costate {
			time_out=_chk_ping(ping_who,&tmp_seq);
			if(time_out!=0xffffffff) {

#ifdef VERBOSE
				printf("received ping:  %ld\n", tmp_seq);
#endif

				pinginled(LEDON);					// flash receive LED
				waitfor(DelayMs(50));
				pinginled(LEDOFF);
#if RCM5600W_SERIES
				waitfor(DelayMs(250));
				pinginled(LEDON);					// flash receive LED again
				waitfor(DelayMs(50));
				pinginled(LEDOFF);
#endif
			}
		}
	}
}
Example #30
0
int main()
{
	SOCKET sniffer;
	struct in_addr addr;
	int in;
	
	char hostname[100];
	struct hostent *local;
	WSADATA wsa;
	
	// Init Winsock
	printf("\nInitialising Winsock... ");
	if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
		printf("WSAStartup() failed.\n");
		return 1;
	}
	printf("done\n");
	
	// Create a RAW Socket
	printf("Creating RAW Socket... ");
	//sniffer = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
	sniffer = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
	if (sniffer == INVALID_SOCKET) {
		printf("Failed to create raw socket.\n");
		return 1;
	}
	printf("Created.\n");
	
	// Retrive the local hostname
	if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
		printf("Error : %d\n", WSAGetLastError());
		return 1;
	}
	printf("\nHost name : %s\n",hostname);
	
	// Retrive the available IPs of the local host
	local = gethostbyname(hostname);
	printf("\nAvailable Network Interfaces : \n");
	if (local == NULL) {
		printf("Error : %d\n", WSAGetLastError());
		return 1;
	}
	
	for (i = 0; local->h_addr_list[i] != 0; ++i) {
		memcpy(&addr, local->h_addr_list[i], sizeof(struct in_addr));
		printf("Interface Number : %d Address : %s\n", i, inet_ntoa(addr));
	}
	
	printf("Enter the interface number you would like to sniff : ");
	scanf("%d",&in);
	
	memset(&dest, 0, sizeof(dest));
	memcpy(&dest.sin_addr.s_addr, local->h_addr_list[in], sizeof(dest.sin_addr.s_addr));
	dest.sin_family = AF_INET;
	dest.sin_port = 0;
	
	printf("\nBinding socket to local system and port 0... ");
	if (bind(sniffer,(struct sockaddr *)&dest,sizeof(dest)) == SOCKET_ERROR)
	{
		printf("bind(%s) failed.\n", inet_ntoa(addr));
		return 1;
	}
	printf("Binding successful\n");
	
	// Enable this socket with the power to sniff : SIO_RCVALL is the key Receive ALL ;)
	
	j=1;
	printf("Setting socket to sniff...");
	if (WSAIoctl(sniffer, SIO_RCVALL, &j, sizeof(j), 0, 0, (LPDWORD) &in , 0 , 0) == SOCKET_ERROR)
	{
		printf("WSAIoctl() failed.\n");
		return 1;
	}
	printf("Socket set.\n");
	
	// Begin
	printf("Started Sniffing\n");
	printf("Packet Capture Statistics...\n");
	packet_recv(sniffer); //Happy Sniffing
	
	// End
	closesocket(sniffer);
	WSACleanup();
	
	return 0;
}