ConnectWindow::ConnectWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ConnectWindow)
{
    ui->setupUi(this);
    this->setFixedSize(this->width(), this->height());
    ui->address_line->setPlaceholderText("Address");
    ui->port_line->setPlaceholderText("Port");
    ui->username_line->setPlaceholderText("Username");
    ui->address_line->setFocus();

    connect(ui->username_line, SIGNAL(returnPressed()), this, SLOT(ConnectToHost()));
    connect(ui->connectButton, SIGNAL(clicked()), this, SLOT(ConnectToHost()));
    ui->port_line->setValidator(new QIntValidator(0, 65535));
}
Beispiel #2
0
// Init connect screen
void _Menu::InitConnect(bool UseConfig, bool ConnectNow) {
	PlayState.Network->Disconnect();

	ChangeLayout("element_menu_connect");

	_TextBox *Host = Assets.TextBoxes["textbox_connect_host"];
	if(UseConfig)
		Host->SetText(Config.LastHost);

	_TextBox *Port = Assets.TextBoxes["textbox_connect_port"];
	if(UseConfig)
		Port->SetText(Config.LastPort);

	_Label *Label = Assets.Labels["label_menu_connect_message"];
	Label->Color = COLOR_WHITE;
	Label->Text = "";

	_Button *Button = Assets.Buttons["button_connect_connect"];
	((_Label *)Button->Children.front())->Text = "Connect";

	// Set focus
	FocusedElement = Host;
	Host->ResetCursor();

	State = STATE_CONNECT;
	if(ConnectNow)
		ConnectToHost();
}
/*
** Returns 1 or 0 depending on whether or not the host described by #host# can
** be verified to be name server within #timeOut# seconds.
*/
static int
IsANameServer(const struct host_desc *host,
              double timeOut) {

  struct host_cookie hostCookie;
  HostInfo hostInfo;
  char hostName[127 + 1];

  SAFESTRCPY(hostName, HostDImage(host));
  MakeHostCookie(host->host_name, host->port, &hostCookie);

  if(!ConnectToHost(&hostCookie, &hostCookie.sd)) {
    FAIL1("IsANameServer: unable to contact %s\n", hostName);
  }

  if(DoTestHost(hostCookie.sd, &hostInfo, timeOut) != HEALTHY) {
    DisconnectHost(&hostCookie);
    FAIL1("IsANameServer: unable to verify that %s is a name server\n",
          hostName);
  }

  DisconnectHost(&hostCookie);

  if(strcmp(hostName, hostInfo.nameServer) != 0) {
    FAIL1("IsANameServer: %s is not a name server\n", hostName);
  }

  return(1);

}
Beispiel #4
0
void TcpClient::ExampleRun()
{
	const std::string host = "127.0.0.1";
	int port = 666;

	ConnectToHost(host, port);
	ShowEndpointInfos();
	_isRunning = true;

	while (_isRunning)
	{
		std::string request;
		
		std::cout << "Enter request: ";
		getline(std::cin, request);
		
		if (request == "END")
			_isRunning = false;
		else if (request == "")
			request = "HELLO-HOW-SHOULD-I-WORK";

		SendHttpRequest(host, request);

		WaitForResponse();
		
		ReceiveResponse(true);

		//DisplayResults();
		//_isRunning = false;
	}
	
	CloseConnection();
}
Beispiel #5
0
int DoHTTPProxyTunnel(STREAM *S, const char *Host, int Port, const char *Destination, int Flags)
{
char *Tempstr=NULL, *Token=NULL;
const char *ptr=NULL;
int result=FALSE;

	S->in_fd=ConnectToHost(Host,Port,0); 
	S->out_fd=S->in_fd;
	if (S->in_fd == -1) return(FALSE);

	ptr=Destination;
	if (strncmp(ptr,"tcp:",4)==0) ptr+=4;
	Tempstr=FormatStr(Tempstr,"CONNECT %s HTTP/1.1\r\n\r\n",ptr);

	STREAMWriteLine(Tempstr,S);
	STREAMFlush(S);
	
	Tempstr=STREAMReadLine(Tempstr,S);
	StripTrailingWhitespace(Tempstr);

	ptr=GetToken(Tempstr," ",&Token,0);
	ptr=GetToken(ptr," ",&Token,0);

	if (*Token=='2') result=TRUE;
	while (StrLen(Tempstr))
	{
		Tempstr=STREAMReadLine(Tempstr,S);
		StripTrailingWhitespace(Tempstr);
	}

DestroyString(Tempstr);
DestroyString(Token);

return(result);
}
Beispiel #6
0
Client::Client(const char *host, int portNum)
{
  OpenSocket();
  ConnectToHost(host, portNum);
  
  SendMsg(NetMsg(Ok, 23));
  GetResponse();

  Disconnect();
}
Beispiel #7
0
int ConnectHopSocks(STREAM *S, int Type, const char *Host, int Port, const char *User, const char *Pass, const char *Path)
{
char *Tempstr=NULL;
uint8_t *ptr;
char *Token=NULL;
const char *tptr;
int result, RetVal=FALSE;

S->in_fd=ConnectToHost(Host,Port,0); 
S->out_fd=S->in_fd;
if (S->in_fd == -1) return(FALSE);


//Horrid binary protocol. 
Tempstr=SetStrLen(Tempstr, StrLen(User) +20);
ptr=Tempstr;
*ptr=4; //version number
ptr++;
*ptr=1; //outward connection (2 binds a port for incoming)
ptr++;

tptr=Path;
if (strncmp(tptr,"tcp:",4)==0) tptr+=4;
tptr=GetToken(tptr,":",&Token,0);

//destination port
*((uint16_t *) ptr) =htons(atoi(tptr));
ptr+=2;

//destination host
*((uint32_t *) ptr) =StrtoIP(Token);
ptr+=4;

strcpy(ptr,User);
ptr+=StrLen(User);
ptr++;
STREAMWriteBytes(S,Tempstr,(char *)ptr-Tempstr); STREAMFlush(S);
result=STREAMReadBytes(S,Tempstr,8);

//Positive response will be 0x00 0x5a 0x00 0x00 0x00 0x00 0x00 0x00
//although only the leading two bytes (0x00 0x5a, or \0Z) matters
if ((result==8) && (Tempstr[0]=='\0') && (Tempstr[1]=='Z')) RetVal=TRUE;


DestroyString(Tempstr);
DestroyString(Token);

return(RetVal);
}
Beispiel #8
0
void Server::Connect()
{
    if(mainSocket != NULL)
    {
        Disconnect();
        free(mainSocket);
        mainSocket = NULL;
    }
    mainSocket = new QTcpSocket(this);
    connect(mainSocket, SIGNAL(connected ()), this, SLOT(ConnectedToHost()));
    connect(mainSocket, SIGNAL(disconnected ()), this, SLOT(DisconnectedFromHost()));
    connect(mainSocket, SIGNAL(error( QAbstractSocket::SocketError )), this, SLOT(SocketError( QAbstractSocket::SocketError )));
    connect(mainSocket, SIGNAL(stateChanged ( QAbstractSocket::SocketState )), this, SLOT(SocketStateChanged ( QAbstractSocket::SocketState )));
    ConnectToHost();
}
Beispiel #9
0
int ProxyControlConnect(TSession *Session, char *Host, int Port)
{
char *Tempstr=NULL;
int fd, result=FALSE;

if (StrLen(Host)==0) 
{
	SendLoggedLine(Session,"421 ERROR: Proxy cannot connect. No destination host.");
}
else 
{
Tempstr=IPCRequest(Tempstr, Session, "GetIP", Host);

   if (strcmp(Tempstr,"DENIED")==0)
   {
      Tempstr=FormatStr(Tempstr,"421 ERROR: Proxy connection denied for host %s:%d",Host,Port);
      SendLoggedLine(Session,Tempstr);

   }
   else
  {
      fd=ConnectToHost(Tempstr,Port,FALSE);
      if (fd==-1)
      {
      	Tempstr=FormatStr(Tempstr,"421 ERROR: Proxy cannot connect to host %s:%d",Host,Port);
        SendLoggedLine(Session,Tempstr);
      }
			else
			{
     	 Session->ProxySock=STREAMFromFD(fd);
     	 result=TRUE;
     	 do
     	 {
     	  Tempstr=STREAMReadLine(Tempstr,Session->ProxySock);
     	  STREAMWriteLine(Tempstr,Session->ClientSock);
     	 } while ( (Tempstr[3]=='-') || (isspace(Tempstr[0])) );
			STREAMFlush(Session->ClientSock);
			}
  }
}

DestroyString(Tempstr);
return(result);
}
Beispiel #10
0
Client::Client(const string& newName, const string& ipaddress, int port)
{
	if(ConnectToHost(port,ipaddress.length()<=1?"127.0.0.1":ipaddress.c_str())){
		success=true;
		string welcomeMsg;
		if(receiveText(welcomeMsg)){
			stringstream ss("");
			ss<<"Client connected to: "<<welcomeMsg<<" ,IP: "<<ipaddress<<" [port: "<<port<<"]";
			wiBackLog::post(ss.str().c_str());
			changeName(newName);
			serverName=welcomeMsg;
		}
	}
	else{
		success=false;
		stringstream ss("");
		ss<<"Connecting to server on address: "<<ipaddress<< " [port "<<port<<"] FAILED with: "<<WSAGetLastError();
		wiBackLog::post(ss.str().c_str());
	}
}
Beispiel #11
0
/* Main ========================================================= */
int main(int argc, char **argv) 
{
	int argSwitch = 0;
	char *hostname = "localhost";
	char *portno = "8888";
	char *fileName = "foo.txt";

	// Parse and set command line arguments
	while ((argSwitch = getopt(argc, argv, "s:p:o:h")) != -1) 
	{
		switch (argSwitch) 
		{
			case 's': // server
				hostname = optarg;
				break; 
			case 'p': // listen-port
				portno = optarg;
				break;                                        
			case 'o': // output file name
				fileName = optarg;
				break;    
			case 'h': // help
				fprintf(stdout, "%s", USAGE);
				exit(0);
				break;       
			default:
				fprintf(stderr, "%s", USAGE);
				exit(1);
		}
	}

	int socketDescriptor = ConnectToHost(hostname, portno);

	ReadSocketToFile(socketDescriptor, fileName);

    close(socketDescriptor);

    return 0;
}
Beispiel #12
0
int STREAMProcessConnectHop(STREAM *S, char *HopURL, int LastHop)
{
int val, result=FALSE;
char *Token=NULL, *Token2=NULL;
char *Tempstr=NULL;
char *User=NULL, *Host=NULL,*Pass=NULL, *KeyFile=NULL;
int Port=0;

ParseConnectDetails(HopURL, &Token, &Host, &Token2, &User, &Pass, NULL);

Port=atoi(Token2);

val=MatchTokenFromList(Token,HopTypes,0);
switch (val)
{
	case CONNECT_HOP_TCP:
		if (S->in_fd==-1)
		{
			S->in_fd=ConnectToHost(Host,Port,0); 
			S->out_fd=S->in_fd;
			if (S->in_fd > -1) result=TRUE;
		}
		break;

	case CONNECT_HOP_HTTPTUNNEL:
		result=DoHTTPProxyTunnel(S, Host, Port, S->Path, 0);
	break;	

	case CONNECT_HOP_SSH:
	case CONNECT_HOP_SSHTUNNEL:
		result=ConnectHopSSH(S, val, Host, Port, User, Pass, S->Path);
	break;

	case CONNECT_HOP_SOCKS4:
		result=ConnectHopSocks(S, val, Host, Port, User, Pass, S->Path);
	break;

	case CONNECT_HOP_SHELL_CMD:
	break;

	case CONNECT_HOP_TELNET:
		if (Port > 0)
		{
		Tempstr=FormatStr(Tempstr,"telnet -8 %s %d ",Host, Port);
		}
		else Tempstr=FormatStr(Tempstr,"telnet -8 %s ",Host);

		if (S->in_fd==-1) 
		{
			PseudoTTYSpawn(& S->in_fd,Tempstr,0);
		        S->out_fd=S->in_fd;
			if (S->in_fd > -1)
			{
				result=TRUE;
				STREAMSetFlushType(S,FLUSH_LINE,0,0);
			}

		}
		else 
		{
			Tempstr=CatStr(Tempstr,";exit\n");
			STREAMWriteLine(Tempstr,S);
			result=TRUE;
		}
		if (StrLen(User) > 0) 
		{
			Tempstr=MCopyStr(Tempstr,User,"\n",NULL);
			STREAMExpectAndReply(S,"ogin:",Tempstr);
		}
		if (StrLen(Pass) > 0) 
		{
			Tempstr=MCopyStr(Tempstr,Pass,"\n",NULL);
			STREAMExpectAndReply(S,"assword:",Tempstr);
		}
		STREAMExpectSilence(S,2);
		break;


}

DestroyString(Tempstr);
DestroyString(Token);
DestroyString(KeyFile);
DestroyString(Host);
DestroyString(User);
DestroyString(Pass);

STREAMFlush(S);
return(result);
}
Beispiel #13
0
int ConnectHopSSH(STREAM *S,int Type, char *Host, int Port, char *User, char *Pass, char *NextHop)
{
char *Tempstr=NULL, *KeyFile=NULL, *Token=NULL, *Token2=NULL;
STREAM *AuthS;
int result=FALSE, val;
unsigned int TunnelPort=0;

if (Type==CONNECT_HOP_SSHTUNNEL) 
{
	TunnelPort=(rand() % (0xFFFF - 9000)) +9000;
	//Host will be Token, and port Token2
	ParseConnectDetails(NextHop, NULL, &Token, &Token2, NULL, NULL, NULL);
	Tempstr=FormatStr(Tempstr,"ssh -2 -N %s@%s  -L %d:%s:%s ",User,Host,TunnelPort,Token,Token2);

}
else Tempstr=MCopyStr(Tempstr,"ssh -2 -T ",User,"@",Host, " ", NULL );

if (strncmp(Pass,"keyfile:",8)==0)
{

		if (S->in_fd != -1)
		{
			Token=FormatStr(Token,".%d-%d",getpid(),time(NULL));
			SendPublicKeyToRemote(S,Token,Pass+8);
			KeyFile=CopyStr(KeyFile,Token);
		}
		Tempstr=MCatStr(Tempstr,"-i ",KeyFile," ",NULL);
		}

		if (Port > 0)
		{
		Token=FormatStr(Token," -p %d ",Port);
		Tempstr=CatStr(Tempstr,Token);
		}

		if (Type==CONNECT_HOP_SSHTUNNEL) 
		{
			Tempstr=CatStr(Tempstr, " 2> /dev/null");
			AuthS=STREAMSpawnCommand(Tempstr,COMMS_BY_PTY);
			STREAMSetValue(S,"HelperPID:SSH",STREAMGetValue(AuthS,"PeerPID"));
		}
		else if (S->in_fd==-1) 
		{
			Tempstr=CatStr(Tempstr, " 2> /dev/null");
			PseudoTTYSpawn(&S->in_fd,Tempstr,0);
			S->out_fd=S->in_fd;
			if (S->in_fd > -1)
			{
				result=TRUE;
				STREAMSetFlushType(S,FLUSH_LINE,0,0);
			}
			AuthS=S;
		}
		else 
		{
			if (StrLen(KeyFile)) Tempstr=MCatStr(Tempstr," ; rm -f ",KeyFile,NULL);
			Tempstr=CatStr(Tempstr,"; exit\n");
			STREAMWriteLine(Tempstr,S);
			result=TRUE;
			AuthS=S;
		}

		if ((StrLen(KeyFile)==0) && (StrLen(Pass) > 0)) 
		{
			Token=MCopyStr(Token,Pass,"\n",NULL);
			for (val=0; val < 3; val++)
			{
			if (STREAMExpectAndReply(AuthS,"assword:",Token)) break;
			}
		}
		STREAMSetTimeout(AuthS,100);
		//STREAMExpectSilence(AuthS);
		sleep(3);

		if (Type==CONNECT_HOP_SSHTUNNEL) 
		{
			S->in_fd=ConnectToHost("127.0.0.1",TunnelPort,0);
			S->out_fd=S->in_fd;
			if (S->in_fd > -1) result=TRUE;
		}


DestroyString(Tempstr);
DestroyString(KeyFile);
DestroyString(Token2);
DestroyString(Token);

return(result);
}
int
main(int argc,
     char *argv[]) {

  typedef enum {STOP,START} Commands;
  
  const char *LOGDEST[]={"none","local","netlogger","remote"};
  const char *USAGE = "ctrl_mem [-l howtolog -f wheretolog] host";

  MemLogDest logdest = MEMORY_LOG_NONE;
  const char* plogdest = NULL;
  int c;
  /* Commands command; */
  struct host_cookie cookie;
  struct host_desc host;
  unsigned short nsPort;
  const char *parameter = NULL;
  extern char *optarg;
  extern int optind;
  
  unsigned short sensorPort;
  double timeOut;

  timeOut = PKTTIMEOUT;

  DirectDiagnostics(DIAGINFO, stdout);
  DirectDiagnostics(DIAGLOG, stdout);
  DirectDiagnostics(DIAGWARN, stderr);
  DirectDiagnostics(DIAGERROR, stderr);
  DirectDiagnostics(DIAGFATAL, stderr);

  nsPort = DefaultHostPort(NAME_SERVER_HOST);
  sensorPort = DefaultHostPort(SENSOR_HOST);

  while((c = getopt(argc, argv, SWITCHES)) != EOF) {

    switch(c) {

    case 'l':
		for(logdest = MEMORY_LOG_NONE; logdest <= MEMORY_LOG_REMOTE; logdest++) {
			if(strncasecmp(LOGDEST[logdest], optarg, strlen(optarg)) == 0)
				break;
		}
		break;

    case 'f':
      plogdest = optarg;
      break;

    case 'z':
      DirectDiagnostics(DIAGINFO, DIAGSUPPRESS);
      DirectDiagnostics(DIAGLOG, DIAGSUPPRESS);
      DirectDiagnostics(DIAGWARN, DIAGSUPPRESS);
      DirectDiagnostics(DIAGERROR, DIAGSUPPRESS);
      DirectDiagnostics(DIAGFATAL, DIAGSUPPRESS);
      break;

    default:
      fprintf(stderr, "unrecognized switch\n%s\n", USAGE);
      exit(1);
      break;

    }

  }

  if(optind >= argc) {
    fprintf(stderr, "%s\n", USAGE);
    exit(1);
  }

  parameter = argv[optind];
  optind++;

  HostDValue(parameter, nsPort, &host);
  
  MakeHostCookie(host.host_name, host.port, &cookie);

  
  if(!ConnectToHost(&cookie, &cookie.sd)) {
      
       WARN1("connect %s failed\n", HostDImage(&host));
	   return 1;
  }
  
    switch(logdest) {
	case MEMORY_LOG_NONE: /* stop logging */
		
		DoStopLogging(cookie.sd, plogdest, timeOut);
		printf("4\n");
		break;
	case MEMORY_LOG_LOCAL: /* set local file */
		DoLogLocal(cookie.sd, plogdest, timeOut);
		break;
	case MEMORY_LOG_NETLOGGER: /* set netlogger  */
		DoLogNetLogger(cookie.sd, plogdest, timeOut);
		break;
	case MEMORY_LOG_REMOTE: /* set remote file */
		/* DoLogRemote(cookie.sd, plogdest, timeOut); */
		break;
	}

  DisconnectHost(&cookie);
  return(0);

}
Beispiel #15
0
// Handle mouse event
void _Menu::MouseEvent(const _MouseEvent &MouseEvent) {
	if(State == STATE_NONE)
		return;

	if(!CurrentLayout)
		return;

	if(MouseEvent.Button == SDL_BUTTON_LEFT)
		CurrentLayout->HandleInput(MouseEvent.Pressed);

	// Get clicked element
	_Element *Clicked = CurrentLayout->GetClickedElement();
	if(Clicked) {
		bool DoubleClick = false;
		if(PreviousClick == Clicked && PreviousClickTimer < MENU_DOUBLECLICK_TIME) {
			PreviousClick = nullptr;
			DoubleClick = true;
		}
		else
			PreviousClick = Clicked;
		PreviousClickTimer = 0.0;

		switch(State) {
			case STATE_TITLE: {
				if(Clicked->Identifier == "button_title_play") {
					PlayState.Connect(true);
				}
				else if(Clicked->Identifier == "button_title_joinserver") {
					InitConnect(true);
				}
				else if(Clicked->Identifier == "button_title_mapeditor") {
					InitEditor();
				}
				else if(Clicked->Identifier == "button_title_exit") {
					Framework.Done = true;
				}
			} break;
			case STATE_CHARACTERS: {
				if(CharactersState == CHARACTERS_NONE) {

					if(Clicked->Identifier == "button_characters_delete") {
						size_t SelectedSlot = GetSelectedCharacter();
						if(SelectedSlot < CharacterSlots.size() && CharacterSlots[SelectedSlot].Used) {
							_Buffer Packet;
							Packet.Write<PacketType>(PacketType::CHARACTERS_DELETE);
							Packet.Write<uint8_t>((uint8_t)SelectedSlot);
							PlayState.Network->SendPacket(Packet);
						}
					}
					else if(Clicked->Identifier == "button_characters_play") {
						size_t SelectedSlot = GetSelectedCharacter();
						if(SelectedSlot < CharacterSlots.size() && CharacterSlots[SelectedSlot].Used) {
							PlayCharacter(SelectedSlot);
						}
					}
					else if(Clicked->Identifier == "button_characters_back") {
						PlayState.Network->Disconnect();
					}
					else if(Clicked->Identifier.substr(0, CharacterButtonPrefix.size()) == CharacterButtonPrefix) {

						// Deselect slots
						_Element *CharactersElement = Assets.Elements["element_menu_characters"];
						for(auto &Element : CharactersElement->Children) {
							if(Element->Identifier.substr(0, CharacterButtonPrefix.size()) == CharacterButtonPrefix) {
								_Button *Button = (_Button *)Element;
								Button->Checked = false;
							}
						}

						// Set selection
						size_t SelectedSlot = (size_t)(intptr_t)Clicked->UserData;
						CharacterSlots[SelectedSlot].Button->Checked = true;

						// Open new character screen
						if(!CharacterSlots[SelectedSlot].Used)
							InitNewCharacter();

						UpdateCharacterButtons();

						if(DoubleClick && SelectedSlot < CharacterSlots.size()) {
							PlayCharacter(SelectedSlot);
						}
					}
				}
				else if(CharactersState == CHARACTERS_CREATE) {
					if(Clicked->Identifier == NewCharacterPortraitPrefix || Clicked->Identifier == NewCharacterBuildPrefix) {
						size_t SelectedID = (size_t)(intptr_t)Clicked->UserData;

						// Unselect all portraits and select the clicked element
						for(auto &Element : Clicked->Parent->Children) {
							_Button *Button = (_Button *)Element;
							Button->Checked = false;
							if((size_t)(intptr_t)Button->UserData == SelectedID) {
								_TextBox *Name = Assets.TextBoxes["textbox_newcharacter_name"];
								FocusedElement = Name;
								Name->ResetCursor();
								Button->Checked = true;
							}
						}

						ValidateCreateCharacter();
					}
					else if(Clicked->Identifier == "button_newcharacter_create") {
						CreateCharacter();
					}
					else if(Clicked->Identifier == "button_newcharacter_cancel") {
						RequestCharacterList();
					}
				}
			} break;
			case STATE_CONNECT: {
				if(Clicked->Identifier == "button_connect_connect") {
					if(!PlayState.Network->IsDisconnected()) {
						PlayState.Network->Disconnect(true);
						InitConnect(false);
					}
					else
						ConnectToHost();
				}
				else if(Clicked->Identifier == "button_connect_back") {
					InitTitle(true);
				}
			} break;
			case STATE_ACCOUNT: {
				if(Clicked->Identifier == "button_account_login") {
					SendAccountInfo();
				}
				else if(Clicked->Identifier == "button_account_create") {
					SendAccountInfo(true);
				}
				else if(Clicked->Identifier == "button_account_back") {
					InitConnect(true);
				}
			} break;
			case STATE_INGAME: {
				if(Clicked->Identifier == "button_ingame_resume") {
					InitPlay();
				}
				else if(Clicked->Identifier == "button_ingame_disconnect") {
					PlayState.Network->Disconnect();
				}
			} break;
			default:
			break;
		}
	}
}
int
main(int argc,
     char *argv[]) {

  typedef enum {ERROR, HALT, LOG, REGISTER, TEST} Commands;
  const char *COMMANDS[] = {"error", "halt", "log", "register", "test"};
  const char *USAGE = "ctrl_host [-P password] [-t n] [-z] <command> host ...";

  int c;
  Commands command;
  struct host_cookie cookie;
  struct host_desc host;
  HostInfo info;
  struct host_desc nsDesc;
  unsigned short nsPort;
  const char *parameter = NULL;
  const char *password;
  const char *STATII[] = {"dead", "healthy", "sick", "unresponsive"};
  unsigned short sensorPort;
  HostStatii status;
  const char *TYPES[] = {"forecaster", "memory", "name_server", "sensor"};
  double timeOut;
  extern char *optarg;
  extern int optind;

  password = NULL;
  timeOut = PKTTIMEOUT;

  DirectDiagnostics(DIAGINFO, stdout);
  DirectDiagnostics(DIAGLOG, stdout);
  DirectDiagnostics(DIAGWARN, stderr);
  DirectDiagnostics(DIAGERROR, stderr);
  DirectDiagnostics(DIAGFATAL, stderr);

  nsPort = DefaultHostPort(NAME_SERVER_HOST);
  sensorPort = DefaultHostPort(SENSOR_HOST);

  while((c = getopt(argc, argv, SWITCHES)) != EOF) {

    switch(c) {

    case 'P':
      password = optarg;
      break;

    case 't':
      timeOut = atof(optarg);
      break;

    case 'z':
      DirectDiagnostics(DIAGINFO, DIAGSUPPRESS);
      DirectDiagnostics(DIAGLOG, DIAGSUPPRESS);
      DirectDiagnostics(DIAGWARN, DIAGSUPPRESS);
      DirectDiagnostics(DIAGERROR, DIAGSUPPRESS);
      DirectDiagnostics(DIAGFATAL, DIAGSUPPRESS);
      break;

    default:
      fprintf(stderr, "unrecognized switch\n%s\n", USAGE);
      exit(1);
      break;

    }

  }

  if(optind >= argc) {
    fprintf(stderr, "%s\n", USAGE);
    exit(1);
  }

  for(command = ERROR; command <= TEST; command++) {
    if(strncasecmp(COMMANDS[command], argv[optind], strlen(argv[optind])) == 0)
      break;
  }

  if(command > TEST) {
    fprintf(stderr, "unknown command %s\n", argv[optind]);
    exit(1);
  }

  optind++;

  switch(command) {

  case REGISTER:
    if(optind >= argc) {
      fprintf(stderr, "missing parameter for %c command\n", command);
      exit(1);
    }
    parameter = argv[optind++];
    HostDValue(parameter, nsPort, &nsDesc);
    if(!IsANameServer(&nsDesc, timeOut)) {
      fprintf(stderr, "%s is not a name server\n", parameter);
    }
    break;

  default:
    break;

  }

  for(; optind < argc; optind++) {

    HostDValue(argv[optind], sensorPort, &host);
    MakeHostCookie(host.host_name, host.port, &cookie);

    if(!ConnectToHost(&cookie, &cookie.sd)) {
      if(command == TEST) {
        printf("%s dead\n", HostDImage(&host));
      }
      else {
        WARN1("connect %s failed\n", HostDImage(&host));
      }
      continue;
    }

    switch(command) {

    case ERROR:
      if(!DoDiagnosticsCommand(cookie.sd, ALL_ERRORS, timeOut)) {
        WARN1("error toggle failed for host %s\n", HostDImage(&host));
      }
      break;

    case HALT:
      if(!DoHaltHost(cookie.sd, password, timeOut)) {
        WARN1("halt failed for host %s\n", HostDImage(&host));
      }
      break;

    case LOG:
      if(!DoDiagnosticsCommand(cookie.sd, ALL_LOGS, timeOut)) {
        WARN1("log toggle failed for host %s\n", HostDImage(&host));
      }
      break;

    case REGISTER:
      if(!DoRegisterHost(cookie.sd, parameter, password, timeOut)) {
        WARN1("registration change failed for host %s\n", HostDImage(&host));
      }
      break;

    case TEST:
      status = DoTestHost(cookie.sd, &info, timeOut);
      if((status == HEALTHY) || (status == SICK)) {
        printf("%s %s ", TYPES[info.hostType], HostDImage(&host));
        if((strcmp(info.registrationName, HostDImage(&host)) != 0) &&
           (strcmp(info.registrationName, "") != 0)) {
          printf("(%s) ", info.registrationName);
        }
        printf("registered with %s ", info.nameServer);
      }
      else {
        printf("%s ", HostDImage(&host));
      }
      printf("%s\n", STATII[status]);
      break;

    }

    DisconnectHost(&cookie);

  }

  return(0);

}
int mpiexec_rsh()
{
    int i;
    smpd_launch_node_t *launch_node_ptr;
    smpd_process_t *process, **processes;
    int result;
    char *iter1, *iter2;
    char exe[SMPD_MAX_EXE_LENGTH];
    char *p;
    char ssh_cmd[100] = "ssh -x";
    SMPDU_Sock_set_t set;
    SMPD_BOOL escape_escape = SMPD_TRUE;
    char *env_str;
    int maxlen;
    SMPDU_Sock_t abort_sock;
    smpd_context_t *abort_context = NULL;
    smpd_command_t *cmd_ptr;
    PROCESS_HANDLE_TYPE hnd;

    smpd_enter_fn("mpiexec_rsh");

#ifdef HAVE_WINDOWS_H
    SetConsoleCtrlHandler(mpiexec_rsh_handler, TRUE);
#else
    /* setup a signall hander? */
#endif

    p = getenv("MPIEXEC_RSH");
    if (p != NULL && strlen(p) > 0){
	    strncpy(ssh_cmd, p, 100);
    }

    p = getenv("MPIEXEC_RSH_NO_ESCAPE");
    if (p != NULL){
	    if (smpd_is_affirmative(p) || strcmp(p, "1") == 0){
	        escape_escape = SMPD_FALSE;
	    }
    }

    result = SMPDU_Sock_create_set(&set);
    if (result != SMPD_SUCCESS){
	    smpd_err_printf("unable to create a set for the mpiexec_rsh.\n");
	    smpd_exit_fn("mpiexec_rsh");
	    return SMPD_FAIL;
    }

    smpd_process.nproc = smpd_process.launch_list->nproc;

    if (smpd_process.use_pmi_server){
	    result = start_pmi_server(smpd_process.launch_list->nproc, root_host, 100, &root_port);
	    if (result != SMPD_SUCCESS){
	        smpd_err_printf("mpiexec_rsh is unable to start the local pmi server.\n");
	        smpd_exit_fn("mpiexec_rsh");
	        return SMPD_FAIL;
	    }
	    smpd_dbg_printf("the pmi server is listening on %s:%d\n", root_host, root_port);
    }
    else{
	    /* start the root smpd */
	    result = start_root_smpd(root_host, SMPD_MAX_HOST_LENGTH, &root_port, &hnd);
	    if (result != SMPD_SUCCESS){
		    smpd_err_printf("mpiexec_rsh is unable to start the root smpd.\n");
		    smpd_exit_fn("mpiexec_rsh");
		    return SMPD_FAIL;
	    }
	    smpd_dbg_printf("the root smpd is listening on %s:%d\n", root_host, root_port);

	    /* create a connection to the root smpd used to abort the job */
	    result = ConnectToHost(root_host, root_port, SMPD_CONNECTING_RPMI, set, &abort_sock, &abort_context);
	    if (result != SMPD_SUCCESS){
	        smpd_exit_fn("mpiexec_rsh");
	        return SMPD_FAIL;
	    }
    }

    processes = (smpd_process_t**)MPIU_Malloc(sizeof(smpd_process_t*) * smpd_process.launch_list->nproc);
    if (processes == NULL){
	    smpd_err_printf("unable to allocate process array.\n");
	    smpd_exit_fn("mpiexec_rsh");
	    return SMPD_FAIL;
    }

    launch_node_ptr = smpd_process.launch_list;
    for (i=0; i<smpd_process.launch_list->nproc; i++){
	    if (launch_node_ptr == NULL){
		    smpd_err_printf("Error: not enough launch nodes.\n");
		    smpd_exit_fn("mpiexec_rsh");
		    return SMPD_FAIL;
	    }

	    /* initialize process structure */
	    result = smpd_create_process_struct(i, &process);
	    if (result != SMPD_SUCCESS){
		    smpd_err_printf("unable to create a process structure.\n");
		    smpd_exit_fn("mpiexec_rsh");
		    return SMPD_FAIL;
	    }
	    /* no need for a pmi context */
	    if (process->pmi){
		    smpd_free_context(process->pmi);
        }
	    process->pmi = NULL;
	    /* change stdout and stderr to rsh behavior: 
	     * write stdout/err directly to stdout/err instead of creating
	     * an smpd stdout/err command 
	     */
	    if (process->out != NULL){
	        process->out->type = SMPD_CONTEXT_STDOUT_RSH;
	    }
	    if (process->err != NULL){
	        process->err->type = SMPD_CONTEXT_STDERR_RSH;
	    }
	    MPIU_Strncpy(process->clique, launch_node_ptr->clique, SMPD_MAX_CLIQUE_LENGTH);
	    MPIU_Strncpy(process->dir, launch_node_ptr->dir, SMPD_MAX_DIR_LENGTH);
	    MPIU_Strncpy(process->domain_name, smpd_process.kvs_name, SMPD_MAX_DBS_NAME_LEN);
	    MPIU_Strncpy(process->env, launch_node_ptr->env, SMPD_MAX_ENV_LENGTH);
	    if (escape_escape == SMPD_TRUE && smpd_process.mpiexec_run_local != SMPD_TRUE){
		    /* convert \ to \\ to make cygwin ssh happy */
		    iter1 = launch_node_ptr->exe;
		    iter2 = exe;
		    while (*iter1){
			    if (*iter1 == '\\'){
				    *iter2 = *iter1;
				    iter2++;
				    *iter2 = *iter1;
			    }
			    else{
				    *iter2 = *iter1;
			    }
			    iter1++;
			    iter2++;
		    }
		    *iter2 = '\0';
		    /*printf("[%s] -> [%s]\n", launch_node_ptr->exe, exe);*/
	    }
	    else{
	        MPIU_Strncpy(exe, launch_node_ptr->exe, SMPD_MAX_EXE_LENGTH);
	    }

	    /* Two samples for testing on the local machine */

	    /* static rPMI initialization */
	    /*sprintf(process->exe, "env PMI_RANK=%d PMI_SIZE=%d PMI_KVS=%s PMI_ROOT_HOST=%s PMI_ROOT_PORT=8888 PMI_ROOT_LOCAL=1 PMI_APPNUM=%d %s",
		    launch_node_ptr->iproc, launch_node_ptr->nproc, smpd_process.kvs_name, root_host, launch_node_ptr->appnum, exe);*/

	    /* dynamic rPMI initialization */
	    /*sprintf(process->exe, "env PMI_RANK=%d PMI_SIZE=%d PMI_KVS=%s PMI_ROOT_HOST=%s PMI_ROOT_PORT=%d PMI_ROOT_LOCAL=0 PMI_APPNUM=%d %s",
		    launch_node_ptr->iproc, launch_node_ptr->nproc, smpd_process.kvs_name, root_host, root_port, launch_node_ptr->appnum, exe);*/

	    if (smpd_process.mpiexec_run_local == SMPD_TRUE){
		    /* -localonly option and dynamic rPMI initialization */
		    env_str = &process->env[strlen(process->env)];
		    maxlen = (int)(SMPD_MAX_ENV_LENGTH - strlen(process->env));
		    MPIU_Str_add_int_arg(&env_str, &maxlen, "PMI_RANK", launch_node_ptr->iproc);
		    MPIU_Str_add_int_arg(&env_str, &maxlen, "PMI_SIZE", launch_node_ptr->nproc);
		    MPIU_Str_add_string_arg(&env_str, &maxlen, "PMI_KVS", smpd_process.kvs_name);
		    MPIU_Str_add_string_arg(&env_str, &maxlen, "PMI_ROOT_HOST", root_host);
		    MPIU_Str_add_int_arg(&env_str, &maxlen, "PMI_ROOT_PORT", root_port);
		    MPIU_Str_add_string_arg(&env_str, &maxlen, "PMI_ROOT_LOCAL", "0");
		    MPIU_Str_add_int_arg(&env_str, &maxlen, "PMI_APPNUM", launch_node_ptr->appnum);
		    MPIU_Strncpy(process->exe, exe, SMPD_MAX_EXE_LENGTH);
    	}
	    else{
		    /* ssh and dynamic rPMI initialization */
			    char fmtEnv[SMPD_MAX_ENV_LENGTH];
		    int fmtEnvLen = SMPD_MAX_ENV_LENGTH;
		    char *pExe = process->exe;
		    int curLen = 0;
		    MPIU_Snprintf(pExe, SMPD_MAX_EXE_LENGTH, "%s %s env", ssh_cmd, launch_node_ptr->hostname);
		    curLen = strlen(process->exe);
		    pExe = process->exe + curLen;
			if(FmtEnvVarsForSSH(launch_node_ptr->env, fmtEnv, fmtEnvLen)){
			    /* Add user specified env vars */
			    MPIU_Snprintf(pExe, SMPD_MAX_EXE_LENGTH - curLen, "%s", fmtEnv);
			    curLen = strlen(process->exe);
			    pExe = process->exe + curLen;
		    }
		    MPIU_Snprintf(pExe, SMPD_MAX_EXE_LENGTH - curLen, " \"PMI_RANK=%d\" \"PMI_SIZE=%d\" \"PMI_KVS=%s\" \"PMI_ROOT_HOST=%s\" \"PMI_ROOT_PORT=%d\" \"PMI_ROOT_LOCAL=0\" \"PMI_APPNUM=%d\" %s",
		    launch_node_ptr->iproc, launch_node_ptr->nproc, smpd_process.kvs_name, root_host, root_port, launch_node_ptr->appnum, exe);
	    }

	    MPIU_Strncpy(process->kvs_name, smpd_process.kvs_name, SMPD_MAX_DBS_NAME_LEN);
	    process->nproc = launch_node_ptr->nproc;
	    MPIU_Strncpy(process->path, launch_node_ptr->path, SMPD_MAX_PATH_LENGTH);

	    /* call smpd_launch_process */
	    smpd_dbg_printf("launching: %s\n", process->exe);
	    result = smpd_launch_process(process, SMPD_DEFAULT_PRIORITY_CLASS, SMPD_DEFAULT_PRIORITY, SMPD_FALSE, set);
	    if (result != SMPD_SUCCESS){
		    smpd_err_printf("unable to launch process %d <%s>.\n", i, process->exe);
		    smpd_exit_fn("mpiexec_rsh");
		    return SMPD_FAIL;
	    }
	    /* save the new process in the list */
	    process->next = smpd_process.process_list;
	    smpd_process.process_list = process;
	    if (i == 0){
		    /* start the stdin redirection thread to the first process */
		    setup_stdin_redirection(process, set);
	    }

	    smpd_process.nproc_launched++;
	    processes[i] = process;
	    launch_node_ptr = launch_node_ptr->next;
    } /* for (i=0; i<smpd_process.launch_list->nproc; i++) */
    
    if (launch_node_ptr != NULL){
	    smpd_err_printf("Error: too many launch nodes.\n");
	    smpd_exit_fn("mpiexec_rsh");
	    return SMPD_FAIL;
    }

    /* Start the timeout mechanism if specified */
    if (smpd_process.timeout > 0){
	    smpd_context_t *reader_context;
	    SMPDU_Sock_t sock_reader;
	    SMPDU_SOCK_NATIVE_FD reader, writer;
#ifdef HAVE_WINDOWS_H
	    /*SOCKET reader, writer;*/
	    smpd_make_socket_loop((SOCKET*)&reader, (SOCKET*)&writer);
#else
	    /*int reader, writer;*/
	    int pair[2];
	    socketpair(AF_UNIX, SOCK_STREAM, 0, pair);
	    reader = pair[0];
	    writer = pair[1];
#endif
	    result = SMPDU_Sock_native_to_sock(set, reader, NULL, &sock_reader);
	    result = SMPDU_Sock_native_to_sock(set, writer, NULL, &smpd_process.timeout_sock);
	    result = smpd_create_context(SMPD_CONTEXT_TIMEOUT, set, sock_reader, -1, &reader_context);
	    reader_context->read_state = SMPD_READING_TIMEOUT;
	    result = SMPDU_Sock_post_read(sock_reader, &reader_context->read_cmd.cmd, 1, 1, NULL);
#ifdef HAVE_WINDOWS_H
	    /* create a Windows thread to sleep until the timeout expires */
	    smpd_process.timeout_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)timeout_thread, NULL, 0, NULL);
	    if (smpd_process.timeout_thread == NULL){
		    printf("Error: unable to create a timeout thread, errno %d.\n", GetLastError());
		    smpd_exit_fn("mp_parse_command_args");
		    return SMPD_FAIL;
	    }
