Пример #1
0
Файл: main.c Проект: Spectus97/C
/* Set pin to HIGH */
void set_pin(uint32_t p)
{
    volatile uint32_t *set_register = ADDR_OFFSET(&FIO0SET, 0x20 * GET_PORT(p));
    volatile uint32_t *mask_register = ADDR_OFFSET(&FIO0MASK, 0x20 * GET_PORT(p));

    *mask_register = ~(1 << GET_PIN(p)); /* Affected pin are those whose mask is 0 */
    *set_register = (1 << GET_PIN(p)); /* Set pin to HIGH */
}
Пример #2
0
Файл: main.c Проект: Spectus97/C
/* Clear pin to GND */
void clr_pin(uint32_t p)
{
    volatile uint32_t *clr_register = ADDR_OFFSET(&FIO0CLR, 0x20 * GET_PORT(p));
    volatile uint32_t *mask_register = ADDR_OFFSET(&FIO0MASK, 0x20 * GET_PORT(p));

    *mask_register = ~(1 << GET_PIN(p)); /* Affected pin are those whose mask is 0 */
    *clr_register = (1 << GET_PIN(p)); /* Set pin to GND */
}
Пример #3
0
void updateLedStatus( unsigned long ledStatus )
{
    LED_PORT1 = ~( GET_PORT( 1 , ledStatus ) );
    LED_PORT2 = ~( GET_PORT( 2 , ledStatus ) );
    LED_PORT3 = ~( GET_PORT( 3 , ledStatus ) );
    LED_PORT4 = ~( GET_PORT( 4 , ledStatus ) );

}
/*
 * Class:     java_net_DualStackPlainDatagramSocketImpl
 * Method:    socketLocalPort
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_java_net_DualStackPlainDatagramSocketImpl_socketLocalPort
  (JNIEnv *env, jclass clazz, jint fd) {
    SOCKETADDRESS sa;
    int len = sizeof(sa);

    if (getsockname(fd, (struct sockaddr *)&sa, &len) == SOCKET_ERROR) {
        NET_ThrowNew(env, WSAGetLastError(), "JVM_GetSockName");
        return -1;
    }
    return (int) ntohs((u_short)GET_PORT(&sa));
}
Пример #5
0
Файл: main.c Проект: dusartc/tpC
void select_gpio_out_mode(uint32_t p) {
    uint32_t register_idx = 2*GET_PORT(p);
    uint32_t pin = GET_PIN(p);
    volatile uint32_t *dir_register;

    if (pin >= 16)
    {
    	pin -= 16;
    	register_idx++;
    }
    /* Configure function */
    PINSEL[register_idx] &= ~(3 << (pin * 2)); /* Clear the two function bits -> gpio mode (p. 108) */

    /* Configure mode */
    PINMODE[register_idx] &= ~(3 << (pin * 2)); /* Clear the two mode bit -> pull-up resistor */

    /* Configure opendrain */
    PINMODE_OD[GET_PORT(p)] &= ~(1 << GET_PIN(p)); /* Clear bit -> normal (not opendrain) mode */

    /* Set GPIO mode to output */
    dir_register = ADDR_OFFSET(&FIO0DIR, 0x20 * GET_PORT(p));
    *dir_register |= (1 << GET_PIN(p)); /* set bit to 1 -> set pin to output */
}
Пример #6
0
CELL make_port(char mode, FILE* fp, char* path)
{
    const int len = strlen(path);
	CELL cell = gc_alloc_extra(PORT, len + 1);
	PORT* p = GET_PORT(cell);
    p->pad_reloc = V_EMPTY;
    p->next_resource = gc_chain_resource(cell);
    p->mark = 0;

	p->mode = mode;
    p->fp = fp;
    p->len = len;
    strcpy(p->data, path);
    return cell;
}
/*
 * Class:     java_net_DualStackPlainSocketImpl
 * Method:    localPort0
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_java_net_DualStackPlainSocketImpl_localPort0
  (JNIEnv *env, jclass clazz, jint fd) {
    SOCKETADDRESS sa;
    int len = sizeof(sa);

    if (getsockname(fd, (struct sockaddr *)&sa, &len) == SOCKET_ERROR) {
        if (WSAGetLastError() == WSAENOTSOCK) {
            JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
                    "Socket closed");
        } else {
            NET_ThrowNew(env, WSAGetLastError(), "getsockname failed");
        }
        return -1;
    }
    return (int) ntohs((u_short)GET_PORT(&sa));
}
/*
 * Class:     java_net_DualStackPlainDatagramSocketImpl
 * Method:    socketReceiveOrPeekData
 * Signature: (ILjava/net/DatagramPacket;IZZ)I
 */
