static void *simple_client(void *cxt)
{
   int i;
   VCOS_MSGQUEUE_T *q;
   VCOS_MSG_ENDPOINT_T self;

   VCOS_STATUS_T st = vcos_msgq_endpoint_create(&self, "client");
   vcos_assert(st == VCOS_SUCCESS);

   q = vcos_msgq_wait("server");

   server_open(q);

   for (i=0; i<1024; i++)
   {
      VCOS_MSG_T msg;
      struct my_msg_t *body = VCOS_MSG_DATA(&msg);
      body->i = i;
      vcos_msg_sendwait(q, MSG_N_MY_MSG, &msg);
      vcos_assert(body->i == i+1); // did the server bump the count?
   }

   server_close(q);

   vcos_msgq_endpoint_delete(&self);
   return (void*)i;
}
Esempio n. 2
0
static int XFP(XFlash *Xf,int server){
	IStr(svhost,MaxHostNameLen);
	int svport;
	int svsock;
	int timeout = 0;
	Connection *Conn = Xf->xf_Conn;

	if( !server ){
		XFlashClient(Xf);
		return 0;
	}

	/* observers */
	strcpy(svhost,"0.0.0.0");
	svport = 6003;
	svsock = server_open("XFlash",AVStr(svhost),svport,1);
	for(;;){
		/* broad casting ? */
		Xf->xf_xfsockfd = ACCEPT(svsock,0,-1,timeout);
		Xf->xf_xfsockfp = fdopen(Xf->xf_xfsockfd,"w+");
		fprintf(stderr,"---- xfsock[%d]\n",Xf->xf_xfsockfd);
		toFlash(Xf,"INIT");
	}
	return 0;
}
Esempio n. 3
0
static int XFlashClient(XFlash *Xf){
	Connection *Conn = Xf->xf_Conn;
	FILE *fc;
	FILE *tc;
	IStr(req,128);
	IStr(com,128);
	IStr(arg,128);
	const char *dp;
	IStr(svhost,128);
	int svsock;
	int port;
	IStr(dispenv,128);
	int actid;

	fc = fdopen(FromC,"r");
	tc = fdopen(ToC,"w");
	if( tc == NULL || fc == NULL ){
		return -1;
	}
	Xf->xf_xfsockfp = tc;
	toFlash(Xf,"INIT2");
	fflush(tc);

	strcpy(svhost,"127.0.0.1");
	for( port = 6001; port < 6010; port++ ){
		svsock = server_open("XFlash",AVStr(svhost),port,1);
		if( 0 <= svsock ){
			break;
		}
	}
	sprintf(dispenv,"DISPLAY=127.0.0.1:%d.0",port-6000);
	fprintf(stderr,"--- env[%s]\n",dispenv);
	actid = thread_fork(0,0,"XFlash-TH",(IFUNCP)Xnew,Xf,svsock);

	for(;;){
		if( fgets(req,sizeof(req),fc) == NULL ){
			break;
		}
		dp = wordScan(req,com);
		dp = lineScan(dp,arg);
		fprintf(stderr,"---- [%s][%s]\n",com,arg);
		if( strcaseeq(com,"quit") || strcaseeq(com,"exit") ){
			break;
		}
		if( strcaseeq(com,"x") ){
			forkXclient(arg,dispenv);
		}
	}
	return 0;
}
Esempio n. 4
0
/*
 * The server_update() function is called whenever the channel count is
 * changed. We maintain the SDP record and open or close the server socket
 * as required.
 */