#else /* HAVE_WINDOWS_H */
#ifdef SIGALRM
	    /* create an alarm to signal mpiexec when the timeout expires */
	    smpd_signal(SIGALRM, timeout_function);
	    alarm(smpd_process.timeout);
#else /* SIGALARM */
#ifdef HAVE_PTHREAD_H
	    /* create a pthread to sleep until the timeout expires */
	    result = pthread_create(&smpd_process.timeout_thread, NULL, timeout_thread, NULL);
	    if (result != 0){
		    printf("Error: unable to create a timeout thread, errno %d.\n", result);
		    smpd_exit_fn("mp_parse_command_args");
		    return SMPD_FAIL;
	    }
#else /* HAVE_PTHREAD_H */
	/* no timeout mechanism available */
#endif /* HAVE_PTHREAD_H */
#endif /* SIGALARM */
#endif /* HAVE_WINDOWS_H */
    } /* if (smpd_process.timeout > 0) */

    result = smpd_enter_at_state(set, SMPD_IDLE);
    if (result != SMPD_SUCCESS){
	    smpd_err_printf("mpiexec_rsh state machine failed.\n");
	    smpd_exit_fn("mpiexec_rsh");
	    return SMPD_FAIL;
    }

    if (smpd_process.use_pmi_server){
	    result = stop_pmi_server();
	    if (result != SMPD_SUCCESS){
		    smpd_err_printf("mpiexec_rsh unable to stop the pmi server.\n");
		    smpd_exit_fn("mpiexec_rsh");
		    return SMPD_FAIL;
	    }
    }
    else{
	    /* Send an abort command to the root_smpd thread/process to insure that it exits.
	     * This only needs to be sent when there is an error or failed process of some sort
	     * but it is safe to send it in all cases.
	     */
	    result = smpd_create_command("abort", 0, 0, SMPD_FALSE, &cmd_ptr);
	    if (result != SMPD_SUCCESS){
		    smpd_err_printf("unable to create an abort command.\n");
		    smpd_exit_fn("mpiexec_rsh");
		    return SMPD_FAIL;
	    }
	    result = smpd_post_write_command(abort_context, cmd_ptr);
	    if (result != SMPD_SUCCESS){
		    /* Only print this as a debug message instead of an error because the root_smpd thread/process may have already exited. */
		    smpd_dbg_printf("unable to post a write of the abort command to the %s context.\n", smpd_get_context_str(abort_context));
		    smpd_exit_fn("mpiexec_rsh");
		    return SMPD_FAIL;
	    }

	    result = stop_root_smpd(hnd);
	    if (result != PMI_SUCCESS){
		    smpd_err_printf("mpiexec_rsh unable to stop the root smpd.\n");
		    smpd_exit_fn("mpiexec_rsh");
		    return SMPD_FAIL;
	    }
    }

    smpd_exit_fn("mpiexec_rsh");
    return 0;
}
Beispiel #18
0
int CTransfer::Transfer(CMobileClient *pClient, char *pszType, int nNzcNumber, int nPort, char *pszFileName, int nTryTime, BOOL bCompress)
{
	char	szNumber[64] = "";
	int		nState, nError;
	BOOL	bConnected = FALSE;
	BOOL	bCDMA, bEvent;
	int		nRetry = 0;
	int		nIndex = 0;
	int		nResult;
	time_t	tmStart, tmNow;

	m_bCompress	= bCompress;
	m_nNzcNumber = nNzcNumber;
	m_nMobileType = MOBILE_GSM;
	bCDMA = (strcmp(pszType, "cdma") == 0) ? TRUE : FALSE;
	if (bCDMA) m_nMobileType = MOBILE_CDMA;
	bEvent = strstr(pszFileName, "event") != NULL ? TRUE : FALSE;

	LoadPhoneList();
	if (m_nPhoneCount == 0)
	{
		XDEBUG("File not found: /app/sw/phonelist\r\n");
		return 0;
	}

	time(&tmStart);
	for(nState=STATE_INIT; !m_bExitSignalPending;)
	{
		switch(nState) {
 		  case STATE_INIT :
			   nRetry = 0;
			   DisconnectModem();
			   nState = STATE_TRY_CONNECT;
			   break;

		  case STATE_TRY_CONNECT :
			   strcpy(szNumber, m_szPhoneList[nIndex]);
		       XDEBUG("CIRCUIT: Try Connect to %s. (%s)\r\n",
						szNumber, bEvent ? "Event" : "Data");
			   UpdateLogFile(LOG_DIR, UPLOAD_LOG_FILE, 0, TRUE, "%s:%d Try connect.\n", szNumber, nPort);

			   nError = ConnectToHost(pClient, szNumber, bCDMA, nPort);
			   if (nError != 0)
			   {
				   switch(nError) {
					 case -4 :
					      XDEBUG("CIRCUIT: Server is not accept. (CPIN=%s, CSQ=%s, SBV=%s)\r\n",
								szCPIN, szCSQ, szSBV);
			       	      UpdateLogFile(LOG_DIR, UPLOAD_LOG_FILE, 0, TRUE, "%s:%d Server is not accept. (CPIN=%s, CSQ=%s, SBV=%s)\n",
								szNumber, nPort, szCPIN, szCSQ, szSBV);
						  break;
				     case -10 :
					      XDEBUG("CIRCUIT: Modem or SIM error!!.\r\n");
			       	      UpdateLogFile(LOG_DIR, UPLOAD_LOG_FILE, 0, TRUE, "%s:%d Modem or SIM error.\n", szNumber, nPort);
						  break;
				     case -1 :
					 case -2 :
					 case -3 :
					  default:
					      XDEBUG("CIRCUIT: Cannot connect to host. (CPIN=%s, CSQ=%s, SBV=%s)\r\n",
								szCPIN, szCSQ, szSBV);
			       	      UpdateLogFile(LOG_DIR, UPLOAD_LOG_FILE, 0, TRUE, "%s:%d Cannot connect to host. (CPIN=%s, CSQ=%s, SBV=%s)\n",
								szNumber, nPort, szCPIN, szCSQ, szSBV);
						  break;
				   }	
				   nState = STATE_RETRY;
				   break;
			   }

		       XDEBUG("CIRCUIT: Connected.\r\n");
			   UpdateLogFile(LOG_DIR, UPLOAD_LOG_FILE, 0, TRUE, "%s:%d Connected. (%s)\n", szNumber, nPort, bEvent ? "Event" : "Data");
			   bConnected = TRUE;
			   nState = STATE_SEND;
		 	   break;

		  case STATE_SEND :
			   XDEBUG("CIRCUIT: Sending %s...\r\n", bEvent ? "Event" : "Data");
			   nResult = -1;
			   m_pszReadBuffer = (char *)MALLOC(1024*30);
			   if (m_pszReadBuffer != NULL)
			   {
				   if (bEvent)
			   		    nResult = SendEvent(pClient, pszFileName);
			   	   else nResult = SendMetering(pClient, pszFileName);
				   FREE(m_pszReadBuffer);
			   }
			   nState = (nResult == SENDERR_OK) ? STATE_TERMINATE : STATE_RETRY;
			   if (nState == STATE_RETRY)
			   {
			   	   UpdateLogFile(LOG_DIR, UPLOAD_LOG_FILE, 0, TRUE, "%s:%d %s Sending fail (ERROR=%d).\n",
								szNumber, nPort,
								bEvent ? "Event" : "Data",
								nResult);
			   }
		 	   break;

		  case STATE_RETRY :
			   XDEBUG("CIRCUIT: Disconnect mobile session.\r\n");
			   DisconnectModem();

			   nIndex++;
			   if (nIndex >= m_nPhoneCount)
			       nIndex = 0;

			   nRetry++;
			   if (nRetry >= MAX_RETRY_COUNT)
			   {
				   XDEBUG("CIRCUIT: Out of MAX_RETRY_COUNT(%d).\r\n", MAX_RETRY_COUNT);
				   DisconnectModem();
				   return 0;
			   }

			   time(&tmNow);
			   if ((tmNow-tmStart) > nTryTime)
			   {
				   XDEBUG("CIRCUIT: Max try timeout(%d).\r\n", (int)(tmNow-tmStart));
				   DisconnectModem();
				   return 0;
			   }

			   XDEBUG("\r\n");
			   XDEBUG("CIRCUIT: SEND RETRY (Retry=%d, Time=%d min %d seconds)\r\n",
						nRetry,
						(int)(tmNow-tmStart) / 60,
						(int)(tmNow-tmStart) % 60);
			   nState = STATE_TRY_CONNECT;
		 	   break;

		  case STATE_TERMINATE :
			   time(&tmNow);
			   XDEBUG("\r\n");
			   XDEBUG("CIRCUIT: Total send time = %d min %d seconds\r\n",
						(int)(tmNow-tmStart) / 60,
						(int)(tmNow-tmStart) % 60);
			   XDEBUG("CIRCUIT: Disconnect mobile session.\r\n");
			   UpdateLogFile(LOG_DIR, UPLOAD_LOG_FILE, 0, TRUE, "%s:%d %s Sending ok (Total=%d).\n",
						szNumber, nPort,
						bEvent ? "Event" : "Data",
						m_nSentLine);
			   DisconnectModem();
			   return 1;
		}
	}

	if (m_bExitSignalPending)
	{
	    XDEBUG("CIRCUIT: User stop. Disconnect mobile.\r\n");
		DisconnectModem();
	}
	
	return 0;
}
Beispiel #19
0
bool BTCtcp::ConnectToHost(int PortNo, const char *szIPAddress)
{
	return ConnectToHost(PortNo, inet_addr(szIPAddress));
}
Beispiel #20
0
int STREAMConnectToHost(STREAM *S, char *DesiredHost, int DesiredPort,int Flags)
{
    ListNode *Curr;
    char *Token=NULL, *ptr;
    int result=FALSE;
    int HopNo=0, val;
    ListNode *LastHop=NULL;

    S->Path=FormatStr(S->Path,"tcp:%s:%d",DesiredHost,DesiredPort);
//Find the last hop, used to decide what ssh command to use
    Curr=ListGetNext(S->Values);
    while (Curr)
    {
        ptr=GetToken(Curr->Tag,":",&Token,0);
        if (strcasecmp(Token,"ConnectHop")==0) LastHop=Curr;
        Curr=ListGetNext(Curr);
    }

    STREAMSetFlushType(S,FLUSH_LINE,0);
    Curr=ListGetNext(S->Values);
    while (Curr)
    {
        ptr=GetToken(Curr->Tag,":",&Token,0);

        if (strcasecmp(Token,"ConnectHop")==0) result=STREAMProcessConnectHop(S, (char *) Curr->Item,Curr==LastHop);

        HopNo++;
        if (! result) break;
        Curr=ListGetNext(Curr);
    }

//If we're not handling the connection through 'Connect hops' then
//just connect to host
    if ((HopNo==0) && StrLen(DesiredHost))
    {
        if (Flags & CONNECT_NONBLOCK) S->Flags |= SF_NONBLOCK;
        val=Flags;
        if (S->Timeout > 0) val |= CONNECT_NONBLOCK;

        S->in_fd=ConnectToHost(DesiredHost,DesiredPort,val);
        S->out_fd=S->in_fd;
        if (S->in_fd > -1) result=TRUE;
    }

    if (result==TRUE)
    {
        if (Flags & CONNECT_NONBLOCK)
        {
            S->State |=SS_CONNECTING;
            S->Flags |=SF_NONBLOCK;
        }
        else
        {
            S->State |=SS_CONNECTED;
            STREAMDoPostConnect(S, Flags);
        }
    }


    return(result);
}
Beispiel #21
0
// Handle key event
void _Menu::KeyEvent(const _KeyEvent &KeyEvent) {
	if(State == STATE_NONE)
		return;

	switch(State) {
		case STATE_TITLE: {
			if(KeyEvent.Pressed && !KeyEvent.Repeat) {
				if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
					Framework.Done = true;
				else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN) {
					PlayState.Connect(true);
				}
			}
		} break;
		case STATE_CHARACTERS: {
			if(CharactersState == CHARACTERS_NONE) {
				if(KeyEvent.Pressed && !KeyEvent.Repeat) {
					if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
						PlayState.Network->Disconnect();
					else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN) {
						size_t SelectedSlot = GetSelectedCharacter();
						if(SelectedSlot >= CharacterSlots.size())
							SelectedSlot = 0;

						if(CharacterSlots[SelectedSlot].Used) {
							PlayCharacter(SelectedSlot);
						}
					}
				}
			}
			else if(CharactersState == CHARACTERS_CREATE){
				ValidateCreateCharacter();

				if(KeyEvent.Pressed) {
					if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
						RequestCharacterList();
					else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN)
						CreateCharacter();
				}
			}
		} break;
		case STATE_CONNECT: {
			if(KeyEvent.Pressed && !KeyEvent.Repeat) {
				if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
					InitTitle(true);
				else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN)
					ConnectToHost();
				else if(KeyEvent.Scancode == SDL_SCANCODE_TAB)
					FocusNextElement();
			}
		} break;
		case STATE_ACCOUNT: {
			if(KeyEvent.Pressed && !KeyEvent.Repeat) {
				if(KeyEvent.Scancode == SDL_SCANCODE_ESCAPE)
					InitConnect(true);
				else if(KeyEvent.Scancode == SDL_SCANCODE_RETURN)
					SendAccountInfo();
				else if(KeyEvent.Scancode == SDL_SCANCODE_TAB)
					FocusNextElement();
			}
		} break;
		case STATE_INGAME: {
		} break;
		default:
		break;
	}
}