JNIEXPORT jint JNICALL Java_java_net_DualStackPlainDatagramSocketImpl_socketReceiveOrPeekData
  (JNIEnv *env, jclass clazz, jint fd, jobject dpObj,
   jint timeout, jboolean connected, jboolean peek) {
    SOCKETADDRESS sa;
    int sa_len = sizeof(sa);
    int port, rv, flags=0;
    char BUF[MAX_BUFFER_LEN];
    char *fullPacket;
    BOOL retry;
    jlong prevTime = 0;

    jint packetBufferOffset, packetBufferLen;
    jbyteArray packetBuffer;

    /* if we are only peeking. Called from peekData */
    if (peek) {
        flags = MSG_PEEK;
    }

    packetBuffer = (*env)->GetObjectField(env, dpObj, dp_bufID);
    packetBufferOffset = (*env)->GetIntField(env, dpObj, dp_offsetID);
    packetBufferLen = (*env)->GetIntField(env, dpObj, dp_bufLengthID);
    /* Note: the buffer needn't be greater than 65,536 (0xFFFF)
    * the max size of an IP packet. Anything bigger is truncated anyway.
    */
    if (packetBufferLen > MAX_PACKET_LEN) {
        packetBufferLen = MAX_PACKET_LEN;
    }

    if (packetBufferLen > MAX_BUFFER_LEN) {
        fullPacket = (char *)malloc(packetBufferLen);
        if (!fullPacket) {
            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed");
            return -1;
        }
    } else {
        fullPacket = &(BUF[0]);
    }

    do {
        retry = FALSE;

        if (timeout) {
            if (prevTime == 0) {
                prevTime = JVM_CurrentTimeMillis(env, 0);
            }
            rv = NET_Timeout(fd, timeout);
            if (rv <= 0) {
                if (rv == 0) {
                    JNU_ThrowByName(env,JNU_JAVANETPKG "SocketTimeoutException",
                                    "Receive timed out");
                } else if (rv == JVM_IO_ERR) {
                    JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
                                    "Socket closed");
                } else if (rv == JVM_IO_INTR) {
                    JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException",
                                    "operation interrupted");
                }
                if (packetBufferLen > MAX_BUFFER_LEN) {
                    free(fullPacket);
                }
                return -1;
            }
        }

        /* receive the packet */
        rv = recvfrom(fd, fullPacket, packetBufferLen, flags,
                    (struct sockaddr *)&sa, &sa_len);

        if (rv == SOCKET_ERROR && (WSAGetLastError() == WSAECONNRESET)) {
            /* An icmp port unreachable - we must receive this as Windows
             * does not reset the state of the socket until this has been
             * received.
             */
            purgeOutstandingICMP(env, fd);

            if (connected) {
                JNU_ThrowByName(env, JNU_JAVANETPKG "PortUnreachableException",
                                "ICMP Port Unreachable");
                if (packetBufferLen > MAX_BUFFER_LEN)
                    free(fullPacket);
                return -1;
            } else if (timeout) {
                /* Adjust timeout */
                jlong newTime = JVM_CurrentTimeMillis(env, 0);
                timeout -= (jint)(newTime - prevTime);
                if (timeout <= 0) {
                    JNU_ThrowByName(env, JNU_JAVANETPKG "SocketTimeoutException",
                                    "Receive timed out");
                    if (packetBufferLen > MAX_BUFFER_LEN)
                        free(fullPacket);
                    return -1;
                }
                prevTime = newTime;
            }
            retry = TRUE;
        }
    } while (retry);

    port = (int) ntohs ((u_short) GET_PORT((SOCKETADDRESS *)&sa));

    /* truncate the data if the packet's length is too small */
    if (rv > packetBufferLen) {
        rv = packetBufferLen;
    }
    if (rv < 0) {
        if (WSAGetLastError() == WSAEMSGSIZE) {
            /* it is because the buffer is too small. It's UDP, it's
             * unreliable, it's all good. discard the rest of the
             * data..
             */
            rv = packetBufferLen;
        } else {
            /* failure */
            (*env)->SetIntField(env, dpObj, dp_lengthID, 0);
        }
    }

    if (rv == -1) {
        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "socket closed");
    } else if (rv == -2) {
        JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException",
                        "operation interrupted");
    } else if (rv < 0) {
        NET_ThrowCurrent(env, "Datagram receive failed");
    } else {
        jobject packetAddress;
        /*
         * Check if there is an InetAddress already associated with this
         * packet. If so, we check if it is the same source address. We
         * can't update any existing InetAddress because it is immutable
         */
        packetAddress = (*env)->GetObjectField(env, dpObj, dp_addressID);
        if (packetAddress != NULL) {
            if (!NET_SockaddrEqualsInetAddress(env, (struct sockaddr *)&sa,
                                               packetAddress)) {
                /* force a new InetAddress to be created */
                packetAddress = NULL;
            }
        }
        if (packetAddress == NULL) {
            packetAddress = NET_SockaddrToInetAddress(env, (struct sockaddr *)&sa,
                                                      &port);
            if (packetAddress != NULL) {
                /* stuff the new Inetaddress into the packet */
                (*env)->SetObjectField(env, dpObj, dp_addressID, packetAddress);
            }
        }

        if (!(*env)->ExceptionCheck(env)) {
            /* populate the packet */
            (*env)->SetByteArrayRegion(env, packetBuffer, packetBufferOffset, rv,
                                   (jbyte *)fullPacket);
            (*env)->SetIntField(env, dpObj, dp_portID, port);
            (*env)->SetIntField(env, dpObj, dp_lengthID, rv);
        }
    }

    if (packetBufferLen > MAX_BUFFER_LEN) {
        free(fullPacket);
    }
    return port;
}
Пример #9
0
void __attribute__((naked)) isr_fault()
{
	/* disable interrupts */
	/* save registers */

	unsigned int sp, lr, psr, usp;

	sp  = __get_sp();
	psr = __get_psr();
	lr  = __get_lr();
	usp = __get_usp();

	debug(MSG_ERROR, "\nFault type: %x <%08x>\n"
		"  (%x=Usage fault, %x=Bus fault, %x=Memory management fault)",
		SCB_SHCSR & 0xfff, SCB_SHCSR, USAGE_FAULT, BUS_FAULT, MM_FAULT);

	debug(MSG_ERROR, "Fault source: ");
	busfault();
	usagefault();

	printk("\nKernel Space\n");
	print_kernel_status((unsigned int *)sp, lr, psr);

	printk("\nUser Space\n");
	print_user_status((unsigned int *)usp);

	printk("\nTask Status\n");
	print_task_status(current);

	printk("\nCurrent Context\n");
	print_context((unsigned int *)usp);

	printk("\nSCB_ICSR  0x%08x\n"
		"SCB_CFSR  0x%08x\n"
		"SCB_HFSR  0x%08x\n"
		"SCB_MMFAR 0x%08x\n"
		"SCB_BFAR  0x%08x\n",
		SCB_ICSR, SCB_CFSR, SCB_HFSR, SCB_MMFAR, SCB_BFAR);

	/* led for debugging */
#ifdef LED_DEBUG
	SET_PORT_CLOCK(ENABLE, PORTD);
	SET_PORT_PIN(PORTD, 2, PIN_OUTPUT_50MHZ);
	unsigned int j;
	while (1) {
		PUT_PORT(PORTD, GET_PORT(PORTD) ^ 4);

		for (i = 100; i; i--) {
			for (j = 10; j; j--) {
				__asm__ __volatile__(
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						::: "memory");
			}
		}
	}
#endif

	while (1);

	/* restore registers */
	/* enable interrupts */
}
Пример #10
0
void gpio_set_value(uint32_t gpio, uint32_t value)
{
	rt_hw_gpio_set(GET_PORT(gpio), GET_PIN(gpio), value);
}
Пример #11
0
void en_socket_stream_connect (EIF_INTEGER *a_fd, EIF_INTEGER *a_fd1, EIF_INTEGER *a_local_port, EIF_POINTER sockaddr, EIF_INTEGER timeout, EIF_BOOLEAN is_blocking) {

	SOCKETADDRESS* him;
	int family;
	SOCKET fd, fd1 = INVALID_SOCKET;
	int ipv6_supported;
	int connect_res;

	EIF_NET_INITIALIZE;

	ipv6_supported = en_ipv6_available();

	fd = (SOCKET) *a_fd;
	if (ipv6_supported) {
		fd1 = *a_fd1;
	}

	him = (SOCKETADDRESS*) sockaddr;

	family = him->him.sa_family; 
	if (family == AF_INET6) {
		if (!ipv6_supported) {
			eraise ("Protocol family not supported", EN_PROG);
			return;
		} else {
			if (fd1 == -1) {
				eraise ("Destination unreachable", EN_PROG);
				return;
			}
				/* close the v4 socket, and set fd to be the v6 socket */
			*a_fd = (EIF_INTEGER) fd1;
			*a_fd1 = -1;
			net_socket_close(fd); 
			fd = fd1;
		}
	} else {
		if (fd1 != -1) {
				/* close the v6 socket */
			*a_fd1 = -1;
			net_socket_close(fd1); 
		}
		if (fd == INVALID_SOCKET) {
			eraise ("Destination unreachable", EN_PROG);
			return;
		} 
	}

	if (timeout <= 0) {
		connect_res = connect(fd, (struct sockaddr *) him, SOCKETADDRESS_LEN(him));
		if (connect_res == SOCKET_ERROR) {
			connect_res = WSAGetLastError();
			if ((connect_res == WSAEWOULDBLOCK) || (connect_res == WSAEINPROGRESS)) {
				connect_res = 0;
				errno = 0;
			}
		}
	} else {
		u_long optval;
		int optlen = sizeof(int);

			/* make socket non-blocking */
		if (is_blocking) {
			optval = 1;
			ioctlsocket( fd, FIONBIO, &optval );
		}

			/* initiate the connect */
		connect_res = connect(fd, (struct sockaddr *) him, SOCKETADDRESS_LEN(him));
		if (connect_res == SOCKET_ERROR) {
			if (WSAGetLastError() == WSAEWOULDBLOCK) {
				fd_set wr, ex;
				struct timeval t;

				FD_ZERO(&wr);
				FD_ZERO(&ex);
				FD_SET(fd, &wr);
				FD_SET(fd, &ex);
				t.tv_sec = timeout / 1000;
				t.tv_usec = (timeout % 1000) * 1000;

					/* Wait for timout, connection established or
					 * connection failed. */
				connect_res = select((int) fd+1, 0, &wr, &ex, &t);

				/* Timeout before connection is established/failed so
				 * we throw exception and shutdown input/output to prevent
				 * socket from being used.
				 * The socket should be closed immediately by the caller. */
				if (connect_res == 0) {
					shutdown( fd, SD_BOTH );
					if (is_blocking) {
							/* make socket blocking again - just in case */
						optval = 0;
						ioctlsocket( fd, FIONBIO, &optval );
					}
					eraise("connect timed out", EN_PROG);
					return;
				}

					/* We must now determine if the connection has been established
					 * or if it has failed. The logic here is designed to work around
					 * bug on Windows NT whereby using getsockopt to obtain the 
					 * last error (SO_ERROR) indicates there is no error. The workaround
					 * on NT is to allow winsock to be scheduled and this is done by
					 * yielding and retrying. As yielding is problematic in heavy
					 * load conditions we attempt up to 3 times to get the error reason. */
				if (!FD_ISSET(fd, &ex)) {
					connect_res = 0;
				} else {
					int retry;
					for (retry=0; retry<3; retry++) {
						net_get_sock_opt(fd, SOL_SOCKET, SO_ERROR, (char*)&connect_res, &optlen);
						if (connect_res) {
							break;
						}
						Sleep(0);
					}

					if (connect_res == 0) {
						eraise("Unable to establish connection", EN_PROG);
						return;
					}
				}
			}
		}

		if (is_blocking) {
				/* make socket blocking again */
			optval = 0;
			ioctlsocket(fd, FIONBIO, &optval);
		}
	}

	if (connect_res) {
		if (connect_res == WSAEADDRNOTAVAIL) {
			eraise("Address is invalid on local machine, or port is not valid on remote machine", EN_PROG);
		} else {
			eraise("Unable to establish connection", EN_PROG);
		}
		return;
	}

	*a_fd = (EIF_INTEGER) fd;

		/* we need to initialize the local port field if bind was called
		 * previously to the connect (by the client) then localport field
		 * will already be initialized. */
	if (*a_local_port == 0) {
			/* Now that we're a connected socket, let's extract the port number
			 * that the system chose for us and store it in the Socket object. */
		u_short port;
		int len = SOCKETADDRESS_LEN(him);
		if (getsockname(fd, (struct sockaddr *)him, &len) == -1) {
			if (WSAGetLastError() == WSAENOTSOCK) {
				eraise("Socket closed", EN_PROG);
			} else {
				eraise("getsockname failed", EN_PROG);
			}
			return;
		}
		port = ntohs (GET_PORT(him));
		*a_local_port = port;
	}
}
Пример #12
0
uint32_t gpio_direction_input(uint32_t gpio)
{
	rt_hw_gpio_init(GET_PORT(gpio), GET_PIN(gpio),INPUT_DIRECTION);
	return rt_hw_gpio_get(GET_PORT(gpio), GET_PIN(gpio));
}
Пример #13
0
uint32_t gpio_get_value(uint32_t gpio)
{
	return rt_hw_gpio_get(GET_PORT(gpio), GET_PIN(gpio));
}
Пример #14
0
void *udpSock(void *param)
		{
	PRINTD(1,"udpSock: udpSock started\n");
#ifdef WIN32
	
	int first = 1;
#endif
	
	HANDLE hComm = 0;

	
	paramThread *paraThread;

	
	paraThread = (paramThread *) param;
	
	int sock = 0;
	
	unsigned char payload[MAX_PAYLOAD_SIZE];
	
	struct info *infos = (struct info *) calloc(logbuffer_size, sizeof(info));
	
	struct addrinfo SrcAddress;
	
	in_port_t tmpPort = 0;
	
	int size_r = 0;
	
	unsigned char *ptrSeqNum = payload + sizeof(uint32_t);			
	
	unsigned char *ptrTimeSec = ptrSeqNum + sizeof(uint32_t);		
	
	unsigned char *ptrTimeUsec = ptrTimeSec + sizeof(uint32_t);		
	
	struct timeval RcvTime;
#ifdef WIN32
	

	
	LARGE_INTEGER _tstart, _tend;
	

	
	unsigned long secs = 0, msecs = 0;
#endif
	
	paraThread->addressInfos = infos;
	
	paraThread->count = 0;

	if (strcmp(paraThread->serial, "noSerial") != 0) {
		hComm = serialUp(paraThread->serial);
		if (hComm == INVALID_HANDLE_VALUE)
			printf("Error opening interface %s \n", paraThread->serial);
	}

	bool socketAlreadyOpen = false;
#ifdef MULTIPORT

	if ((passiveMode == false) && (paraThread->indexPort > 0))
			{
		MUTEX_THREAD_LOCK(sharedUdpSockets[paraThread->indexPort].mutexSharedSockets);

		sock = sharedUdpSockets[paraThread->indexPort].socket;

		if (sock > 0)
				{
			socketAlreadyOpen = true;
		}
	}

#endif

	
	if (socketAlreadyOpen == false) {
		sock = socket(paraThread->destHost.ai_family, SOCK_DGRAM, 0);
		if (paraThread->dsByte
				&& (paraThread->destHost.ai_family == AF_INET)
				&& setsockopt(sock, SOL_IP, IP_TOS, (char *) &paraThread->dsByte, sizeof(BYTE)) < 0) {
			printf("** WARNING ** Flow %d. Could not set DS byte to: %d\n", paraThread->flowId, paraThread->dsByte);
		}
	}

	if (sock < 0)
		reportErrorAndExit("udpSock", "socket", "Cannot create a DATAGRAM socket on port");

	if ((passiveMode == false) && (socketAlreadyOpen == false))
			{

		if (bind(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) {
			
			printf("Error into bind function!\n");
			struct pipeMsg msg;
			msg.code = MSG_FT_ERR1;
			msg.flowId = paraThread->flowId;
			if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
				printf(" sending msg error");
			}
			sleep(INFINITE);
		}
		else
		{
			
#ifdef WIN32
			int len=paraThread->destHost.ai_addrlen;
			getsockname(sock,paraThread->destHost.ai_addr,&len);
			paraThread->destHost.ai_addrlen=len;
#else
			getsockname(sock, paraThread->destHost.ai_addr, &(paraThread->destHost.ai_addrlen));
#endif

			
			GET_PORT((&(paraThread->destHost)), tmpPort);
			fprintf(stderr, "Listening on UDP port : %d\n", ntohs(tmpPort));
			fflush(stderr);

#ifdef MULTIPORT
			if (paraThread->indexPort == 0)
					{
				paraThread->indexPort = ntohs(tmpPort);
				MUTEX_THREAD_LOCK(sharedUdpSockets[paraThread->indexPort].mutexSharedSockets);
			}
#endif

			
			struct pipeMsg msg;
			msg.code = MSG_FT_OK;
			msg.flowId = paraThread->flowId;
			if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
				printf("error sending msg to signal manager");
			}
		}

	}
	
	else if (passiveMode == true) {
		struct addrinfo *addrForListen = NULL;

//#if (defined WIN32 && defined IPv6RECV) || defined UNIX || defined BSD
		if (paraThread->destHost.ai_family == PF_INET6) {
			getaddrinfo("::", NULL, &hint, &addrForListen);
		} else
//#endif
		{
			getaddrinfo("0.0.0.0", NULL, &hint, &addrForListen);
		}

		
		SET_PORT((addrForListen), htons((paraThread->portForPssv)));

		
		if (bind(sock, addrForListen->ai_addr, addrForListen->ai_addrlen) < 0) {
			
			struct pipeMsg msg;

			msg.code = MSG_FT_ERR1;
			msg.flowId = paraThread->flowId;
			if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
				printf(" sending msg error");
			}
			sleep(INFINITE); 
		} else {
			
			GET_PORT(( addrForListen), tmpPort);
			printf("Listening on UDP port : %d\n", ntohs(tmpPort));
			fflush(stdout);
			
			for (int x = 0; x < numHolePkt; x++) {
				if (sendto(sock, "hello", sizeof("hello"), 0, paraThread->destHost.ai_addr,
						paraThread->destHost.ai_addrlen) < 0) {
					reportErrorAndExit("udpSock", "sendto", "Cannot sendto (Passive Mode --> Hole punching)");
				}
			}
		}

		
		if (connect(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) {
			reportErrorAndExit("udpSock", "connect", "Cannot connect (Passive Mode)");
		}
		freeaddrinfo(addrForListen);
	}