void
server_update(int count)
{

	if (server_limit == 0)
		return;

	log_debug("count %d", count);

	server_avail = UINT8_MAX - (count - 1) * UINT8_MAX / server_limit;
	log_info("Service Availability: %d/%d", server_avail, UINT8_MAX);

	if (server_avail == 0 && server_fd != -1)
		server_close();

	if (server_avail > 0 && server_fd == -1)
		server_open();

	if (service_name)
		server_register();
}
Esempio n. 5
0
static void PASV(FILE *tc,int *vsockp){
	VSAddr ba;
	int balen;
	CStr(mport,128);
	int vsock = -1;

	vsock = server_open("SftpGW",VStrNULL,0,1);
	if( 0 <= vsock ){
		balen = sizeof(ba);
		getsockname(vsock,(SAP)&ba,&balen);
#if defined(__CYGWIN__)
		if( VSA_addrisANY(&ba) ){
		    /*connection to 0.0.0.0 fails on CYGWIN?*/
		    VSA_atosa(&ba,VSA_port(&ba),"127.0.0.1");
		}
#endif
		VSA_prftp(&ba,AVStr(mport));
		putresp(tc,227,"Enterning Passive Mode (%s)",mport);
		*vsockp = vsock;
	}else{
		putresp(tc,500,"No");
	}
}
Esempio n. 6
0
File: main.c Progetto: jnwu/nanork
main (int Parm_Count, char *Parms[])
{

  long BAUD, DATABITS, STOPBITS, PARITYON, PARITY;
  char devicename[80];
  char debug_flag[80];
  int fd, tty, slipin, slipout, res, i, error;
  int received = 0, port_num,tmp_pcount;
  uint8_t c;
  FILE *np;
  int mode, val;
  //place for old and new port settings for serial port
  struct termios oldtio, newtio;
  int start_flag;

  got_connection = 0;
  reply_mode = LAST_CONNECTION;

  mode = ASCII;

  BAUD = B115200;
  DATABITS = CS8;
  STOPBITS = 0;
  //STOPBITS = CSTOPB;
  PARITYON = 0;
  PARITY = 0;
  //PARITYON = PARENB;
  //PARITY = PARODD;
  if (Parm_Count < 3 || Parm_Count > 6)
    print_usage ();
  strcpy (buf, Parms[1]);
  i = sscanf (buf, "%s", devicename);
  if (i != 1)
    print_usage ();
  //open the device(com port) to be non-blocking (read will return immediately)
  fd = open (devicename, O_RDWR | O_NOCTTY | O_NONBLOCK);
  if (fd < 0) {
    perror (devicename);
    exit (-1);
  }
  strcpy (buf, Parms[2]);
  i = sscanf (buf, "%d", &port_num);
  if (i != 1)
    print_usage ();
  debug = 0;
  tmp_pcount=3;
  //if (Parm_Count > 3) {
  while(tmp_pcount<Parm_Count)
  {
    strcpy (buf, Parms[tmp_pcount]);
    i = sscanf (buf, "%s", debug_flag);
    if (i != 1)
      print_usage ();
    if (strcmp (debug_flag, "-d") == 0)
      debug = 1;
    else if (strcmp (debug_flag, "-s") == 0)
      debug = 2;
    else if (strcmp (debug_flag, "-a") == 0)
	{
	reply_mode=STATIC_CLIENT;
	tmp_pcount++;
	if(tmp_pcount>=Parm_Count) print_usage();
    	strcpy (reply_address, Parms[tmp_pcount]);
	}
    else 
    	print_usage ();
    tmp_pcount++;
  }


  if(debug!=2) printf ("opened: %s\n", devicename);
  tcgetattr (fd, &oldtio);      // save current port settings 
  // set new port settings for canonical input processing 
  newtio.c_cflag =
    BAUD | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
  newtio.c_iflag = IGNPAR;
  newtio.c_oflag = 0;
  newtio.c_lflag = 0;           //ICANON;
  newtio.c_cc[VMIN] = 1;
  newtio.c_cc[VTIME] = 0;
  tcflush (fd, TCIFLUSH);
  tcsetattr (fd, TCSANOW, &newtio);

  server_open (port_num);
  start_flag = 0;
  while (1) {
    server_non_blocking_rx (fd);
    res = read (fd, &c, 1);
    if (res > 0) {

      if (c == START)
        mode = SLIP;
      if (mode == ASCII)
        if(debug!=2) printf ("%c", c);
      if (mode == SLIP) {
        slip_rx (fd);
        mode = ASCII;
      } 

    } else usleep(10000);
  }
}                               //end of main
Esempio n. 7
0
int main(int argc, char const * argv[]) {
	const char * config_file;
	int connection_numer = 0, ret, pid;
	short vals[SEM_SIZE] = {1, 1};
	key_t key = ftok("database.sql", KEY_ID);
	key_t key_db = ftok("database.sql", KEY_DB_ID);

	switch(argc) {
		case 1: {
			config_file = CONFIG_FILE_DEFAULT;
		} break;

		case 2: {
			config_file = argv[1];
		} break;

		default: {
			fprintf(stderr, "Usage: 'server.app [config_file]'.\n");
			exit(EXIT_FAILURE);
		}
	}

	pcg32_srandom(time(NULL), (intptr_t)&connection_numer);

	server_sems = sem_make(key, SEM_SIZE, vals);
	if(server_sems == -1) {
		fprintf(stderr, "1 Can't create neccessary data to operate.\n");
		exit(EXIT_FAILURE);
	}

	bettors = mmap(NULL, sizeof(*bettors), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
	if(bettors == MAP_FAILED) {
		fprintf(stderr, "2 Can't create neccessary data to operate.\n");
		exit(EXIT_FAILURE);
	}

	clients = mmap(NULL, sizeof(*clients), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
	if(clients == MAP_FAILED) {
		fprintf(stderr, "3 Can't create neccessary data to operate.\n");
		exit(EXIT_FAILURE);
	}

	winner = mmap(NULL, sizeof(*winner) * MAX_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
	if(winner == MAP_FAILED) {
		fprintf(stderr, "4 Can't create neccessary data to operate.\n");
		exit(EXIT_FAILURE);
	}

	*bettors = 0;
	*clients = 0;
	memset(winner, 0, sizeof(*winner) * MAX_SIZE);

	if(!log_open()) {
		fprintf(stderr, "Can't connect logging server.\n");
		//exit(EXIT_FAILURE);
	}

	database = smemory_open(key_db); // TODO: define 8080
	if(database == NULL) {
		fprintf(stderr, "Can't reach the database.\n");
		exit(EXIT_FAILURE);
	}

	connection = server_open(config_file);
	if(connection == NULL) {
		fprintf(stderr, "Can't create the main connection.\n");
		exit(EXIT_FAILURE);
	}

	signal(SIGINT, handle_int);
	signal(SIGCHLD, handle_int);

	while(TRUE) {
		connection_t connection_accepted;

		connection_accepted = server_accept(connection);
		if(connection_accepted == NULL) {
			log_send(LEVEL_ERROR, "[MAIN SV] Can't connect to client.");
			exit(EXIT_FAILURE); // TODO: Exit?
		}

		connection_numer++;
		(*clients)++;

		pid = fork();
		if(pid == -1) {
			log_send(LEVEL_ERROR, "[MAIN SV] Can't assign resources to client.");
			exit(EXIT_FAILURE); // TODO: Exit?
		}

		if(!pid) { // Child process
			// sem_lock(server_sems, 1);
			// (*clients)++;
			// sem_unlock(server_sems, 1);
			server_ajar(connection);
			log_send(LEVEL_INFO, "[CHILD SV] Disconnecting main connection.");

			ret = handle(connection_accepted);
			if(ret == EXIT_FAILURE) {
				log_send(LEVEL_ERROR, "[CHILD SV] There was an error handling client.");
			}

			server_close(connection_accepted);
			log_send(LEVEL_INFO, "[CHILD SV] Closed client connection.");
			// sem_lock(server_sems, 1);
			// (*clients)--;
			// sem_unlock(server_sems, 1);
			exit(ret);
		}

		log_send(LEVEL_INFO, "[MAIN SV] Disconnecting new connection.");
		server_ajar(connection_accepted);
	}

	server_close(connection);
	if(!db_close(database)) {
		log_send(LEVEL_ERROR, "[MAIN SV] Couldn't correctly logout from database.");
	}
	log_close();
	sem_remove(server_sems);

	return 0;
}
Esempio n. 8
0
int main (int argc, char *argv[])
{
    char devicename[80];
    int fd, res;
    uint8_t c;
    struct termios oldtio, newtio;
    int start_flag;

    got_connection = 0;

    mode_t mode = ascii;

    long BAUD = B115200;
    long DATABITS = CS8;
    long STOPBITS = 0;      // STOPBITS = CSTOPB;
    long PARITYON = 0;      // PARITYON = PARENB;
    long PARITY = 0;             // PARITY = PARODD;
    
    unsigned int portNum = 4000;
    sprintf(devicename, "/dev/ttyUSB0");
 
    int opt;
    while ((opt = getopt (argc, argv, "hdc:p:")) != -1) {
        switch (opt) {
            case 'h':
                print_usage();
                break;
            case 'd':
                debug = 1;
                break;
            case 'c':
                strcpy(&devicename[0],optarg);
                break;
            case 'p':
                portNum = atoi(optarg);
                break;
            case ':':
                fprintf(stderr, "Option -%c requires an operand\n", optopt);
                break;
           case '?':
                fprintf (stderr, "Unknown option `-%c'.\n", optopt);
                return 1;
        }
    }

    // open the device to be non-blocking (read will return immediately)
    fd = open (devicename, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd < 0) {
        perror (devicename);
        exit (-1);
    }

    if(debug) {
        printf ("opened: %s\n", devicename);
    }

    // save current port setting
    tcgetattr (fd, &oldtio);

    // set new port settings for canonical input processing
    newtio.c_cflag =  BAUD | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;
    newtio.c_lflag = 0;         //ICANON;
    newtio.c_cc[VMIN] = 1;
    newtio.c_cc[VTIME] = 0;
    tcflush (fd, TCIFLUSH);
    tcsetattr (fd, TCSANOW, &newtio);

    server_open(portNum);
    start_flag = 0;
    while (1) {
        server_non_blocking_rx(fd);
        res = read (fd, &c, 1);
        if (res > 0) {
            if (c == START) {
                mode = slip;
            }
            if (mode == slip) {
                slip_rx (fd);
                mode = ascii;
            }
            if (mode == ascii) {
                if(debug) printf ("%c", c);
            }
        } else {
            usleep(10000);
        }
    }
}
Esempio n. 9
0
static void SftpGW(PCStr(host),int port,int gw){
	int tofrom_sftp[2];
	FILE *fc;
	FILE *tc;
	FILE *ts;
	FILE *fs;
	int rcc;
	CStr(req,1024);
	CStr(com,1024);
	const unsigned char *ucom = (const unsigned char*)com;
	CStr(arg,1024);
	CStr(scom,1024);
	CStr(user,128);
	CStr(passMD5,128);
	CStr(md5,1024);
	CStr(logindir,1024);
	CStr(rnfr,512);
	CStr(res,1024);
	CStr(xcom,1024);
	const char *dp;
	int vsock = -1;
	int dsock = -1;
	CStr(fifo,1024);
	CStr(sresp,0x10000);
	CStr(path,1024);
	CStr(resp1,1024);
	int Ok;
	int Bad;
	int xpid;
	int nready;
	int nfc;
	FILE *fpv[2];
	int rdv[2];
	int ncc = 0;
	int leng;

	FileSize datamax = DATA_MAX;
	IStr(opt1,128);
	if( getMountOpt1(MainConn(),"datamax",AVStr(opt1),sizeof(opt1)) ){
		datamax = kmxatoi(opt1);
		sv1log("## datamax=%s 0x%llX\n",opt1,datamax);
	}

	DEBUG("--SFTPGW start\n");
	fc = fdopen(gw,"r");
	tc = fdopen(gw,"w");
	putresp(tc,220,"SFTP/FTP gateway ready.");
	fflush(tc);
	ts = NULL;
	fs = NULL;

	logindir[0] = 0;
	fpv[0] = fc;
	nfc = 1;
	for(;;){
		nready = fPollIns(0,nfc,fpv,rdv);
		if( nready == 0 && errno == EINTR ){
			DEBUG("--SFTPGW ignored EINTR\n");
			sleep(1);
			continue;
		}
		if( nready <= 0 ){
			break;
		}
		if( 1 < nfc && 0 < rdv[1] ){
			DEBUG("--SFTPGW EOF from server?\n");
			relay_resp(fs,-1,0,AVStr(sresp),"",1);
			break;
		}

		fflush(tc);
		if( fgets(req,sizeof(req),fc) == 0 )
			break;
		dp = wordScan(req,com);
		if( *dp == ' ' ){
			textScan(dp+1,arg);
		}else
		lineScan(dp,arg);
		if( strcaseeq(com,"PASS") )
			DEBUG("--SFTPGW << [%s][****]\n",com);
		else	DEBUG("--SFTPGW << [%s][%s]\n",com,arg);

		if( strcaseeq(com,"QUIT") ){
			putresp(tc,221,"Ok Bye.");
			fclose(fc);
			fclose(tc);
			fc = 0;
			tc = 0;
			if( fs == NULL ){
				DEBUG("--SFTPGW DONE (not started)\n");
				break;
			}
			gw = CC_accept("sftp",host,port,user,fileno(fs));
			if( 0 <= gw ){
				putsftp(ts,"cd .","");
				relay_resp(fs,-1,0,AVStr(sresp),"restart",1);
				if( sresp[0] == 0 ){
					sv1log("##sftp_CC NotAlive\n");
					break;
				}
				fc = fdopen(gw,"r");
				fpv[0] = fc;
				tc = fdopen(gw,"w");
				ncc++;
				DEBUG("--SFTPGW SFTPCC restart #%d\n",ncc);
				putresp(tc,220,"Ok (reusing)");
				continue;
			}
			DEBUG("--SFTPGW DONE\n");
			break;
		}else
		if( strcaseeq(com,"NOOP") ){
			putresp(tc,200,"Ok");
		}else
		if( strcaseeq(com,"USER") ){
			strcpy(user,arg);
			putresp(tc,331,"Send password or passphrase for '%s'",
				arg);
		}else
		if( strcaseeq(com,"PASS") ){
			if( ts != NULL ){
				toMD5(arg,md5);
				DEBUG("--SFTP reusing user[%s]pass[%s][%s]\n",
					user,passMD5,md5);
				if( !streq(md5,passMD5) ){
					putresp(tc,530,"No");
					continue;
				}else	putresp(tc,230,"Ok");
				putsftp(ts,"cd %s",logindir);
				relay_resp(fs,-1,0,AVStr(sresp),"restart",1);
				continue;
			}
			/*
			if( forkSftp(host,port,user,arg,tofrom_sftp) != 0 ){
			*/
			if( forkSftp(host,port,user,arg,tofrom_sftp,AVStr(sresp)) != 0 ){
				IStr(prompt,1024);
				lineScan(sresp,prompt);
				DEBUG("--SFTP login failed\n");
				/*
				putresp(tc,530,"No (Login failed)");
				*/
				putresp(tc,530,"No (Login failed:'%s')",prompt);
if( lGATEWAY() )
sv1log("####@@@@ LOGIN FAILURE\n");
continue; /* to return normal resp. for following commands... */
				break;
			}
			toMD5(arg,passMD5);
			fs = fdopen(tofrom_sftp[0],"r");
			ts = fdopen(tofrom_sftp[1],"w");
			fpv[1] = fs;
			nfc = 2;
			putresp(tc,230,"Ok");

			putsftp(ts,"pwd");
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			/*
			if( strneq(sresp,"Remote working directory: ",26) ){
				CStr(path,1024);
				lineScan(sresp+26,path);
			*/
			if( scanresp(sresp,"Remote working directory:",
			    AVStr(path),sizeof(path)) ){
				strcpy(logindir,path);
			}
		}else
		if( strcaseeq(com,"TYPE") ){
			putresp(tc,200,"Ok");
		}else
		if( strcaseeq(com,"PASV") ){
			PASV(tc,&vsock);
#if 0
			VSAddr ba;
			int balen;
			CStr(mport,128);
			vsock = server_open("SftpGW",VStrNULL,0,1);
			if( 0 <= vsock ){
				balen = sizeof(ba);
				getsockname(vsock,(SAP)&ba,&balen);
#if defined(__CYGWIN__)
				if( VSA_addrisANY(&ba) ){
				    /*connection to 0.0.0.0 fails on CYGWIN?*/
				    VSA_atosa(&ba,VSA_port(&ba),"127.0.0.1");
				}
#endif
				VSA_prftp(&ba,AVStr(mport));
			putresp(tc,227,"Enterning Passive Mode (%s)",mport);
			}else{
				putresp(tc,500,"No");
			}
#endif
		}else
		if( ts == NULL ){
			sv1log("Not Logged In: %s",req);
			putresp(tc,530,"Please login with USER and PASS.");
		}else
		if( strcaseeq(com,"PWD") ){
			putsftp(ts,"pwd");
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			/*
			if( strneq(sresp,"Remote working directory: ",26) ){
				CStr(path,1024);
				lineScan(sresp+26,path);
			*/
			if( scanresp(sresp,"Remote working directory:",
			    AVStr(path),sizeof(path)) ){
				putresp(tc,257,"\"%s\"",path);
			}else{
				putresp(tc,257,"\"/\"");
			}
		}else
		if( strcaseeq(com,"CWD") ){
			putsftp(ts,"cd %s",arg);
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			/*
			if( strneq(sresp,"Couldn't",8)
			 || strneq(sresp,"Can't",4) ){
			*/
			if( linehead(sresp,"Couldn't",0)
			 || linehead(sresp,"Can't",0) ){
				if( strstr(sresp,BadPath) )
					putresp(tc,550,BadPath);
				else
				putresp(tc,550,"No");
			}else	putresp(tc,250,"Ok");
		}else
		/*
		if( strcaseeq(com,"SIZE") ){
			putsftp(ts,"ls -ld %s",arg);
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			if( *sresp == '-' ){
				int sz = 0;
				sscanf(sresp,"%*s %*s %*s %*s %d",&sz);
				putresp(tc,213,"%d",sz);
			}else{
				putresp(tc,550,"Not a plain file");
			}
		}else
		*/
		if( strcaseeq(com,"STOR") ){
			if( vsock < 0 ){
				putresp(tc,500,"No");
				continue;
			}
			dsock = ACCEPT(vsock,1,-1,10);
			if( 0 <= dsock ){
				CStr(tmpf,1024);
				FILE *dfp;
				FILE *tmp;
				/*
				int bytes;
				*/
				FileSize Bytes;
				int isbin;
				double St;

				dfp = fdopen(dsock,"r");
				if( dfp == NULL ){
					putresp(tc,500,"No-1");
					continue;
				}
				tmp = getfile(AVStr(tmpf),"w",0);
				if( tmp == NULL ){
					putresp(tc,500,"No-2");
					fclose(dfp);
					continue;
				}
				putresp(tc,150,"Ok");
				St = Time();
				/*
				bytes = file_copy(dfp,tmp,NULL,DATA_MAX,&isbin);
				DEBUG("--SFTPGW bin=%d,%d bytes upload\n",
					isbin,bytes);
				*/
				Bytes = file_copy(dfp,tmp,NULL,datamax,&isbin);
				DEBUG("--SFTPGW bin=%d,%lld bytes upload\n",
					isbin,Bytes);
				fclose(tmp);
				fclose(dfp);

				DEBUG("--SFTPGW put %s (%lld %lld)\n",tmpf,
					Bytes,File_sizeX(tmpf));
				putsftp(ts,"put %s %s",tmpf,arg);
				/*
				relay_resp(fs,-1,15*1000,AVStr(sresp),com,1);
				*/
				relay_resp(fs,-1,5*1000,AVStr(sresp),com,1);

				if( strneq(sresp,"Uploading ",10)
				 && strstr(sresp,"sftp>") == 0 ){
					waitUploaded(com,AVStr(sresp),fs,fc,tc,
						Time()-St,&vsock);
				}else
				if( strncmp(sresp,"Could",5) == 0 )
					putresp(tc,550,"No");
				else	putresp(tc,226,"Ok");
				unlink(tmpf);
				dsock = -1;
			}else{
				putresp(tc,500,"accept error");
			}
			vsock = -1;
		}else
		if( strcaseeq(com,"RETR") ){
			if( vsock < 0 ){
				putresp(tc,500,"No");
				continue;
			}
			dsock = ACCEPT(vsock,1,-1,10);
			if( arg[0]==0 ||streq(arg,".") ||strtailstr(arg,"/") ){
				putresp(tc,550,"RETR for dir [%s]",arg);
				if( 0 <= dsock ){
					close(dsock);
					dsock = -1;
				}
			}else
			if( 0 <= dsock ){
				CStr(rpath,1024);
				FILE *rfp;
				int pid;

				truncVStr(rpath);
				getfile(AVStr(fifo),NULL,1);
				if( SFTP_WITH_SEEK ){
					/* newer sftp with output seeking */
					sprintf(rpath,"%sr",fifo);
					rfp = fopen(rpath,"w+");
					if( rfp ){
					  pid = Fork("SFTP-DATA");
					  if( pid == 0 ){
						/*
						relayFile2Fifo(rfp,rpath,fifo);
						*/
						relayFile2Fifo(fs,rfp,rpath,fifo);
						_exit(0);
					  }
					  else{
						fclose(rfp); /* 9.9.8 */
					  }
					}
					putsftp(ts,"get %s %s",arg,rpath);
				}else{
				putsftp(ts,"get %s %s",arg,fifo);
				}
				/*
				if( relay_fifo(fs,tc,fifo,dsock,com)==0 )
				*/
				leng = relay_fifo(fs,tc,fifo,dsock,com,AVStr(sresp));
				if( leng <= 0 ){
					sv1log("RETR ERROR: %s\n",sresp);
				}
				if( leng == 0 && strstr(sresp,BadPath) )
					putresp(tc,550,BadPath);
				else
				if( 0 < leng )
					putresp(tc,226,"Ok");
				else	putresp(tc,550,"No");
				relay_resp(fs,-1,1,AVStr(sresp),com,1);
				if( rpath[0] ){
					unlink(rpath);
					xpid = NoHangWait();
					DEBUG("--SFTP-DATA finished, pid=%d\n",
						xpid);
				}
				close(dsock);
				dsock = -1;
				unlink(fifo);
			}else{
				putresp(tc,500,"accept error");
			}
			if( 0 <= vsock ){
				close(vsock); /* 9.9.8 */
			}
			vsock = -1;
		}else
		if( strcaseeq(com,"NLST") || strcaseeq(com,"LIST") ){
			if( vsock < 0 ){
				putresp(tc,500,"No");
				continue;
			}
			dsock = ACCEPT(vsock,1,-1,10);
			if( 0 <= dsock ){
				putresp(tc,150,"Ok");
				if( arg[0] == '-' ){
					char *op;
					for( op = arg+1; *op; ){
						if( strchr(" \t\r\n",*op) )
							break;
						if( strchr("L",*op) ){
							ovstrcpy(op,op+1);
						}else	op++;
					}
				}
				/*
				if( streq(com,"NLST") || strstr(arg,"-l") )
					putsftp(ts,"ls %s",arg);
				else	putsftp(ts,"ls -l %s",arg);
				relay_resp(fs,dsock,0,VStrNULL,com,0);
				*/
				if( streq(com,"NLST") || strstr(arg,"-l") )
					sprintf(scom,"ls %s",arg);
				else	sprintf(scom,"ls -l %s",arg);
				putsftp(ts,"%s",scom);
				relay_list(fs,dsock,scom);
				close(dsock);
				dsock = -1;
				putresp(tc,226,"Ok");
			}else{
				putresp(tc,500,"accept error");
			}
			vsock = -1;
		}else
		if( ucom[0]==0xFF && ucom[1]==0xF4 /* IAC+IP */
		 && ucom[2]==0xF2 /* SYNC */
		 && strcaseeq(com+3,"ABOR") ){
			sv1log("--SFTPGW ABOR\n");
		}else
		if( strcaseeq(com,"RNFR") ){
			strcpy(rnfr,arg);
			putresp(tc,350,"Ok");
		}else
		if( strcaseeq(com,"RNTO") ){
			putsftp(ts,"rename %s %s",rnfr,arg);
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			if( dp = strstr(sresp,"Couldn't") ){
				lineScan(dp,resp1);
				putresp(tc,550,"No %s",resp1);
			}else	putresp(tc,250,"Ok");
		}else
		if( strcaseeq(com,"MKD") || strcaseeq(com,"RMD")
		 || strcaseeq(com,"DELE")
		){ 
			Bad = 550;
			if( strcaseeq(com,"MKD") ){
				Ok = 257;
				putsftp(ts,"mkdir %s",arg);
			}else
			if( strcaseeq(com,"RMD") ){
				Ok = 250;
				putsftp(ts,"rmdir %s",arg);
			}else{
				Ok = 250;
				putsftp(ts,"rm %s",arg);
			}
			relay_resp(fs,-1,0,AVStr(sresp),com,1);
			if( dp = strstr(sresp,"Couldn't") ){
				lineScan(dp,resp1);
				putresp(tc,Bad,"No %s",resp1);
			}else	putresp(tc,Ok,"Ok");
		}else
		{
			putresp(tc,502,"No not supported");
		}
	}
	if( fs != NULL && !feof(fs) ){
		putsftp(ts,"quit");
		relay_resp(fs,-1,0,AVStr(sresp),com,1);
	}
	xpid = NoHangWait();
	DEBUG("--SFTPGW finished, pid=%d\n",xpid);
}
Esempio n. 10
0
int main(int argc, char *const argv[]) {
	int error = 0;
	
	log_debug("Parsing options");
	Options *opts = parse_opt(argc, argv);
	if (!opts) {
		show_banner();
		show_help();
		return -1;
	}
	log_set_level(opts->loglevel);
	if (opts->logfile) {
		log_set_logfile(opts->logfile);
		log_set_logfile_level(LOG_LEVEL_MAX);
	}
#ifdef HAVE_VSYSLOG
	if (opts->syslog) {
		log_set_syslog("daliserver");
	}
#endif
	if (opts->background) {
		daemonize(opts->pidfile);
	} else {
		show_banner();
	}

	log_info("Starting daliserver");

	log_debug("Initializing dispatch queue");
	DispatchPtr dispatch = dispatch_new();
	if (!dispatch) {
		error = -1;
	} else {
		//dispatch_set_timeout(dispatch, 100);

		UsbDaliPtr usb = NULL;
		if (!opts->dryrun) {
			log_debug("Initializing USB connection");
			usb = usbdali_open(NULL, dispatch, opts->usbbus, opts->usbdev);
			if (!usb) {
				error = -1;
			}
		}

		if (opts->dryrun || usb) {
			log_debug("Initializing server");
			ServerPtr server = server_open(dispatch, opts->address, opts->port, DEFAULT_NET_FRAMESIZE, net_frame_handler, usb);

			if (!server) {
				error = -1;
			} else {
				server_set_connection_destroy_callback(server, net_dequeue_connection, usb);
				
				if (usb) {
					usbdali_set_outband_callback(usb, dali_outband_handler, server);
					usbdali_set_inband_callback(usb, dali_inband_handler);
				}

				log_debug("Creating shutdown notifier");
				killsocket = ipc_new();
				
				if (!killsocket) {
					error = -1;
				} else {
					ipc_register(killsocket, dispatch);

					log_info("Server ready, waiting for events");
					running = 1;
					signal(SIGTERM, signal_handler);
					signal(SIGINT, signal_handler);
					while (running && dispatch_run(dispatch, usbdali_get_timeout(usb)));

					log_info("Shutting daliserver down");
					ipc_free(killsocket);
				}
				
				server_close(server);
			}
			
			if (usb) {
				usbdali_close(usb);
			}
		}

		dispatch_free(dispatch);
	}

	free_opt(opts);
	
	log_info("Exiting");
	return error;
}
Esempio n. 11
0
static UDP_Assoc *newUA(Connection *Conn,UDP_Assoc *uav[],PCStr(clhost),int clport,PCStr(svhost),int svport)
{	int ux;
	UDP_Assoc *ua;
	int svsock;
	int rcode;
	CStr(msg,128);
	CStr(lhost,256);
	int lport;
	CStr(local,256);
	CStr(remote,256);
	int SOCKSctl = -1;
	CStr(rh,256);
	int rp;

	rcode = -1;
	if( !permitted(clhost,clport,svhost,svport) )
		return NULL;

	sprintf(local,"*:*");
	sprintf(remote,"%s:%d",svhost,svport);
	Conn->from_cached = 1;
	VA_setClientAddr(Conn,clhost,clport,0);
	Conn->no_dstcheck_proto = serviceport("tcprelay");
	initConnect(Conn);
	setupConnect(Conn);

	ServerFlags |= PF_UDP;
	Conn->sv.p_SOCKSCTL = -1;
	svsock = connectViaSocks(Conn,svhost,svport,AVStr(rh),&rp);
	if( 0 <= svsock ){
		sv1log("via SOCKS UDP:%d@%s CTL:%d\n",svsock,
			Conn->sv.p_SOCKSADDR,Conn->sv.p_SOCKSCTL);
		SOCKSctl = Conn->sv.p_SOCKSCTL;
		goto ADDUA;
	}

	svsock = VSocket(Conn,"CNCT/UDPRELAY",-1,AVStr(local),AVStr(remote),"");
	if( 0 <= svsock ){
/*
		setNonblockingIO("UDPRELAY-SV",svsock,1);
*/
		SetNonblockingIO("UDPRELAY-SV",svsock,1);
		goto ADDUA;
	}

	strcpy(lhost,"*");
	lport = 0;
	SRCIFfor(Conn,"udprelay",svhost,svport,AVStr(lhost),&lport);
	if( strcmp(lhost,"*") == 0 )
		lhost[0] = 0;

	svsock = server_open("UDPRELAY",AVStr(lhost),lport,-1);
	if( svsock < 0 ){
		if( uav[0] == 0 ){
			return NULL;
		}
		ux = longestIdle(uav);
		sv1log("push out longest idle 1 [%d]\n",ux);
		delUA(uav,ux,"NoMoreSocket",1);
		svsock = server_open("UDPRELAY",AVStr(lhost),lport,-1);
		if( svsock < 0 )
			return NULL;
	}

	if( UDPRELAY_RPORT_FIX ){
	rcode = __connectServer(svsock,"UDPRELAY","udprelay",svhost,svport /*,1*/);
	if( rcode < 0 ){
		sv1log("UDPRELAY: connect(%d) error %d\n",svsock,rcode);
		close(svsock);
		return NULL;
	}
	}

ADDUA:
	for( ux = 0; uav[ux]; ux++ )
		;
	if( UDPRELAY_MAXASSOC <= ux ){
		ux = longestIdle(uav);
		sv1log("push out longest idle 2 [%d]\n",ux);
		delUA(uav,ux,"NoMoreClient",0);
	}

	ua = (UDP_Assoc*)calloc(1,sizeof(UDP_Assoc));
	ua->ua_id = ++uaid;
	ua->ua_ctime = time(0);
	ua->ua_clhost = stralloc(clhost);
	ua->ua_clport = clport;
	ua->ua_svsock = svsock;
	ua->ua_svbound = (0 < peerPort(svsock));
	ua->ua_svtcp = !isUDPsock(svsock);
	ua->ua_svhost = stralloc(svhost);
	ua->ua_svport = svport;
	ua->ua_svSOCKS = SOCKSctl;
	VSA_aptosa(&ua->ua_SOCKSADDR,Conn->sv.p_SOCKSADDR);
	uav[ux] = ua;

	msghead(AVStr(msg),"start",ua,ux);
	sv1log("%s > %s:%d\n",msg,svhost,svport);
	return ua;
}