Ejemplo n.º 1
0
int loop()
{
	int					sockfd;
	struct sockaddr_in	servaddr, cliaddr;
#ifdef SC12
	int error;
#endif

#ifdef SC12
	sockfd = opensocket(SOCK_DGRAM, &error);
#else
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
#endif
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(6454);

#ifdef SC12
	bind(sockfd, (const struct sockaddr far *) &servaddr, &error);
#else
	bind(sockfd, (SA *) &servaddr, sizeof(servaddr));
#endif

	return dg_echo(sockfd, (SA *) &cliaddr, sizeof(cliaddr));
}
Ejemplo n.º 2
0
int main(void)
{
	int ret, status;
	int sockfd, shared_fd;
	unsigned char *map_buf;
	unsigned long map_len;
	struct ion_buffer_info info;
	struct socket_info skinfo;

	/* This is the client part. Here 0 means client or importer */
	status = opensocket(&sockfd, SOCKET_NAME, 0);
	if (status < 0) {
		fprintf(stderr, "No exporter exists...\n");
		ret = status;
		goto err_socket;
	}

	skinfo.sockfd = sockfd;

	ret = socket_receive_fd(&skinfo);
	if (ret < 0) {
		fprintf(stderr, "Failed: socket_receive_fd\n");
		goto err_recv;
	}

	shared_fd = skinfo.datafd;
	printf("Received buffer fd: %d\n", shared_fd);
	if (shared_fd <= 0) {
		fprintf(stderr, "ERROR: improper buf fd\n");
		ret = -1;
		goto err_fd;
	}

	memset(&info, 0, sizeof(info));
	info.buffd = shared_fd;
	info.buflen = ION_BUFFER_LEN;

	ret = ion_import_buffer_fd(&info);
	if (ret < 0) {
		fprintf(stderr, "Failed: ion_use_buffer_fd\n");
		goto err_import;
	}

	map_buf = info.buffer;
	map_len = info.buflen;
	read_buffer(map_buf, map_len);

	/* Write probably new data to the same buffer again */
	map_len = ION_BUFFER_LEN;
	write_buffer(map_buf, map_len);

err_import:
	ion_close_buffer_fd(&info);
err_fd:
err_recv:
err_socket:
	closesocket(sockfd, SOCKET_NAME);

	return ret;
}
Ejemplo n.º 3
0
/**
 * Program which prints ThinkGear EEG_POWERS values to stdout.
 */
int main( void ) {

	opensocket();
	dataFile = fopen("dataStore.txt", "a+");

    /* Print driver version number */
    dllVersion = TG_GetDriverVersion();
    printf( "ThinkGear DLL version: %d\n", dllVersion );

    /* Get a connection ID handle to ThinkGear */
    connectionId = TG_GetNewConnectionId();
    if( connectionId < 0 ) {
        fprintf( stderr, "ERROR: TG_GetNewConnectionId() returned %d.\n", 
                 connectionId );
        wait();
        exit( EXIT_FAILURE );
    }

    /* Attempt to connect the connection ID handle to serial port "COM5" */
    //comPortName = "\\\\.\\COM19";
	comPortName = "COM7:";
    errCode = TG_Connect( connectionId, 
                          comPortName, 
                          TG_BAUD_57600, 
                          TG_STREAM_PACKETS );

	printf("TG_Connect struct: %d, %s, %d \n", connectionId, comPortName, TG_BAUD_57600);
    if( errCode < 0 ) {
        fprintf( stderr, "ERROR: TG_Connect() returned %d.\n", errCode );
        wait();
        exit( EXIT_FAILURE );
    }

    errCode = TG_EnableBlinkDetection( connectionId, 1 );
    if( errCode < 0 ) {
        fprintf( stderr, "ERROR: TG_EnableBlinkDetection() returned %d.\n", errCode );
        wait();
        exit( EXIT_FAILURE );
    }


	do
	{
		readdata();
		if(blink>=80)
			trncmd();
		else if(att>=68)
			fwdcmd();
		//wait();
		 
	}while(1);

    /* Clean up */
    TG_FreeConnection( connectionId );

    /* End program */
    wait();
    return( EXIT_SUCCESS );
}
Ejemplo n.º 4
0
/**
 * Erstellet einen Socket der horcht
 * @param Der jeweilige Socketdiskriptor 
 * @param Fehlercode
 * @return Der Rückgabewert ist ein Integer und gibt den Socket Deskriptor an
 */ 