#ifdef MULTIPORT
	else if ((passiveMode == false) && (socketAlreadyOpen == true)) {
		
		struct pipeMsg msg;
		msg.code = MSG_FT_OK;
		msg.flowId = paraThread->flowId;
		if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
			printf("error sending msg to signal manager");
		}
	}

	if (passiveMode == false) {
		
		if (socketAlreadyOpen == false) {
			sharedUdpSockets[paraThread->indexPort].socket = sock;
		}

		sharedUdpSockets[paraThread->indexPort].inUse++;

		MUTEX_THREAD_UNLOCK(sharedUdpSockets[paraThread->indexPort].mutexSharedSockets);
	}
#endif
	

//#if defined UNIX && ! defined BSD
	
	if ((paraThread->iface) && (socketAlreadyOpen == false)) {
		printf("Binding to device %s\n", paraThread->iface);
		if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, paraThread->iface, strlen(paraThread->iface)) < 0) {
			printf("** WARNING ** Cannot bind to device %s (hint: you must be root)\n", paraThread->iface);
			fflush(stdout);
		}
	}
//#endif

	
	paraThread->socketClose = sock;
	
	SrcAddress.ai_family = paraThread->destHost.ai_family;
	
	if (SrcAddress.ai_family == PF_INET) {
		
		SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in));
		
		SrcAddress.ai_addrlen = sizeof(struct sockaddr_in);
		
	} else if (SrcAddress.ai_family == PF_INET6) {
		
		SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in6));
		
		SrcAddress.ai_addrlen = sizeof(struct sockaddr_in6);
	}

	pthread_cleanup_push(free, SrcAddress.ai_addr);

		int firstpacket = 1;
		char HelpSrcAddress[INET6_ADDRSTRLEN];
		char HelpDstAddress[INET6_ADDRSTRLEN];
		int tmpPort_SrcPort = 0;
		int tmpPort_DstPort = 0;

		
		
		TSTART(_tstart, secs, msecs, first, 0, RECEIVER);

		PRINTD(1,"udpSock: main loop\n");
		
		while (1) {
			if (passiveMode == false) {									
				
				size_r = recvfrom(sock, (char *) payload, MAX_PAYLOAD_SIZE, 0, SrcAddress.ai_addr,
						(socklen_t *) &SrcAddress.ai_addrlen);
			} else {
						
				size_r = recvfrom(sock, (char *) payload, MAX_PAYLOAD_SIZE, 0, NULL, NULL);	
			}												
			PRINTD(2,"udpSock: Received DATAGRAM packet\n");

			if (size_r < 0) {
				PRINTD(1,"\nudpSock: Error:%s\n",strerror(errno));
				
				
#ifndef OSX
				reportErrorAndExit("udpSock", "recvfrom", "Cannot receive UDP packets");
#else
				sleep(INFINITE);
#endif
			}

			if (hComm > 0) {
				DTR_Disable(hComm);
				DTR_Enable(hComm);
			}

			
			GET_TIME_OF_DAY(&RcvTime, _tend, _tstart, secs, msecs, 0, RECEIVER);
			

			
			if ((logCheck != 0) || (logRemote != 0)) {
				if (firstpacket == 1) {
					if (passiveMode == false) {
						getInfo(&SrcAddress, tmpPort_SrcPort, HelpSrcAddress);
						getInfo(&paraThread->destHost, tmpPort_DstPort, HelpDstAddress);
					} else {
						
#ifdef WIN32
						int len=SrcAddress.ai_addrlen;						
						getsockname(sock,SrcAddress.ai_addr,&len);
						SrcAddress.ai_addrlen=len;
#else
						getsockname(sock, SrcAddress.ai_addr, &SrcAddress.ai_addrlen);		
#endif
						getInfo(&paraThread->destHost, tmpPort_SrcPort, HelpSrcAddress);	
						getInfo(&SrcAddress, tmpPort_DstPort, HelpDstAddress);			
					}
					firstpacket = 0;
				}
#ifdef MULTIPORT
				else if (passiveMode == false) {
					getInfo(&SrcAddress, tmpPort_SrcPort, HelpSrcAddress);
				}
#endif
				
				if (logCheck != 0) {
					int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); 
					int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); 

					if (paraThread->payloadLogType == PL_STANDARD) { 	
						writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload,
								*(uint32_t *) ptrSeqNum,
								HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort,
								net_TimeSec,
								RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size_r);	
					} else if (paraThread->payloadLogType == PL_SHORT) {	
						writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload,
								*(uint32_t *) ptrSeqNum,
								HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort,
								RcvTime.tv_sec % 86400L,
								RcvTime.tv_usec, size_r);						
					} else {
						
						
						writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress,
								HelpDstAddress,
								tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L,
								RcvTime.tv_usec, size_r);
					}
				}
				
				
				
				if (logRemote != 0) {
					int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); 
					int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); 

					if (paraThread->payloadLogType == PL_STANDARD) { 	
						writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload,
								*(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
								tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L,
								net_TimeUsec, RcvTime.tv_usec, size_r); 				
					} else if (paraThread->payloadLogType == PL_SHORT) {	
						writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload,
								*(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
								tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L,
								RcvTime.tv_usec, size_r); 						
					} else {
						
						
						writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress,
								HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort,
								RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size_r);
					}
					infosHostToNet(&infos[paraThread->count]);
				}
				
				
				paraThread->count++;
				
				if (paraThread->count == logbuffer_size) {
					
					if (logCheck != 0)
						flushBuffer((ofstream *) paraThread->fileLog, infos, paraThread->count);
					
					else
					if (logRemote != 0)
							{
						MUTEX_THREAD_LOCK(mutexLogRem);

						if (sendto(paraThread->logSock, (char *) infos,
								paraThread->count * sizeof(struct info), 0,
								paraThread->logHost->ai_addr, paraThread->logHost->ai_addrlen) < 0)
							reportErrorAndExit("udpSock", "sendto", "Cannot send log infos to LogServer");

						paraThread->count = 0;

						MUTEX_THREAD_UNLOCK(mutexLogRem);

						PRINTD(1,"udpSock: Sent Infos to LogServer\n");
					}
				} 
			} 
			
			if (paraThread->meter == METER_RTTM) {
				if (passiveMode == false) {								
					if (sendto(sock, (char *) payload, size_r, 0, SrcAddress.ai_addr, SrcAddress.ai_addrlen) < 0)
						reportErrorAndExit("udpSock", "sendto", "Cannot send back payload for rttm");
				} else {										
					if (sendto(sock, (char *) payload, size_r, 0, NULL, 0) < 0)			
						reportErrorAndExit("udpSock", "sendto",
								"Cannot send back payload for rttm (Passive Mode)");	
				}											
				PRINTD(2,"udpSock: Sent RTTM message\n");
			} 
		} 
		pthread_cleanup_pop(1);
	return NULL;
} 
Пример #15
0
static int net_bindV6(struct ipv6bind* b) {
	SOCKET fd=INVALID_SOCKET, ofd=INVALID_SOCKET, rv;
	int len;
		/* need to defer close until new sockets created */
	SOCKET close_fd=INVALID_SOCKET, close_ofd=INVALID_SOCKET; 
	SOCKETADDRESS oaddr; /* other address to bind */
	int family = b->addr->him.sa_family;
	int ofamily;
	u_short port; /* requested port parameter */
	u_short bound_port;

		/* We only bind to only IPv4 or IPv6 if the listen address is different from the ANY IP address or 
		 * the LOOPBACK IP address. */
	if (family == AF_INET && (b->addr->him4.sin_addr.s_addr != INADDR_ANY) && (b->addr->him4.sin_addr.s_addr != htonl (INADDR_LOOPBACK))) {
			/* bind to v4 only */
		int ret;
		ret = net_bind (b->ipv4_fd, (struct sockaddr *)b->addr, sizeof (struct sockaddr_in));
		if (ret == SOCKET_ERROR) {
			CLOSE_SOCKETS_AND_RETURN;
		}
		closesocket (b->ipv6_fd);
		b->ipv6_fd = INVALID_SOCKET;
		return 0;
	}
	if (family == AF_INET6 && (!NET_IN6ADDR_ISANY(&b->addr->him6)) && !NET_IN6ADDR_ISLOOPBACK(&b->addr->him6)) {
			/* bind to v6 only */
		int ret;
		ret = net_bind (b->ipv6_fd, (struct sockaddr *)b->addr, sizeof (struct sockaddr_in6));
		if (ret == SOCKET_ERROR) {
			CLOSE_SOCKETS_AND_RETURN;
		}
		closesocket (b->ipv4_fd);
		b->ipv4_fd = INVALID_SOCKET;
		return 0;
	}

		/* We need to bind on both stacks, with the same port number */
	memset (&oaddr, 0, sizeof(oaddr));
	if (family == AF_INET) {
		ofamily = AF_INET6;
		fd = b->ipv4_fd;
		ofd = b->ipv6_fd;
		port = ntohs (GET_PORT (b->addr));
		if (b->addr->him4.sin_addr.s_addr == htonl (INADDR_LOOPBACK)) {
			NET_IN6ADDR_SETLOOPBACK (&oaddr.him6);
		} else {
			NET_IN6ADDR_SETANY (&oaddr.him6);
		}
		oaddr.him6.sin6_port = port;
	} else {
		ofamily = AF_INET;
		ofd = b->ipv4_fd;
		fd = b->ipv6_fd;
		port = ntohs (GET_PORT (b->addr));
		oaddr.him4.sin_family = AF_INET;
		oaddr.him4.sin_port = port;
		if (NET_IN6ADDR_ISLOOPBACK(&b->addr->him6)) {
			oaddr.him4.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
		} else {
			oaddr.him4.sin_addr.s_addr = INADDR_ANY;
		}
	}

	rv = net_bind (fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr));
	if (rv == SOCKET_ERROR) {
		CLOSE_SOCKETS_AND_RETURN;
	}

	/* get the port and set it in the other address */
	len = SOCKETADDRESS_LEN(b->addr);
	if (getsockname(fd, (struct sockaddr *)b->addr, &len) == -1) {
		CLOSE_SOCKETS_AND_RETURN;
	}
	bound_port = ntohs (GET_PORT (b->addr));
	SET_PORT (&oaddr, htons (bound_port));
	len = SOCKETADDRESS_LEN (&oaddr);
	if ((rv=net_bind (ofd, (struct sockaddr *) &oaddr, len)) == SOCKET_ERROR) {
		int retries;
		int sotype, arglen=sizeof(sotype);

			/* no retries unless, the request was for any free port */
		if (port != 0) {
			CLOSE_SOCKETS_AND_RETURN;
		}

		getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen);

#define SOCK_RETRIES 50
		/* 50 is an arbitrary limit, just to ensure that this
		 * cannot be an endless loop. Would expect socket creation to 
		 * succeed sooner.
		 */
		for (retries = 0; retries < SOCK_RETRIES; retries ++) {
			int len;
			close_fd = fd; fd = INVALID_SOCKET;
			close_ofd = ofd; ofd = INVALID_SOCKET;
			b->ipv4_fd = INVALID_SOCKET;
			b->ipv6_fd = INVALID_SOCKET;

				/* create two new sockets */
			fd = check_socket_bounds (socket (family, sotype, 0));
			if (fd == INVALID_SOCKET) {
				CLOSE_SOCKETS_AND_RETURN;
			}
			ofd = check_socket_bounds (socket (ofamily, sotype, 0));
			if (ofd == INVALID_SOCKET) {
				CLOSE_SOCKETS_AND_RETURN;
			}

				/* bind random port on first socket */
			SET_PORT (&oaddr, 0);
			rv = net_bind (ofd, (struct sockaddr *)&oaddr, SOCKETADDRESS_LEN(&oaddr));
			if (rv == SOCKET_ERROR) {
				CLOSE_SOCKETS_AND_RETURN;
			}
				/* close the original pair of sockets before continuing */
			closesocket (close_fd); 
			closesocket (close_ofd); 
			close_fd = close_ofd = INVALID_SOCKET;

				/* bind new port on second socket */
			len = SOCKETADDRESS_LEN(&oaddr);
			if (getsockname(ofd, (struct sockaddr *)&oaddr, &len) == -1) {
				CLOSE_SOCKETS_AND_RETURN;
			}
			bound_port = ntohs (GET_PORT (&oaddr));
			SET_PORT (b->addr, htons (bound_port));
			rv = net_bind (fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr));

			if (rv != SOCKET_ERROR) {
				if (family == AF_INET) {
					b->ipv4_fd = fd;
					b->ipv6_fd = ofd;
				} else {
					b->ipv4_fd = ofd;
					b->ipv6_fd = fd;
				}
				return 0;
			}
		}
		CLOSE_SOCKETS_AND_RETURN;
	}
	return 0;
}
Пример #16
0
void *sctpSock(void *param)
		{
	PRINTD(1,"sctpSock: sctpSock started\n");
#ifdef WIN32
	
	int first = 1;
#endif
	
	HANDLE hComm = 0;

	
	paramThread *paraThread;
	
	paraThread = (paramThread *) param;

	
	int sock = 0;

	
	unsigned char payload[MAX_PAYLOAD_SIZE];
	
	struct info *infos = (struct info *) calloc(logbuffer_size, sizeof(info));
	
	struct addrinfo SrcAddress;
	
	in_port_t tmpPort = 0;
	
	int newSock = 0;
	
	int size = 0;
	
	unsigned char *ptrSeqNum = payload + sizeof(uint32_t);			
	
	unsigned char *ptrTimeSec = ptrSeqNum + sizeof(uint32_t);		
	
	unsigned char *ptrTimeUsec = ptrTimeSec + sizeof(uint32_t);		
	
	struct timeval RcvTime;
#ifdef WIN32
	

	
	LARGE_INTEGER _tstart, _tend;
	

	
	unsigned long secs = 0, msecs = 0;
#endif


	int sctpId;
	bool newSession = true;


	PRINTD(1,"sctpSock: Start of Function. logCheck = %d logRemote = %d \n", logCheck, logRemote);

	
	paraThread->addressInfos = infos;
	
	paraThread->count = 0;

	
	memset(payload, 0, MAX_PAYLOAD_SIZE);

	if (strcmp(paraThread->serial, "noSerial") != 0) {
		hComm = serialUp(paraThread->serial);
		if (hComm == INVALID_HANDLE_VALUE)
			printf("Error opening interface %s \n", paraThread->serial);
	}


	unsigned int port = 0;
	GET_PORT((&(paraThread->destHost)), port);

	MUTEX_THREAD_LOCK(mutexSctp);

	
	for (sctpId = 0; sctpId < sctpSessionCount; sctpId++) {
		if (sctpSessions[sctpId].parsedStreams > 0 && sctpSessions[sctpId].port == port) {
			newSession = false;
			break;
		}
	}

	
	if (newSession) {
		PRINTD(1,"sctpSock: Receiving new SCTP session on port %d...\n", ntohs(port));
		sctpId = sctpSessionCount++;
		sctpSessions[sctpId].port = port;
		sctpSessions[sctpId].busyStreams = 0;
		sctpSessions[sctpId].parsedStreams = 1;
		sctpSessions[sctpId].sock = -1;
	}
	else
		sctpSessions[sctpId].parsedStreams++;

	

	PRINTD(1,"sctpSock: Receiving new SCTP stream...\n");

	

	if (newSession) {
		
		sock = socket(paraThread->destHost.ai_family, SOCK_STREAM, IPPROTO_SCTP);
		if (sock < 0) {
			reportErrorAndExit("sctpSock", "socket", "Cannot create a STREAM socket on port");
		}

		
		if (bind(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) {
			
			struct pipeMsg msg;

			msg.code = MSG_FT_ERR1;
			msg.flowId = paraThread->flowId;
			if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
				printf(" sending msg error");
			}
			sleep(INFINITE);
		}

		
		if (listen(sock, SOMAXCONN) < 0) {
			reportErrorAndExit("tcpSock", "listen", "Cannot listen on a port");
		} else {
			
#ifdef WIN32
			int len = paraThread->destHost.ai_addrlen;
			getsockname(sock,paraThread->destHost.ai_addr, &len);
			paraThread->destHost.ai_addrlen = len;
#else
			getsockname(sock, paraThread->destHost.ai_addr, &(paraThread->destHost.ai_addrlen));
#endif

			
			GET_PORT((&(paraThread->destHost)), tmpPort);
			fprintf(stderr, "Listening on STCP port : %d\n", ntohs(tmpPort));
			fflush(stderr);

			
			struct pipeMsg msg;
			msg.code = MSG_FT_OK;
			msg.flowId = paraThread->flowId;
			if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
				printf("error into sending msg to signal manager");
			}
		}

		
		SrcAddress.ai_family = paraThread->destHost.ai_family;
		
		if (SrcAddress.ai_family == PF_INET) {
			
			SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in));
			
			SrcAddress.ai_addrlen = sizeof(struct sockaddr_in);
			
		} else if (SrcAddress.ai_family == PF_INET6) {
			
			SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in6));
			
			SrcAddress.ai_addrlen = sizeof(struct sockaddr_in6);
		}

		

		

		if ((newSock = accept(sock, SrcAddress.ai_addr, (socklen_t *) &SrcAddress.ai_addrlen)) < 0)
			reportErrorAndExit("sctpSock", "accept", "Cannot accept connection");
		
		if (closeSock(sock) == -1)
			reportErrorAndExit("sctpSock", "closeSock", "Cannot close socket sock");

		
		paraThread->socketClose = newSock;

		
		sctpSessions[sctpId].sock = newSock;
		
	} else {
		newSock = sctpSessions[sctpId].sock;
	}
	MUTEX_THREAD_UNLOCK(mutexSctp);

	int firstpacket = 1;
	char HelpSrcAddress[INET6_ADDRSTRLEN];
	char HelpDstAddress[INET6_ADDRSTRLEN];
	int tmpPort_SrcPort = 0;
	int tmpPort_DstPort = 0;

	
	TSTART(_tstart, secs, msecs, first, 0, RECEIVER);
	PRINTD(1,"sctpSock: main loop\n");
	
	while (1) {
		
		size = SCTPrecvPacket((unsigned char*) payload, newSock, sctpId, paraThread->preambleSize, paraThread->payloadLogType);
		PRINTD(2,"sctpSock: Received SCTP data. Size of the received data chinck: %d\n",size);

		if (hComm > 0) {
			DTR_Disable(hComm);
			DTR_Enable(hComm);
		}

		
		GET_TIME_OF_DAY(&RcvTime, _tend, _tstart, secs, msecs, 0, RECEIVER);

		
		
		if ((logCheck != 0) || (logRemote != 0)) {  
			
			PRINTD(2,"sctpSock: Log received data \n");
			if (firstpacket == 1) {
				getInfo(&SrcAddress, tmpPort_SrcPort, HelpSrcAddress);
				getInfo(&paraThread->destHost, tmpPort_DstPort, HelpDstAddress);
				firstpacket = 0;
			}


			if (logCheck != 0) {
				int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); 
				int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); 

				if (paraThread->payloadLogType == PL_STANDARD) {	
					writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload,
							*(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort,
							tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L, net_TimeUsec,
							RcvTime.tv_usec, size);
				} else if (paraThread->payloadLogType == PL_SHORT) {	
					writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload,
							*(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort,
							tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size);
				} else {
					
					
					writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress,
							HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L,
							RcvTime.tv_usec, size);
				}
			}
			
			
			
			if (logRemote != 0) {
				int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); 
				int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); 

				if (paraThread->payloadLogType == PL_STANDARD) { 	
					writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload,
							*(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort,
							tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L, net_TimeUsec,
							RcvTime.tv_usec, size); 						
				} else if (paraThread->payloadLogType == PL_SHORT) {	
					writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload, *(uint32_t *) ptrSeqNum,
							HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort,
							RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); 			
				} else {
					
					
					writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress,
							HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L,
							RcvTime.tv_usec, size);
				}
				infosHostToNet(&infos[paraThread->count]);
			}

			
			paraThread->count++;
			
			if (paraThread->count == logbuffer_size) {
				
				if (logCheck != 0)
					flushBuffer((ofstream *) paraThread->fileLog, infos, paraThread->count);
				
				else
				if (logRemote != 0)
						{
					MUTEX_THREAD_LOCK(mutexLogRem);

					if (sendto(paraThread->logSock, (char *) infos, paraThread->count * sizeof(struct info), 0,
							paraThread->logHost->ai_addr, paraThread->logHost->ai_addrlen) < 0)
						reportErrorAndExit("sctpSock", "sendto", "Cannot send log infos to LogServer");

					paraThread->count = 0;

					MUTEX_THREAD_UNLOCK(mutexLogRem);

					PRINTD(1,"sctpSock: Sent infos to LogServer\n");
				}
			} 
		} 

		
		if (paraThread->meter == METER_RTTM) {
			if (sendto(newSock, (char *) payload, size, 0, SrcAddress.ai_addr,
					SrcAddress.ai_addrlen) < 0)
				reportErrorAndExit("sctpSock", "sendto", "Cannot send payload back for rttm");
			PRINTD(2,"sctpSock: Sent RTTM infos\n");
		} 
	} 

	
	
	MUTEX_THREAD_LOCK(mutexSctp);
	if (--sctpSessionCount == 0)
		free(SrcAddress.ai_addr);
	MUTEX_THREAD_UNLOCK(mutexSctp);

	return NULL;
} 
Пример #17
0
void en_socket_stream_bind (EIF_INTEGER *a_fd, EIF_INTEGER *a_fd1, EIF_INTEGER *a_local_port, EIF_POINTER sockaddr) {

	SOCKETADDRESS* him;
	int family;
	SOCKET fd, fd1;
	int ipv6_supported;
	int localport;
	int rv;

	EIF_NET_INITIALIZE;

	ipv6_supported = en_ipv6_available();

	him = (SOCKETADDRESS*) sockaddr;
	family = him->him.sa_family; 
	localport = ntohs (GET_PORT (him));

	fd = (SOCKET) *a_fd;
	fd1 = (SOCKET) *a_fd1;
	if (ipv6_supported) {
		struct ipv6bind v6bind;
		v6bind.addr = him;
		v6bind.ipv4_fd = fd;
		v6bind.ipv6_fd = fd1;
		rv = net_bindV6(&v6bind);
		if (rv != -1) {
				/* check if the fds have changed */
			if (v6bind.ipv4_fd != fd) {
				fd = v6bind.ipv4_fd;
				if (fd == INVALID_SOCKET) {
						/* socket is closed. */
					*a_fd = -1;
				} else {
						/* socket was re-created */
					*a_fd = (EIF_INTEGER) fd;
				}
			}
			if (v6bind.ipv6_fd != fd1) {
				fd1 = v6bind.ipv6_fd;
				if (fd1 == INVALID_SOCKET) {
						/* socket is closed. */
					*a_fd1 = -1;
				} else {
						/* socket was re-created */
					*a_fd1 = (EIF_INTEGER) fd1;
				}
			}
		}
	} else {
		rv = net_bind(fd, (struct sockaddr *)him, SOCKETADDRESS_LEN(him));
	}

	if (rv == -1) {	
		eraise("bind error", EN_PROG);
		return;
	}

		/* intialize the local port */
	if (localport == 0) {
			/* Now that we're a bound socket, let's extract the port number
			 * that the system chose for us and store it in the Socket object. */
		int len = SOCKETADDRESS_LEN(him);
		u_short port;
		fd = him->him.sa_family == AF_INET? fd: fd1;

		if ((rv=getsockname(fd, (struct sockaddr *)him, &len)) == -1) {
			eif_net_check(rv);
			return;
		}
		port = ntohs (GET_PORT (him));
		*a_local_port = port;
	} else {
		*a_local_port = localport;
	}
}
Пример #18
0
JNIEXPORT int JNICALL
NET_BindV6(struct ipv6bind* b) {
    int fd=-1, ofd=-1, rv, len;
    /* need to defer close until new sockets created */
    int close_fd=-1, close_ofd=-1; 
    SOCKETADDRESS oaddr; /* other address to bind */
    int family = b->addr->him.sa_family;
    int ofamily;
    u_short port; /* requested port parameter */
    u_short bound_port;

    if (family == AF_INET && (b->addr->him4.sin_addr.s_addr != INADDR_ANY)) {
	/* bind to v4 only */
	int ret;
	ret = NET_Bind (b->ipv4_fd, (struct sockaddr *)b->addr, 
				sizeof (struct sockaddr_in));
        if (ret == SOCKET_ERROR) {
	    CLOSE_SOCKETS_AND_RETURN;
        }
	closesocket (b->ipv6_fd);
	b->ipv6_fd = -1;
	return 0;
    }
    if (family == AF_INET6 && (!IN6_IS_ADDR_ANY(&b->addr->him6.sin6_addr))) {
	/* bind to v6 only */
	int ret;
	ret = NET_Bind (b->ipv6_fd, (struct sockaddr *)b->addr, 
				sizeof (struct SOCKADDR_IN6));
        if (ret == SOCKET_ERROR) {
	    CLOSE_SOCKETS_AND_RETURN;
        }
	closesocket (b->ipv4_fd);
	b->ipv4_fd = -1;
	return 0;
    }

    /* We need to bind on both stacks, with the same port number */

    memset (&oaddr, 0, sizeof(oaddr));
    if (family == AF_INET) {
	ofamily = AF_INET6;
	fd = b->ipv4_fd;
	ofd = b->ipv6_fd;
	port = (u_short)GET_PORT (b->addr);
	IN6ADDR_SETANY (&oaddr.him6);
	oaddr.him6.sin6_port = port;
    } else {
	ofamily = AF_INET;
	ofd = b->ipv4_fd;
	fd = b->ipv6_fd;
	port = (u_short)GET_PORT (b->addr);
	oaddr.him4.sin_family = AF_INET;
	oaddr.him4.sin_port = port;
	oaddr.him4.sin_addr.s_addr = INADDR_ANY;
    }

    rv = NET_Bind (fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr));
    if (rv == SOCKET_ERROR) {
    	CLOSE_SOCKETS_AND_RETURN;
    }

    /* get the port and set it in the other address */
    len = SOCKETADDRESS_LEN(b->addr);
    if (getsockname(fd, (struct sockaddr *)b->addr, &len) == -1) {
    	CLOSE_SOCKETS_AND_RETURN;
    }
    bound_port = GET_PORT (b->addr);
    SET_PORT (&oaddr, bound_port);
    if ((rv=NET_Bind (ofd, (struct sockaddr *) &oaddr, 
				SOCKETADDRESS_LEN (&oaddr))) == SOCKET_ERROR) {
	int retries;
	int sotype, arglen=sizeof(sotype);

 	/* no retries unless, the request was for any free port */

        if (port != 0) {
    	    CLOSE_SOCKETS_AND_RETURN;
        }

	getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen);