int openListenSocket(int lsd,int error){
	 int result = opensocket(SOCK_STREAM, &error);
   	 if(result == API_ERROR){
    	printf("\r\nTCP Echoserver, Open socket failed %d",error);
      	shutDownServer(lsd,error);
   		}//if(result == API_ERROR)
   	 return result;
	}//openListenSocket()
Ejemplo n.º 5
0
static Chan*
fsopen(Chan *c, int mode)
{
	char *path;
	int m;
	UnixFd *ufd;
	
	ufd = c->aux;
	if(Trace)
		print("fsopen %s %#x\n", ufd->path->s, mode);

	/* protect files whose path does not begin with allowed */
	if(strncmp(ufd->path->s, canopen, strlen(canopen)) != 0)
		error(Eperm);

	if(mode & ~(OTRUNC|ORCLOSE|3))
		error(Ebadarg);

	if((c->qid.type & QTDIR) && mode != OREAD)
		error(Eperm);
	
	if((c->qid.type&QTDIR) && mode != OREAD)
		error(Eperm);

	c->mode = openmode(mode);
	path = fspath(c, nil);
	if(c->qid.type & QTDIR){
		ufd->dir = opendir(path);
		if(ufd->dir == nil){
			free(path);
			oserror();
		}
		ufd->diroffset = 0;
		ufd->nextde = nil;
	}else{
		m = mode & 3;
		if(m == OEXEC)
			m = OREAD;
		if(mode & OTRUNC)
			m |= O_TRUNC;
		if((ufd->fd = open(path, m)) < 0 && opensocket(ufd, path) < 0){
			free(path);
			oserror();
		}
	}
	free(path);
	c->flag |= COPEN;
	return c;
}
Ejemplo n.º 6
0
static int
probe_pubalgo()
{
  char hashhex[1024];
  byte buf[8192], *bp;
  u32 signtime = time(NULL);
  int i, ulen, outl;

  opensocket();
  ulen = strlen(user);
  bp = (byte *)hashhex;
  for (i = 0; i < hashlen[hashalgo]; i++, bp += 2)
    sprintf((char *)bp, "01");
  sprintf((char *)bp, "@00%08x", (unsigned int)signtime);

  if (!privkey)
    {
      /* old style sign */
      if (ulen + strlen(hashhex) + 4 + 1 + (hashalgo == HASH_SHA1 ? 0 : strlen(hashname[hashalgo]) + 1) > sizeof(buf))
	{
	  closesocket();
	  return -1;
	}
      buf[0] = ulen >> 8;
      buf[1] = ulen;
      buf[2] = 0;
      buf[3] = 0;
      memmove(buf + 4, user, ulen);
      bp = buf + 4 + ulen;
      if (hashalgo != HASH_SHA1)
	{
	  strcpy((char *)bp, hashname[hashalgo]);
	  bp += strlen((const char *)bp);
	  *bp++ = ':';
	}
      strcpy((char *)bp, hashhex);
      bp += strlen((char *)bp);
      buf[3] = bp - (buf + 4 + ulen);
      outl = doreq_old(buf, (int)(bp - buf), sizeof(buf));
    }
  else
    {
Ejemplo n.º 7
0
int main (int argc, char *argv[]) {
	pthread_pool *tp = NULL;
	int  piped[2]
	  , sd
	  , csd;

	/*   log   */
	if(pipe(piped) < 0) {
		printf("NOp!!\n");
		return 0;	
	}
	

	if(fork() == 0) {
		int readed = 0
		  , logd;
		char buffer[1024]
		   , *datestring;

		time_t date;

		memset(buffer, '\0', 1024);

		logd = open("log.out", O_RDWR | O_CREAT | O_APPEND, 0644);
		if(logd < 0) {
			printf("Nop!!!\n");
			return -1;
		}

		close(piped[1]);

		while((readed = read(piped[0], buffer, 1024)) > 0) {
			time(&date);
			datestring = ctime((const time_t *)&date);
			// -1 to avoit the \n at the end of datestring
			write(logd, datestring, (strlen(datestring) - 1));
			write(logd, buffer, readed);
		}
		return 0;
	}

	close(piped[0]);
	/* end log */

	sd = opensocket();

	/* pthread_pool create */
	tp = pthread_pool_create(NULL);
	if(tp == NULL) {
		write(2, "No se pudo crear el thread pool!\n", 33);
		return -1;
	}

	printf ("threads: %d\n", tp->current);
	/* end pthread_pool create */


	listen (sd,10);
	printf("listening...\n");

	while ((csd = accept(sd, NULL, NULL)) > 0) {

		if (csd <1)
		{
			perror("accept");
			return -1;
		}
		
		write(piped[1], " Request Received\n", 19);

		add_new_task(&(tp->list), tramullo, (void *) &csd, 1);	
	}

	return 0;
}
Ejemplo n.º 8
0
signed function (struct plc * plc, char const * socket)

{
	struct channel * channel = (struct channel *)(plc->channel);
	struct message * message = (struct message *)(plc->message);

	static char const * actions [] =
	{
		"start device",
		"store firmware",
		"store parameters",
		"update host",
		"config memory",
		"restore defaults",
		"unknown"
	};

#ifndef __GNUC__
#pragma pack (push,1)
#endif

	struct __packed vs_host_action_ind
	{
		struct ethernet_hdr ethernet;
		struct qualcomm_hdr qualcomm;
		uint8_t MACTION;
		uint8_t MAJOR_VERSION;
		uint8_t MINOR_VERSION;
	}
	* indicate = (struct vs_host_action_ind *) (message);

#ifndef __GNUC__
#pragma pack (pop)
#endif

	signed fd = opensocket (socket);
	char firmware [PLC_VERSION_STRING];
	char const * FactoryNVM = plc->NVM.name;
	char const * FactoryPIB = plc->PIB.name;
	signed action;
	signed status;
	write (fd, MESSAGE, strlen (MESSAGE));
	while (!done)
	{
		status = ReadMME (plc, 0, (VS_HOST_ACTION | MMTYPE_IND));
		if (status < 0)
		{
			break;
		}
		if (status < 1)
		{
			continue;
		}
		action = indicate->MACTION;
		if (action < SIZEOF (actions))
		{
			fprintf(stderr, "plchostd2: action = %s\n", actions[action]);
		}
		else
		{
			fprintf(stderr, "plchostd2: action = %d\n", action);
		}
		memcpy (channel->peer, indicate->ethernet.OSA, sizeof (channel->peer));
		if (HostActionResponse (plc))
		{
			return (-1);
		}
		if (action == 0x00)
		{
			if (BootDevice2 (plc))
			{
				return (-1);
			}
			if (WaitForStart (plc, firmware, sizeof (firmware)))
			{
				return (-1);
			}
			if (_anyset (plc->flags, PLC_FLASH_DEVICE))
			{
				FlashDevice2 (plc, (PLC_COMMIT_FORCE | PLC_COMMIT_NORESET | PLC_COMMIT_FACTPIB));
			}
			continue;
		}
		if (action == 0x01)
		{
			close (plc->NVM.file);
			if (ReadFirmware2 (plc))
			{
				return (-1);
			}
			if ((plc->NVM.file = open (plc->NVM.name = plc->nvm.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->NVM.name);
			}
			continue;
		}
		if (action == 0x02)
		{
			close (plc->PIB.file);
			if (ReadParameters2 (plc))
			{
				return (-1);
			}
			if ((plc->PIB.file = open (plc->PIB.name = plc->pib.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->PIB.name);
			}
			if (ResetDevice (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x03)
		{
			close (plc->PIB.file);
			if (ReadParameters2 (plc))
			{
				return (-1);
			}
			if ((plc->PIB.file = open (plc->PIB.name = plc->pib.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->PIB.name);
			}
			close (plc->NVM.file);
			if (ReadFirmware2 (plc))
			{
				return (-1);
			}
			if ((plc->NVM.file = open (plc->NVM.name = plc->nvm.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->NVM.name);
			}
			if (ResetDevice (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x04)
		{
			if (InitDevice2 (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x05)
		{
			close (plc->NVM.file);
			if ((plc->NVM.file = open (plc->NVM.name = FactoryNVM, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->NVM.name);
			}
			close (plc->PIB.file);
			if ((plc->PIB.file = open (plc->PIB.name = FactoryPIB, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->PIB.name);
			}
			if (ResetDevice (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x06)
		{
			close (plc->PIB.file);
			if (ReadParameters2 (plc))
			{
				return (-1);
			}
			if ((plc->PIB.file = open (plc->PIB.name = plc->pib.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->PIB.name);
			}
			continue;
		}
		error (0, ENOSYS, "Host Action 0x%02X", action);
	}
	close (fd);
	return (0);
}
/* Open port and convert SLIP-encoded packets into UDP packets */
int sliptoudp(const char *infile, const char *host, char dump)
{
	#define BUFFER_SIZE 0xffff
	static char buffer[BUFFER_SIZE];
	size_t bufferLength = 0;
	int fd;
	struct sockaddr_in serverAddr;
	SOCKET s = SOCKET_ERROR;

	fd = fileno(stdin);
	if (infile != NULL && infile[0] != '\0' && !(infile[0] == '-' && infile[1] == '\0'))
	{
#ifdef _WIN32
		fd = open(infile, O_BINARY | O_RDONLY);
#else
		fd = open(infile, O_RDONLY | O_NOCTTY | O_NDELAY);
#endif
		
		if (fd < 0)
		{
			fprintf(stderr, "ERROR: Problem opening input: %s\n", infile);
			return 2;
		}
#ifdef _WIN32
#else
		fcntl(fd, F_SETFL, 0);	/* Clear all descriptor flags */
		/* Set the port options */
		{
			struct termios options;
			
			int rts = TIOCM_RTS, cts = TIOCM_CTS;
			ioctl(fd, TIOCMBIC, &rts);
			ioctl(fd, TIOCMBIC, &cts);
			
			tcgetattr(fd, &options);
			options.c_cflag = (options.c_cflag | CLOCAL | CREAD | CS8) & ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
			options.c_lflag &= ~(ICANON | ECHO | ISIG);
			tcsetattr(fd, TCSANOW, &options);
			
		}
#endif
	}

#ifdef _WIN32
	{
		WSADATA wsaData;
		WSAStartup(MAKEWORD(1, 1), &wsaData);
	}
#endif

	/* Open UDP socket */
	if (host != NULL)
	{
		s = opensocket(host, 1234, &serverAddr);
	}

	/* Read packets and transmit */
	{
		size_t len;
		while ((len = slipread(fd, buffer, BUFFER_SIZE)) != 0)
		{
		//	if (dump) { hexdump(buffer, len); }
			if (s != SOCKET_ERROR)
			{ 
				size_t tlen = transmit(s, &serverAddr, buffer, len);
				if (tlen != len) { fprintf(stderr, "WARNING: Problem transmitting: %d / %d\n", (unsigned int)tlen, (unsigned int)len); }
			}
		}
	}

	/* Close socket */
	if (s != SOCKET_ERROR) { closesocket(s); }

	/* Close file */
	if (fd != fileno(stdin)) { close(fd); }

#ifdef _WIN32
	WSACleanup();
#endif

	return (s != SOCKET_ERROR) ? 0 : 1;
}
Ejemplo n.º 10
0
/******************************************************************************
* main()
******************************************************************************/
int main(void)
{
   struct sockaddr_in   addr;
   struct sockaddr_in   claddr;


   int sd;
   int asd;
   int established = 0;

   #ifdef  PRINT_DATA
   int i;
   #endif
   
   int retval;
   int error;


   printf("\r\nTCPserver, listening on port %d\r\n",TM_PORT_ECHO);
   
   #ifdef TCP_ECHO_SERVER_DEBUG
   printf("\r\nOpen socket");
   #endif
   
   /**********************************************************************/
   //API call open socket START
   /**********************************************************************/   
   //Hiermit wird ein Socket geöffnet. D.h. nicht das eine Socketverbindung aufgebaut wird
   //es steht jetzt nur ein Socket zur Verfügung
   //1.Param.: SOCK_STREAM = 1 für TCP socket(Verbindungorientiert)
   //2.Param.: Fehlercode
   //Rückgabewert: -1==API_ERROR ansonsten Socket deskriptor
   retval = opensocket( SOCK_STREAM, &error );

   	if(retval == API_ERROR){
       printf("\r\nSocket open failed: %d",error);
       goto TCP_SERVER_DONE;
	   }
   	else{
       sd = retval;
   		}
   /**********************************************************************/
   //API call open socket ENDE
   /**********************************************************************/
   

   /**********************************************************************/
   //API-Call bind
   /**********************************************************************/
   //addr.sin_len    =  sizeof(struct sockaddr_in); // Ausgeklammert von Beck
   
   // Weist einem Socket eine lokale Protokoll Adresse zu   
   addr.sin_family =  PF_INET; // Protocoll Familie 
   //convert your sending port to correct byte order! SEHR WICHTIG
   retval = htons(TM_PORT_ECHO);
   addr.sin_port =  retval;
   
   // Das 'sin_addr' Attribut ist eine einfache IP Adresse in big endian byte order
   addr.sin_addr.s_addr =  0L;

   //call bind
   retval = bind( sd, (const struct sockaddr *)&addr, &error );
   if(retval == API_ERROR)
   {
       printf("\r\nTCPserver: Socket bind failed: %d",error);
       goto TCP_SERVER_DONE;
   }


   while(1)   //do forever
   {
     /**********************************************************************/
     //API-Call listen for connections
     /**********************************************************************/
     //Mit Listen versetzt man einen Socket in Lauschmodus
     printf("\r\nTCPserver: Listening for connection");

     
     // @Param1.: Der eigentliche Socket
     // @Param2.: Der Backlog, hier kann man die Länge der Warteschlange eingeben für die 
     //			  nicht vollständig verbundenen Clients. Z.b. Solche die eine Anfrage gesendet haben 
     //			  und auf einen Response warten(Thema Parallele Clients bedienen). Laut Beck API 
     //			  sind maximal 5 ausstehende Verbindung hier möglich.
     //           http://www.beck-ipc.com/files/ipc/documentation/api/scxxx/CLIB/TCPIP/tcp0E.htm
     // @Param3.: Fehlercode
     // Rückgabewert: 0 für erfolgreich ansonsten -1=API_ERROR
     retval = listen( sd, 1, &error );

     	if(retval == API_ERROR){
         printf("\r\nTCPserver: Socket listen failed: %d",error);
         goto TCP_SERVER_DONE;
	     }



     /**********************************************************************/
     //API-Call accept, establish a connection
     /**********************************************************************/
	 // Holt einen Client ab von einem lauschendem Socket
     claddr.sin_family      =  PF_INET;
     claddr.sin_port        =  0;
     claddr.sin_addr.s_addr =  0L;

	 // @Param1.: Socketdeskriptor der lauscht(MUß VORHER IN DEN LISTEN-MODUS VERSTEZT WERDEN)
	 // @Param2.: Ein Optionaler Parameter, ein Zeiger auf eine Struktur worüber man die Client IP und
	 //  		  Port ermitteln kann. Kann man auch mit 0 stehen lassen
	 // @Param3.: Fehlercode
	 // Rückgabewert: 0 für erfolgreich ansonsten -1=API_ERROR
     retval = accept( sd, (struct sockaddr *)&claddr, &error );

     	if(retval == API_ERROR){
         printf("\r\nTCPserver: Socket accept failed: %d",error);
         goto TCP_SERVER_DONE;
		}

     //save the new socketdescriptor
     asd = retval;
     established = 1;

     //get clients IP
     InetToAscii( (unsigned long *) &claddr.sin_addr.s_addr, (char *) ClientIP );

     printf("\r\nTCPserver: Connected with %s , Port %u\r\n",ClientIP, htons(claddr.sin_port));

     
     
     
     
     while(established)   //loop forever
     {

       /*******************************************************************/
       //Wait for incoming data from the client
       //To prevent a socketoverrun, we read all available data from the socket
       /*******************************************************************/
       do
       {

          //recv() wird eingesetzt um Daten von einem verbundenem Socket zu lesen
          // @Param1.: Der Socket Deskriptor des Clients
          // @Param2.: Zeigt auf einen Puffer der die aufzunehmenden Daten aufnehmen soll
          // @Param3.: Größe des Puffers(hier eine Konstante mit dem wert 1024)
          // @Param4.: Hier wird ein optionale Flag gesetzt. 
		  // 		   Auszug aus der API:
		  //          		Wait option:
	      //    					* MSG_BLOCKING - Sleep until data comes in.
		  //  						* MSG_TIMEOUT - The caller wakes up after timeout or if bufLen data is received.
    	  //						* MSG_DONTWAIT - Return immediately after collecting what ever data is ready.
    	  //     Sieh dazu API: http://www.beck-ipc.com/files/ipc/documentation/api/scxxx/CLIB/TCPIP/tcp10.htm
		  // @Param5.: Maximalla Zeit in Millisekunden wenn flag = MSG_TIMEOUT gesetzt isz
		  // @Param6.: Fehlercode, 
		  // Rückgabewert: -1=API_ERROR ansonsten Anzahl der gesendeten Bytes die in den Puffer geschrieben werden
          retval = recv( asd, (char *)recvbuf, TM_TCPECHOBUF_SERVER_RECVSIZE, MSG_TIMEOUT, 20000L, &error );

          	if(retval == API_ERROR){
             	#ifdef TCP_ECHO_SERVER_DEBUG
	            printf("\r\nTCPserver: Recverror %d",error);
    	        #endif
           	   established = 0;
           	   break;
          		}
          	else{
          		
               	if( retval > 0){//data received
                  #ifdef  PRINT_DATA
             		printf("\r\nTCPserver: Received data\r\n");
                 	for(i=0;i<retval; i++){
                   		printf("%02X ",(char)recvbuf[i]);
                 	}//for(i=0;i<outregs.x.ax;i++)
             		printf("\r\n");
             		#endif
             				             				
/*****************************Rückgabe zum Client START ******************************/

               		//send
               		retval = send( asd, (char *)recvbuf, retval, 0, &error );

               		if(retval == API_ERROR){
                   		#ifdef TCP_ECHO_SERVER_DEBUG
                   	    printf("\r\nTCPserver: Senderror %d",error);
                   		#endif
                 		established = 0;
                 		break;
               			}
			   	 }//if(retval > 0)    //data received
           	    else{
             		#ifdef TCP_ECHO_SERVER_DEBUG
             		printf("\r\nTCPserver: Nothing received %d\r\n",error);
                	#endif
           			}
          		}//elseif(retval == API_ERROR)

/*****************************Rückgabe zum Client ENDE ********************************/


          /*****************************************************************/
          //Check, if there is more data available at the socket ?
          /*****************************************************************/

          retval = GetWaitingBytes( asd, &error );

        	#ifdef TCP_ECHO_SERVER_DEBUG
          	if(retval==API_ENOERROR){
	           printf("\r\nTCPserver: Bytes waiting on the socket  %d",retval);
	         }
        	#endif
       }//while data available
       while((retval!=API_ERROR) && (retval>0));
     }//while(established)


     //close socket, given from accept
     printf("\r\nTCPserver: Closing connection");

     retval = closesocket( asd, &error );
	
	     #ifdef TCP_ECHO_SERVER_DEBUG
    	 if(retval==API_ERROR){
		      printf("\r\nTCPserver: Socket close failed: %d",error);
     		}
     	#endif

   }//while(1)

   /************************************/
   //Shutdown server, should not happen
   /************************************/

TCP_SERVER_DONE:

   printf("\r\nTCPserver: Closing listening socket");
   retval = closesocket( sd, &error );

   #ifdef TCP_ECHO_SERVER_DEBUG
   if(retval==API_ERROR)
   {
    printf("\r\nTCPserver: Socket close failed %d",error);
   }
   #endif


   return 0;

}
Ejemplo n.º 11
0
signed function (struct plc * plc, char const * socket)

{
	struct channel * channel = (struct channel *)(plc->channel);
	struct message * message = (struct message *)(plc->message);

#ifndef __GNUC__
#pragma pack (push,1)
#endif

	struct __packed vs_host_action_ind
	{
		struct ethernet_hdr ethernet;
		struct qualcomm_hdr qualcomm;
		uint8_t MACTION;
		uint8_t MAJOR_VERSION;
		uint8_t MINOR_VERSION;
	}
	* indicate = (struct vs_host_action_ind *) (message);

#ifndef __GNUC__
#pragma pack (pop)
#endif

	byte buffer [3000];
	struct plctopology * plctopology = (struct plctopology *)(buffer);
	signed fd = opensocket (socket);
	char const * FactoryNVM = plc->NVM.name;
	char const * FactoryPIB = plc->PIB.name;
	signed action;
	signed status;
	memset (buffer, 0, sizeof (buffer));
	write (fd, MESSAGE, strlen (MESSAGE));
	while (!done)
	{
		status = ReadMME (plc, 0, (VS_HOST_ACTION | MMTYPE_IND));
		if (status < 0)
		{
			break;
		}
		if (status < 1)
		{
			PLCTopology (channel, message, plctopology);
			PLCTopologyPrint (plctopology);
			continue;
		}
		action = indicate->MACTION;
		memcpy (channel->peer, indicate->ethernet.OSA, sizeof (channel->peer));
		if (HostActionResponse (plc))
		{
			return (-1);
		}
		if (action == 0x00)
		{
			if (BootDevice2 (plc))
			{
				return (-1);
			}
			if (_anyset (plc->flags, PLC_FLASH_DEVICE))
			{
				FlashDevice2 (plc);
			}
			continue;
		}
		if (action == 0x01)
		{
			close (plc->NVM.file);
			if (ReadFirmware1 (plc))
			{
				return (-1);
			}
			if ((plc->NVM.file = open (plc->NVM.name = plc->nvm.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->NVM.name);
			}
			if (ResetDevice (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x02)
		{
			close (plc->PIB.file);
			if (ReadParameters (plc))
			{
				return (-1);
			}
			if ((plc->PIB.file = open (plc->PIB.name = plc->pib.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->PIB.name);
			}
			if (ResetDevice (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x03)
		{
			close (plc->PIB.file);
			if (ReadParameters (plc))
			{
				return (-1);
			}
			if ((plc->PIB.file = open (plc->PIB.name = plc->pib.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->PIB.name);
			}
			close (plc->NVM.file);
			if (ReadFirmware1 (plc))
			{
				return (-1);
			}
			if ((plc->NVM.file = open (plc->NVM.name = plc->nvm.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->NVM.name);
			}
			if (ResetDevice (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x04)
		{
			if (InitDevice (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x05)
		{
			close (plc->NVM.file);
			if ((plc->NVM.file = open (plc->NVM.name = FactoryNVM, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->NVM.name);
			}
			close (plc->PIB.file);
			if ((plc->PIB.file = open (plc->PIB.name = FactoryPIB, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->PIB.name);
			}
			if (ResetDevice (plc))
			{
				return (-1);
			}
			continue;
		}
		if (action == 0x06)
		{
			close (plc->PIB.file);
			if (ReadParameters (plc))
			{
				return (-1);
			}
			if ((plc->PIB.file = open (plc->PIB.name = plc->pib.name, O_BINARY|O_RDONLY)) == -1)
			{
				error (1, errno, "%s", plc->PIB.name);
			}
			continue;
		}
		error (0, ENOSYS, "Host Action 0x%02X", action);
	}
	close (fd);
	return (0);
}
Ejemplo n.º 12
0
int main(int argc, char** argv)
{
	char* configfile;
	const char* socketfile = NULL;
	mode_t permission = S_IRUSR | S_IWUSR;
	int socket;
	int lircdfd;
	struct sigaction act;
	struct sockaddr_un addr;
	char dir[FILENAME_MAX + 1] = { 0 };

	lirc_log_open("lircrcd", 0, LIRC_NOLOG);
	while (1) {
		int c;
		static struct option long_options[] = {
			{ "help",	no_argument,	   NULL, 'h' },
			{ "version",	no_argument,	   NULL, 'v' },
			{ "permission", required_argument, NULL, 'p' },
			{ "output",	required_argument, NULL, 'o' },
			{ 0,		0,		   0,	 0   }
		};
		c = getopt_long(argc, argv, "hvp:o:", long_options, NULL);
		if (c == -1)
			break;
		switch (c) {
		case 'h':
			printf("Usage: %s [options] config-file\n", progname);
			printf("\t -h --help\t\t\tdisplay this message\n");
			printf("\t -v --version\t\t\tdisplay version\n");
			printf("\t -p --permission=mode\t\tfile permissions for socket\n");
			printf("\t -o --output=socket\t\toutput socket filename\n");
			return EXIT_SUCCESS;
		case 'v':
			printf("%s %s\n", progname, VERSION);
			return EXIT_SUCCESS;
		case 'p':
			if (oatoi(optarg) == -1) {
				fprintf(stderr, "%s: invalid mode\n", progname);
				return EXIT_FAILURE;
			}
			permission = oatoi(optarg);
			break;
		case 'o':
			socketfile = optarg;
			break;
		default:
			printf("Usage: %s [options] config-file\n", progname);
			return EXIT_FAILURE;
		}
	}
	if (optind == argc - 1) {
		configfile = argv[optind];
	} else {
		fprintf(stderr, "%s: invalid argument count\n", progname);
		return EXIT_FAILURE;
	}

	lircdfd = lirc_init("lircrcd", 0);
	if (lircdfd == -1)
		return EXIT_FAILURE;

	/* read config file */
	if (lirc_readconfig_only(configfile, &config, NULL) != 0) {
		lirc_deinit();
		return EXIT_FAILURE;
	}

	/* open socket */
	socket = opensocket(config->lircrc_class, socketfile, permission, &addr);
	if (socket == -1) {
		lirc_freeconfig(config);
		lirc_deinit();
		return EXIT_FAILURE;
	}

	/* fork */
	if (getcwd(dir, sizeof(dir)) == NULL) {
		lirc_freeconfig(config);
		lirc_deinit();
		perror("getcwd()");
		return EXIT_FAILURE;
	}
	if (daemon(0, 0) == -1) {
		perror("daemon() failed");
		shutdown(socket, 2);
		close(socket);
		lirc_deinit();
		lirc_freeconfig(config);
		return EXIT_FAILURE;
	}
	daemonized = 1;

	openlog(progname, LOG_CONS | LOG_PID, LOG_USER);
	umask(0);
	signal(SIGPIPE, SIG_IGN);

	act.sa_handler = sigterm;
	sigfillset(&act.sa_mask);
	act.sa_flags = SA_RESTART;      /* don't fiddle with EINTR */
	sigaction(SIGTERM, &act, NULL);
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGHUP, &act, NULL);

	log_notice("%s started", progname);
	loop(socket, lircdfd);

	closelog();
	shutdown(socket, 2);
	close(socket);
	if (chdir(dir) == 0)
		unlink(addr.sun_path);
	lirc_freeconfig(config);
	lirc_deinit();
	return EXIT_SUCCESS;
}