#define SOCK_RETRIES 50
	/* 50 is an arbitrary limit, just to ensure that this
	 * cannot be an endless loop. Would expect socket creation to 
	 * succeed sooner.
	 */
    	for (retries = 0; retries < SOCK_RETRIES; retries ++) {
	    int len;
	    close_fd = fd; fd = -1;
	    close_ofd = ofd; ofd = -1;
	    b->ipv4_fd = SOCKET_ERROR;
	    b->ipv6_fd = SOCKET_ERROR;

	    /* create two new sockets */
	    fd = socket (family, sotype, 0);
	    if (fd == SOCKET_ERROR) {
    	        CLOSE_SOCKETS_AND_RETURN;
	    }
	    ofd = socket (ofamily, sotype, 0);
	    if (ofd == SOCKET_ERROR) {
    	        CLOSE_SOCKETS_AND_RETURN;
	    }

	    /* bind random port on first socket */
	    SET_PORT (&oaddr, 0);
    	    rv = NET_Bind (ofd, (struct sockaddr *)&oaddr, SOCKETADDRESS_LEN(&oaddr));
    	    if (rv == SOCKET_ERROR) {
    	        CLOSE_SOCKETS_AND_RETURN;
	    }
	    /* close the original pair of sockets before continuing */
	    closesocket (close_fd); 
	    closesocket (close_ofd); 
	    close_fd = close_ofd = -1;

	    /* bind new port on second socket */
	    len = SOCKETADDRESS_LEN(&oaddr);
            if (getsockname(ofd, (struct sockaddr *)&oaddr, &len) == -1) {
    	        CLOSE_SOCKETS_AND_RETURN;
            }
    	    bound_port = GET_PORT (&oaddr);
	    SET_PORT (b->addr, bound_port);
    	    rv = NET_Bind (fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr));

    	    if (rv != SOCKET_ERROR) {
		if (family == AF_INET) {
	    	    b->ipv4_fd = fd;
	    	    b->ipv6_fd = ofd;
		} else {
	    	    b->ipv4_fd = ofd;
	    	    b->ipv6_fd = fd;
		}
		return 0;
	    }
	}
	CLOSE_SOCKETS_AND_RETURN;
    }
    return 0;
}
Пример #19
0
void __attribute__((naked)) isr_fault()
{
	unsigned int sp, lr, psr, usp;

	sp  = GET_SP ();
	psr = GET_PSR();
	lr  = GET_LR ();
	usp = GET_USP();

	printk("\nKernel SP      0x%08x\n"
		"Stacked PSR    0x%08x\n"
		"Stacked PC     0x%08x\n"
		"Stacked LR     0x%08x\n"
		"Current LR     0x%08x\n"
		"Current PSR    0x%08x(vector number:%d)\n", sp,
		*(unsigned int *)(sp + 28),
		*(unsigned int *)(sp + 24),
		*(unsigned int *)(sp + 20),
		lr, psr, psr & 0x1ff);
	printk("\nUser SP        0x%08x\n"
		"Stacked PSR    0x%08x\n"
		"Stacked PC     0x%08x\n"
		"Stacked LR     0x%08x\n",
		usp,
		*(unsigned int *)(usp + 28),
		*(unsigned int *)(usp + 24),
		*(unsigned int *)(usp + 20));

	printk("\ncurrent->sp         0x%08x\n"
		"current->base       0x%08x\n"
		"current->heap       0x%08x\n"
		"current->kernel     0x%08x\n"
		"current->kernel->sp 0x%08x\n"
		"current->state      0x%08x\n"
		"current->irqflag    0x%08x\n"
		"current->addr       0x%08x\n"
		"current             0x%08x\n"
		, current->mm.sp, current->mm.base, current->mm.heap,
		current->mm.kernel.base, current->mm.kernel.sp, current->state,
		current->irqflag, current->addr, current);

	printk("\ncurrent context\n");
	unsigned int i;
	for (i = 0; i < NR_CONTEXT*2; i++)
		printk("[0x%08x] 0x%08x\n", usp + i*4, ((unsigned int *)usp)[i]);

	printk("\nSCB_ICSR  0x%08x\n"
		"SCB_CFSR  0x%08x\n"
		"SCB_HFSR  0x%08x\n"
		"SCB_MMFAR 0x%08x\n"
		"SCB_BFAR  0x%08x\n",
		SCB_ICSR, SCB_CFSR, SCB_HFSR, SCB_MMFAR, SCB_BFAR);

	/* led for debugging */
#ifdef LED_DEBUG
	SET_PORT_CLOCK(ENABLE, PORTD);
	SET_PORT_PIN(PORTD, 2, PIN_OUTPUT_50MHZ);
	unsigned int j;
	while (1) {
		PUT_PORT(PORTD, GET_PORT(PORTD) ^ 4);

		for (i = 100; i; i--) {
			for (j = 10; j; j--) {
				__asm__ __volatile__(
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						"nop		\n\t"
						::: "memory");
			}
		}
	}
#endif
}
Пример #20
0
Файл: main.c Проект: dusartc/tpC
int read_pin(uint32_t p){
    volatile uint32_t *pin_register = ADDR_OFFSET(&FIO0PIN, 0x20 * GET_PORT(p));
    volatile uint32_t *mask_register = ADDR_OFFSET(&FIO0MASK, 0x20 * GET_PORT(p));
    *mask_register = ~(1 << GET_PIN(p));
    return ((*pin_register & (1 << GET_PIN(p))) ? 1 : 0);
}
Пример #21
0
void *dccpSock(void *param)
		{
	PRINTD(1,"dccpSock: dccpSock started\n");
	HANDLE hComm = 0;
	int sock = 0;
	int sendCheck = 0;
	unsigned char payload[MAX_PAYLOAD_SIZE];
	struct info *infos = (struct info *) calloc(logbuffer_size, sizeof(info));
	struct addrinfo SrcAddress;
	in_port_t tmpPort = 0;
	int newSock = 0;
	int size = 0;
	int optval = 0; 
	struct timeval RcvTime;

	unsigned char *ptrSeqNum = payload + sizeof(uint32_t);			
	unsigned char *ptrTimeSec = ptrSeqNum + sizeof(uint32_t);		
	unsigned char *ptrTimeUsec = ptrTimeSec + sizeof(uint32_t);		

	paramThread *paraThread;
	paraThread = (paramThread *) param;

	paraThread->addressInfos = infos;
	paraThread->count = 0;
	if (strcmp(paraThread->serial, "noSerial") != 0) {
		hComm = serialUp(paraThread->serial);
		if (hComm == INVALID_HANDLE_VALUE)
			printf("Error opening interface %s \n", paraThread->serial);
	}
	sock = socket(paraThread->destHost.ai_family, SOCK_DCCP, 0);
	if (sock < 0)
		reportErrorAndExit("dccpSock", "socket", "Cannot create a DCCP socket on port");

	if (paraThread->dsByte
			&& (paraThread->destHost.ai_family == AF_INET)
			&& setsockopt(sock, SOL_IP, IP_TOS, (char *) &paraThread->dsByte, sizeof(BYTE)) < 0) {
		printf("** WARNING ** Flow %d. Could not set DS byte to: %d\n", paraThread->flowId, paraThread->dsByte);
	}

	if (bind(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) {
		printf(" Error into bind function\n");
		struct pipeMsg msg;
		msg.code = MSG_FT_ERR1;
		msg.flowId = paraThread->flowId;
		if (sendPipeMsg(paraThread->rPipe, &msg) < 0)
			printf(" sending msg error");
		sleep(INFINITE);
	}
	
	
	
	
	
	if (setsockopt(sock, SOL_DCCP, DCCP_SOCKOPT_SERVICE, &optval, sizeof(optval)) < 0)
		reportErrorAndExit("dccpSock", "setsockopt", "Cannot set option DCCP_SERVICE");
	
	if (listen(sock, SOMAXCONN) < 0)
		reportErrorAndExit("dccpSock", "listen", "Cannot listen on a port");
	else {
		
#ifdef WIN32
		int len=paraThread->destHost.ai_addrlen;
		getsockname(sock,paraThread->destHost.ai_addr,&len);
		paraThread->destHost.ai_addrlen=len;
#else
		getsockname(sock, paraThread->destHost.ai_addr, &(paraThread->destHost.ai_addrlen));
#endif
		GET_PORT((&(paraThread->destHost)), tmpPort);
		fprintf(stderr, "Listening on DCCP port : %d\n", ntohs(tmpPort));
		fflush(stderr);
		struct pipeMsg msg;
		msg.code = MSG_FT_OK;
		msg.flowId = paraThread->flowId;
		if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
			printf("error into sending msg to signal manager");
		}
	}
	SrcAddress.ai_family = paraThread->destHost.ai_family;
	if (SrcAddress.ai_family == PF_INET) {
		SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in));
		SrcAddress.ai_addrlen = sizeof(struct sockaddr_in);
	} else if (SrcAddress.ai_family == PF_INET6) {
		SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in6));
		SrcAddress.ai_addrlen = sizeof(struct sockaddr_in6);
	}

	pthread_cleanup_push(free, SrcAddress.ai_addr);

		if ((newSock = accept(sock, SrcAddress.ai_addr, (socklen_t *) &SrcAddress.ai_addrlen)) < 0)
			reportErrorAndExit("dccpSock", "accept", "Cannot accept connection");
		if (closeSock(sock) == -1)
			reportErrorAndExit("dccpSock", "closeSock", "Cannot close socket sock");
		paraThread->socketClose = newSock;
		int firstpacket = 1;
		char HelpSrcAddress[INET6_ADDRSTRLEN];
		char HelpDstAddress[INET6_ADDRSTRLEN];
		int tmpPort_SrcPort = 0;
		int tmpPort_DstPort = 0;

		TSTART(_tstart, secs, msecs, first, 0, RECEIVER);
		PRINTD(1,"dccpSock: main loop\n");
		while (1) {
			size = recv(newSock, (char *) payload, MAX_PAYLOAD_SIZE, 0);
			if (size < 0)
				reportErrorAndExit("udpSock", "recvfrom", "Cannot receive UDP packets");
			else if (size > 0) {
				PRINTD(2,"dccpSock: Received DCCP packet, size %d\n", size);
				if (hComm > 0) {
					DTR_Disable(hComm);
					DTR_Enable(hComm);
				}
				GET_TIME_OF_DAY(&RcvTime, _tend, _tstart, secs, msecs, 0, RECEIVER);
				if ((logCheck != 0) || (logRemote != 0)) {
					if (firstpacket == 1) {
						getInfo(&SrcAddress, tmpPort_SrcPort, HelpSrcAddress);
						getInfo(&paraThread->destHost, tmpPort_DstPort, HelpDstAddress);
						firstpacket = 0;
					}


					if (logCheck != 0) {
						int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); 
						int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); 

						if (paraThread->payloadLogType == PL_STANDARD) {	
							writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload,
									*(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
									tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec,
									RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size);
						} else if (paraThread->payloadLogType == PL_SHORT) {	
							writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload,
									*(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
									tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L,
									RcvTime.tv_usec, size);
						} else {
							
							
							writeInBufferNone(&infos[paraThread->count], paraThread->flowId,
									HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort,
									tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec,
									size);
						}
					}
					
					
					
					if (logRemote != 0) {
						int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); 	
						int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); 	

						if (paraThread->payloadLogType == PL_STANDARD) {	
							writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload,
									*(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
									tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec,
									RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size); 		
						} else if (paraThread->payloadLogType == PL_SHORT) {	
							writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload,
									*(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
									tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L,
									RcvTime.tv_usec, size); 						
						} else {
							
							
							writeInBufferNone(&infos[paraThread->count], paraThread->flowId,
									HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort,
									tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec,
									size);
						}
						infosHostToNet(&infos[paraThread->count]);
					}

					
					paraThread->count++;
					
					if (paraThread->count == logbuffer_size) {
						
						if (logCheck != 0)
							flushBuffer((ofstream *) paraThread->fileLog, infos, paraThread->count);
						
						else
						if (logRemote != 0) {
							MUTEX_THREAD_LOCK(mutexLogRem);

							if (sendto(paraThread->logSock, (char *) infos,
									paraThread->count * sizeof(struct info), 0,
									paraThread->logHost->ai_addr, paraThread->logHost->ai_addrlen)
									< 0)
								reportErrorAndExit("dccpSock", "sendto",
										"Cannot send log infos to LogServer");

							paraThread->count = 0;

							MUTEX_THREAD_UNLOCK(mutexLogRem);
							PRINTD(1,"dccpSock: Sent infos to LogServer\n");
						}
					}
				}
				if (paraThread->meter == METER_RTTM) {
					do {
						PRINTD(2,"dccpSock: Trying to send RTTM infos\n");
						sendCheck = sendto(newSock, (char *) payload, size, 0, SrcAddress.ai_addr,
								SrcAddress.ai_addrlen);
					} while (sendCheck < 0 && errno == EAGAIN);
					if (sendCheck < 0)
						reportErrorAndExit("dccpSock", "sendto", "Cannot send payload back for rttm");
					PRINTD(2,"dccpSock: Sent RTTM infos\n");
				}
			} 
		} 
		pthread_cleanup_pop(1);
	return NULL;
} 
Пример #22
0
void gpio_direction_output(uint32_t gpio, uint32_t value)
{
	rt_hw_gpio_init(GET_PORT(gpio), GET_PIN(gpio),OUTPUT_DIRECTION);
	rt_hw_gpio_set(GET_PORT(gpio), GET_PIN(gpio), value);
}
Пример #23
0
void *tcpSock(void *param)
		{
	PRINTD(1,"tcpSock: tcpSock started\n");
#ifdef WIN32
	
	int first = 1;
#endif
	
	HANDLE hComm = 0;

	
	paramThread *paraThread;
	
	paraThread = (paramThread *) param;

	
	int sock = 0;

	
	unsigned char payload[MAX_PAYLOAD_SIZE];
	
	struct info *infos = (struct info *) calloc(logbuffer_size, sizeof(info));
	
	struct addrinfo SrcAddress;
	
	in_port_t tmpPort = 0;
	
	int newSock = 0;
	
	int size = 0;
	
	unsigned char *ptrSeqNum = payload + sizeof(uint32_t);			
	
	unsigned char *ptrTimeSec = ptrSeqNum + sizeof(uint32_t);		
	
	unsigned char *ptrTimeUsec = ptrTimeSec + sizeof(uint32_t);		
	
	struct timeval RcvTime;
#ifdef WIN32
	

	
	LARGE_INTEGER _tstart, _tend;
	

	
	unsigned long secs = 0, msecs = 0;
#endif
	
	paraThread->addressInfos = infos;
	
	paraThread->count = 0;

	
	memset(payload, 0, MAX_PAYLOAD_SIZE);

	if (strcmp(paraThread->serial, "noSerial") != 0) {
		hComm = serialUp(paraThread->serial);
		if (hComm == INVALID_HANDLE_VALUE)
			printf("Error opening interface %s \n", paraThread->serial);
	}

	bool socketAlreadyOpen = false;
#ifdef MULTIPORT

	if ((passiveMode == false) && (paraThread->indexPort > 0)) {
		MUTEX_THREAD_LOCK(sharedTcpSockets[paraThread->indexPort].mutexSharedSockets);

		sock = sharedTcpSockets[paraThread->indexPort].socket;

		if (sock > 0) {
			socketAlreadyOpen = true;
		}
	}

#endif

	
	if (socketAlreadyOpen == false) {
		sock = socket(paraThread->destHost.ai_family, SOCK_STREAM, 0);
		if (paraThread->dsByte
				&& (paraThread->destHost.ai_family == AF_INET)
				&& setsockopt(sock, SOL_IP, IP_TOS, (char *) &paraThread->dsByte, sizeof(BYTE)) < 0) {
			printf("** WARNING ** Flow %d. Could not set DS byte to: %d\n", paraThread->flowId, paraThread->dsByte);
		}
	}

	if (sock < 0)
		reportErrorAndExit("tcpSock", "socket", "Cannot create a STREAM socket on port");

	if ((passiveMode == false) && (socketAlreadyOpen == false)) { 	

		
		if (bind(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) {
			
			struct pipeMsg msg;

			msg.code = MSG_FT_ERR1;
			msg.flowId = paraThread->flowId;
			if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
				printf(" sending msg error");
			}
			sleep(INFINITE); 
		}

	}

//#if defined UNIX && ! defined BSD
	
	if ((paraThread->iface) && (socketAlreadyOpen == false)) {
		printf("Binding to device %s\n", paraThread->iface);
		if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, paraThread->iface, strlen(paraThread->iface)) < 0) {
			printf("** WARNING ** Cannot bind to device %s (hint: you must be root)\n", paraThread->iface);
			fflush(stdout);
		}
	}
//#endif

	if ((passiveMode == false) && (socketAlreadyOpen == false)) {

		
		if (listen(sock, SOMAXCONN) < 0)
			reportErrorAndExit("tcpSock", "listen", "Cannot listen on a port");
		else {
			
#ifdef WIN32
			int len=paraThread->destHost.ai_addrlen;
			getsockname(sock,paraThread->destHost.ai_addr,&len);
			paraThread->destHost.ai_addrlen=len;
#else
			getsockname(sock, paraThread->destHost.ai_addr, &(paraThread->destHost.ai_addrlen));
#endif
			
			GET_PORT((&(paraThread->destHost)), tmpPort);
			printf("Listening on TCP port : %d\n", ntohs(tmpPort));
			fflush(stdout);

#ifdef MULTIPORT
			if (paraThread->indexPort == 0)
					{
				paraThread->indexPort = ntohs(tmpPort);
				MUTEX_THREAD_LOCK(sharedTcpSockets[paraThread->indexPort].mutexSharedSockets);
			}
#endif

			
			struct pipeMsg msg;
			msg.code = MSG_FT_OK;
			msg.flowId = paraThread->flowId;
			if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
				printf("error into sending msg to signal manager");
			}
		}

	}
	#ifdef MULTIPORT
	else if ((passiveMode == false) && (socketAlreadyOpen == true))
			{
		
		struct pipeMsg msg;
		msg.code = MSG_FT_OK;
		msg.flowId = paraThread->flowId;
		if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
			printf("error into sending msg to signal manager");
		}
	}
#endif

	
	SrcAddress.ai_family = paraThread->destHost.ai_family;
	
	if (SrcAddress.ai_family == PF_INET) {
		
		SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in));
		
		SrcAddress.ai_addrlen = sizeof(struct sockaddr_in);
		
	} else if (SrcAddress.ai_family == PF_INET6) {
		
		SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in6));
		
		SrcAddress.ai_addrlen = sizeof(struct sockaddr_in6);
	}

	pthread_cleanup_push(free, SrcAddress.ai_addr);

		if (passiveMode == false) { 	

			

			if ((newSock = accept(sock, SrcAddress.ai_addr, (socklen_t *) &SrcAddress.ai_addrlen)) < 0)
				reportErrorAndExit("tcpSock", "accept", "Cannot accept connection");

#ifdef MULTIPORT
			
			if ((passiveMode == false) && (socketAlreadyOpen == false))
					{
				sharedTcpSockets[paraThread->indexPort].socket = sock;
			}

			sharedTcpSockets[paraThread->indexPort].inUse++;

			MUTEX_THREAD_UNLOCK(sharedTcpSockets[paraThread->indexPort].mutexSharedSockets);
#else
			
			if ( closeSock(sock) == -1)
			reportErrorAndExit("tcpSock","closeSock","Cannot close socket sock");
#endif

			
			paraThread->socketClose = newSock;

			
		} else {
			struct addrinfo *SrcAddrForConnect = NULL;

//#if (defined WIN32 && defined IPv6RECV) || defined UNIX || defined BSD
			if (paraThread->destHost.ai_family == PF_INET6) {
				getaddrinfo("::", NULL, &hint, &SrcAddrForConnect);
			} else
//#endif
			{
				getaddrinfo("0.0.0.0", NULL, &hint, &SrcAddrForConnect);
			}

			
			SET_PORT((SrcAddrForConnect), htons((paraThread->portForPssv)));

			
			if (bind(sock, SrcAddrForConnect->ai_addr, SrcAddrForConnect->ai_addrlen) < 0) {
				
				struct pipeMsg msg;

				msg.code = MSG_FT_ERR1;
				msg.flowId = paraThread->flowId;
				if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
					printf(" sending msg error");
				}
				sleep(INFINITE); 
			}

			
			if (connect(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0)
				reportErrorAndExit("tcpSock", "connect", "Cannot connect (Passive Mode)");
			PRINTD(1,"tcpSock: Connection establishes (Passive Mode)\n");

			freeaddrinfo(SrcAddrForConnect);

			
			newSock = sock;

			
			paraThread->socketClose = sock;

			
#ifdef WIN32
			int len=SrcAddress.ai_addrlen;						
			getsockname(sock,SrcAddress.ai_addr,&len);				
			SrcAddress.ai_addrlen=len;						
#else
			getsockname(sock, SrcAddress.ai_addr, &SrcAddress.ai_addrlen);		
#endif
		}
		

		int firstpacket = 1;
		char HelpSrcAddress[INET6_ADDRSTRLEN];
		char HelpDstAddress[INET6_ADDRSTRLEN];
		int tmpPort_SrcPort = 0;
		int tmpPort_DstPort = 0;

		
		TSTART(_tstart, secs, msecs, first, 0, RECEIVER);
		PRINTD(1,"tcpSock: main loop\n");
		
		while (1) {
			
			PRINTD(2, "tcpSock: preambleSize = %d \n",paraThread->preambleSize);
			size = TCPrecvPacket((unsigned char*) payload, newSock, paraThread->preambleSize, paraThread->payloadLogType);

			
			if (size <= 0) {
				PRINTD(1,"tcpSock: TCPrecvPacket() = %d\n",size);
				
				if (size < 0) {
					
					struct pipeMsg msg;

					if (passiveMode == false) {
						GET_PORT((&(paraThread->destHost)), tmpPort_DstPort);
					} else {
						GET_PORT((&SrcAddress), tmpPort_DstPort);
					}
					printf("Error on TCP port : %d\n", ntohs(tmpPort_DstPort));
					printf("Finish on TCP port : %d\n\n", ntohs(tmpPort_DstPort));
					fflush(stdout);

					msg.code = MSG_FT_ERR_SOCK;
					msg.flowId = paraThread->flowId;
					if (sendPipeMsg(paraThread->rPipe, &msg) < 0) {
						printf(" sending msg error");
					}
				}
				sleep(INFINITE);
			}

			if (hComm > 0) {
				DTR_Disable(hComm);
				DTR_Enable(hComm);
			}

			
			GET_TIME_OF_DAY(&RcvTime, _tend, _tstart, secs, msecs, 0, RECEIVER);

			
			
			if ((logCheck != 0) || (logRemote != 0)) {

				if (firstpacket == 1) {
					if (passiveMode == false) {							
						getInfo(&SrcAddress, tmpPort_SrcPort, HelpSrcAddress);
						getInfo(&paraThread->destHost, tmpPort_DstPort, HelpDstAddress);
					} else {									
						
#ifdef WIN32
						int len=SrcAddress.ai_addrlen;						
						getsockname(sock,SrcAddress.ai_addr,&len);
						SrcAddress.ai_addrlen=len;
#else
						getsockname(sock, SrcAddress.ai_addr, &SrcAddress.ai_addrlen);		
#endif
						getInfo(&paraThread->destHost, tmpPort_SrcPort, HelpSrcAddress);	
						getInfo(&SrcAddress, tmpPort_DstPort, HelpDstAddress);			
					}										
					firstpacket = 0;
				}
				
				if (paraThread->l7Proto == L7_PROTO_TELNET)
					size = size - 20; 

				if (logCheck != 0) {
					int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); 
					int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); 

					if (paraThread->payloadLogType == PL_STANDARD) {	
						writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload,
								*(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
								tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L,
								net_TimeUsec, RcvTime.tv_usec, size);					
					} else if (paraThread->payloadLogType == PL_SHORT) {	
						writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload,
								*(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
								tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L,
								RcvTime.tv_usec, size);							
					} else {
						
						
						writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress,
								HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort,
								RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size);
					}
				}
				
				
				
				if (logRemote != 0) {
					int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); 
					int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); 

					if (paraThread->payloadLogType == PL_STANDARD) {	
						writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload,
								*(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
								tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L,
								net_TimeUsec, RcvTime.tv_usec, size); 					
					} else if (paraThread->payloadLogType == PL_SHORT) { 	
						writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload,
								*(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress,
								tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L,
								RcvTime.tv_usec, size); 						
					} else {
						
						
						writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress,
								HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort,
								RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size);
					}
					infosHostToNet(&infos[paraThread->count]);
				}

				
				if (size != 0) paraThread->count++; 

				
				if (paraThread->count == logbuffer_size) {
					
					if (logCheck != 0)
						flushBuffer((ofstream *) paraThread->fileLog, infos, paraThread->count);
					
					else
					if (logRemote != 0)
							{
						MUTEX_THREAD_LOCK(mutexLogRem);

						if (sendto(paraThread->logSock, (char *) infos,
								paraThread->count * sizeof(struct info), 0,
								paraThread->logHost->ai_addr, paraThread->logHost->ai_addrlen) < 0)
							reportErrorAndExit("tcpSock", "sendto", "Cannot send log infos to LogServer");

						paraThread->count = 0;

						MUTEX_THREAD_UNLOCK(mutexLogRem);
						PRINTD(1,"tcpSock: Sent infos to LogServer\n");
					}
				} 
			} 
			
			if (paraThread->meter == METER_RTTM) {
				if (sendto(newSock, (char *) payload, size, 0, SrcAddress.ai_addr, SrcAddress.ai_addrlen) < 0)
					reportErrorAndExit("tcpSock", "sendto", "Cannot send payload back for rttm");
				PRINTD(2,"tcpSock: Sent RTTM infos\n");
			} 
		} 
		pthread_cleanup_pop(1);
	return NULL;
} 
Пример #24
0
void internal_generic_output(FILE* fp, CELL cell, int strict, int tab)
{
	switch(GET_TYPE(cell)) {
	case T_VOID:
		fputs("#<void>", fp);
		break;

	case T_NULL:
		fputs("()", fp);
		break;

	case T_UNDEFINED:
		fputs("#<undefined>", fp);
		break;

	case T_EMPTY:
		fputs("#<empty>", fp);
		break;

	case T_BOOL:
		fputs(GET_BOOL(cell) ? "#t" : "#f", fp);
		break;

	case T_CHAR:
		{
			CHAR ch = GET_CHAR(cell);
			if (strict) {
				switch(ch) {
				case ' ':  fputs("#\\space",     fp); break;
				case 0:    fputs("#\\nul",       fp); break;
				case 27:   fputs("#\\escape",    fp); break;
				case 127:  fputs("#\\rubout",    fp); break;
				case '\a': fputs("#\\alarm",     fp); break;
				case '\b': fputs("#\\backspace", fp); break;
				case '\f': fputs("#\\page",      fp); break;
				case '\n': fputs("#\\newline",   fp); break;
				case '\r': fputs("#\\return",    fp); break;
				case '\t': fputs("#\\tab",       fp); break;
				case '\v': fputs("#\\vtab",      fp); break;
				default:   fprintf(fp, "#\\%c", ch); break;
				}
			}
			else {
				fputc(ch, fp);
			}
		}
		break;

	case T_INT:
		fprintf(fp, "%d", GET_INT(cell));
		break;

    case T_BIGINT:
        fprintf(fp, "%lld", GET_BIGINT(cell));
        break;

	case T_FLOAT:
		fprintf(fp, "%f", GET_FLOAT(cell));
		break;

	case T_STRING:
		{
			STRING* p = GET_STRING(cell);
			size_t len = p->len;
			char* data = p->data;
			if (strict) {
				// FIXME -- make this more efficient, and escape other special chars?
				fputc('"', fp);
				while(len--) {
					char ch = *data++;
					if (ch == '"' || ch == '\\') {
						fputc('\\', fp);
					}
					fputc(ch, fp);
				}
				fputc('"', fp);
			}
			else {
				fwrite(data, 1, len, fp);
			}
		}
		break;

	case T_NAME:
		{
			NAME* p = GET_NAME(cell);
			if (p->gensym) {
				fprintf(fp, "#_%d", p->gensym);
			}
			else {
				fwrite(GET_NAME(cell)->data, 1, GET_NAME(cell)->len, fp);
			}
		}
		break;

	case T_KEYWORD:
		{
			KEYWORD* p = GET_KEYWORD(cell);
            fwrite(p->data, 1, p->len, fp);
            fputc(':', fp);
		}
		break;

	case T_SLOT:
		fprintf(fp, "#<slot:%d>", GET_SLOT(cell));
		break;

    // FIXME - arbitrary recursion
	case T_CONS:
		fputc('(', fp);
		if (tab) ++tab;
		int did = 0;
		while(1) {
			int pair = CONSP(CAR(cell));
			if (!did && tab && pair && !CONSP(CAR(CAR(cell)))) { fprintf(fp, "\n%*s", (tab-1)*2, ""); }
			internal_generic_output(fp, CAR(cell), strict, tab);
			cell = CDR(cell);
			if (NULLP(cell)) {
				break;
			}
			did = (tab && pair);
			if (did) { fprintf(fp, "\n%*s", (tab-1)*2, ""); }
			else fputc(' ', fp);
			if (!CONSP(cell)) {
				fputs(". ", fp);
				internal_generic_output(fp, cell, strict, tab);
				break;
			}
		}
		fputc(')', fp);
		break;

    // FIXME - arbitrary recursion
	case T_VECTOR:
		{
			VECTOR *vec = GET_VECTOR(cell);
			fputs("#(", fp);
			if (vec->len > 0) {
				int i = 0;
				internal_generic_output(fp, vec->data[i++], strict, tab);
				while(i < vec->len) {
					fputc(' ', fp);
					internal_generic_output(fp, vec->data[i++], strict, tab);
				}
			}
			fputc(')', fp);
			break;
		}

	case T_FUNC:
		fprintf(fp, "#<primitive:%s>", GET_FUNC(cell)->name);
		break;

	case T_COMPILED_LAMBDA:
		fprintf(fp, "#<compiled-lambda:0x%08x>", AS_LITERAL(cell));
		break;
		{
			if (tab) ++tab;
			COMPILED_LAMBDA *l = GET_COMPILED_LAMBDA(cell);
			fprintf(fp, "#<%s %d%s:%d/%d",
					l->is_macro ? "macro" : "lambda",
					l->argc, l->rest ? "+" : "",
					l->depth,
					l->max_slot);

			if (tab) { fprintf(fp, "\n%*s", (tab-1)*2, ""); }
			else { fputc(' ', fp); }

			internal_generic_output(fp, l->body, strict, tab);
			fputc('>', fp);
		}
		break;
		
	case T_CLOSURE:
		fprintf(fp, "#<closure:0x%08x>", AS_LITERAL(cell));
		break;
		{
			if (tab) ++tab;
			CLOSURE *c = GET_CLOSURE(cell);
			fprintf(fp, "#<closure ");
			if (tab) { fprintf(fp, "\n%*s", (tab-1)*2, ""); }
			internal_print_env(fp, c->env);
			if (tab) { fprintf(fp, "\n%*s", (tab-1)*2, ""); }
			fputc(' ', fp);
			internal_generic_output(fp, c->compiled_lambda, strict, tab);
			fputc('>', fp);
		}
		break;

	case T_EXCEPTION:
		fputs("#<exception:", fp);
		fwrite(GET_EXCEPTION(cell)->data, 1, GET_EXCEPTION(cell)->len, fp);
		fputc('>', fp);
		break;

	case T_REIFIED_CONTINUATION:
		fprintf(fp, "#<continuation:0x%08x>", (int)GET_REIFIED_CONTINUATION(cell)->cont);
		break;

	case T_STACK_FRAME:
		{
			STACK_FRAME* p = GET_STACK_FRAME(cell);
			fputs("#<stack-frame [", fp);
			int i;
			for(i = 0; i < p->len; ++i) {
				if (i) fputc(' ', fp);
				fprintf(fp, "0x%08x", (int)p->cells[i]);
			}
			fputs("]>", fp);
		}
		break;

	case T_ENV:
		fprintf(fp, "#<env:count=%d>", GET_ENV(cell)->count);
		break;

	case T_RELOC:
		fprintf(fp, "#<reloc:0x%08x>", (int)GET_RELOC(cell));
		break;

    case T_PORT:
        fprintf(fp, "#<port:%s>", GET_PORT(cell)->data);
        break;

    case T_DB_CONNECTION:
        fprintf(fp, "#<db-connection>");
        break;

    case T_DB_RESULT:
        fprintf(fp, "#<db-result>");
        break;

    case T_RECORD:
        fprintf(fp, "#<record>");
        break;

	default:
		fprintf(fp, "#<%s-%02x:%08x>",
			IS_LITERAL(cell) ? "literal" : "pointer",
			GET_TYPE(cell),
			AS_LITERAL(cell)
		);
		break;
	}
}