Exemplo n.º 1
0
void MumbleClient::connectToServer(QString address, unsigned port)
{
    _telnet->connectHost(address,port);
    QObject::connect(_telnet,SIGNAL(connectedToHost()),this,SLOT(sendVersion()));
    QObject::connect(_telnet,SIGNAL(haveMessage(QByteArray)),this,SLOT(processProtoMessage(QByteArray)));
    QObject::connect(_telnet,SIGNAL(haveUDPData(QByteArray)),this,SLOT(processUDPData(QByteArray)));
}
Exemplo n.º 2
0
void epuckPlayer()
{
  //e_start_agendas_processing();
  //e_init_motors();
  //e_init_prox();
  //e_init_uart1();

  /* Must send anything here or it don't work. Is it a bug? */
  e_send_uart1_char("epuckSide_v3.0", 14);

  unsigned a,b;

  /* Flash the LED's in a singular manner for show that this program is in
   * epuck memory */
  for(a=0; a<8; a++)
    for(b=0; b<20000; b++)
      e_set_led(a ,1); /* LED ON */

  for(a=0; a<8; a++)
    for(b=0; b<20000; b++)
      e_set_led(a ,0); /* LED OFF */

  char command;
  while(1)
  {
    command = recv_char();

    switch(command)
    {
    case 0x13:
      recv_vel();
      break;
    case 0x14:
      send_steps();
      break;
    case 0x16:
      read_ir_sensors();
      break;
    case 0x15:
      stop_motors();
      break;
    case 0x17:
      read_camera();
      break;
    case 0x18:
      set_LEDs();
      break;
    case 0x01:
      sendVersion();
      break;
    case 0x02:
      config_camera();
      break;
    }
  }
}
Exemplo n.º 3
0
ServerConnection::ServerConnection( const QString &sourcedir, QTcpSocket *socket ) : 
  RemoteObjectConnection( socket )
{
  fDefaultSourceDir = sourcedir;
  fSourceDir = sourcedir;
  
  connect( this, SIGNAL(recvTargetDirectory(const QString &)), SLOT(recvTargetDirectory(const QString &)) );
  connect( this, SIGNAL(recvStatFileReq(const QString &)), SLOT(recvStatFileReq(const QString &)) );
  connect( this, SIGNAL(recvSendFile(const QString &, const QDateTime &, const QByteArray &, bool)), SLOT(recvSendFile(const QString &, const QDateTime &, const QByteArray &, bool)) );
  connect( this, SIGNAL(recvDeleteFile(const QString &)), SLOT(recvDeleteFile(const QString &)) );

  sendVersion();
}
Exemplo n.º 4
0
void MumbleClient::disconnectFromServer()
{
    if(_authenticated)
    {
        _telnet->disconnectHost();
        QObject::disconnect(_telnet,SIGNAL(connectedToHost()),this,SLOT(sendVersion()));
        QObject::disconnect(_telnet,SIGNAL(haveMessage(QByteArray)),this,SLOT(processProtoMessage(QByteArray)));
        QObject::disconnect(_telnet,SIGNAL(haveUDPData(QByteArray)),this,SLOT(processUDPData(QByteArray)));
        _encryption_set = false;
        _authenticated = false;
        _synchronized = false;
        _session_id = -1;
    }
}
Exemplo n.º 5
0
/* #define SERVER_DEBUG 1   */
int
main(int argc, char *argv[])
{
    int status;
    rsComm_t rsComm;
    char *tmpStr;

    ProcessType = AGENT_PT;

#ifdef RUN_SERVER_AS_ROOT
#ifndef windows_platform
    if (initServiceUser() < 0) {
        exit (1);
    }
#endif
#endif

#ifdef windows_platform
	iRODSNtAgentInit(argc, argv);
#endif

#ifndef windows_platform
    signal(SIGINT, signalExit);
    signal(SIGHUP, signalExit);
    signal(SIGTERM, signalExit);
    /* set to SIG_DFL as recommended by andy.salnikov so that system()
     * call returns real values instead of 1 */
    signal(SIGCHLD, SIG_DFL);
    signal(SIGUSR1, signalExit);
    signal(SIGPIPE, rsPipSigalHandler);
#endif

#ifndef windows_platform
#ifdef SERVER_DEBUG
    if (isPath ("/tmp/rodsdebug"))
        sleep (20);
#endif
#endif

#ifdef SYS_TIMING
    rodsLogLevel(LOG_NOTICE);
    printSysTiming ("irodsAgent", "exec", 1);
#endif

    memset (&rsComm, 0, sizeof (rsComm));

    status = initRsCommWithStartupPack (&rsComm, NULL);

    if (status < 0) {
	sendVersion (rsComm.sock, status, 0, NULL, 0);
        cleanupAndExit (status);
    }

    /* Handle option to log sql commands */
    tmpStr = getenv (SP_LOG_SQL);
    if (tmpStr != NULL) {
#ifdef IRODS_SYSLOG
       int j = atoi(tmpStr);
       rodsLogSqlReq(j);
#else
       rodsLogSqlReq(1);
#endif
    }

    /* Set the logging level */
    tmpStr = getenv (SP_LOG_LEVEL);
    if (tmpStr != NULL) {
       int i;
       i = atoi(tmpStr);
       rodsLogLevel(i);
    } else {
       rodsLogLevel(LOG_NOTICE); /* default */
    }

#ifdef IRODS_SYSLOG
/* Open a connection to syslog */
#ifdef SYSLOG_FACILITY_CODE
    openlog("rodsAgent",LOG_ODELAY|LOG_PID,SYSLOG_FACILITY_CODE);
#else
    openlog("rodsAgent",LOG_ODELAY|LOG_PID,LOG_DAEMON);
#endif
#endif

    status = getRodsEnv (&rsComm.myEnv);

    if (status < 0) {
	sendVersion (rsComm.sock, SYS_AGENT_INIT_ERR, 0, NULL, 0);
        cleanupAndExit (status);
    }

#if RODS_CAT
    if (strstr(rsComm.myEnv.rodsDebug, "CAT") != NULL) {
       chlDebug(rsComm.myEnv.rodsDebug);
    }
#endif

#ifdef RULE_ENGINE_N
    status = initAgent (RULE_ENGINE_TRY_CACHE, &rsComm);
#else
    status = initAgent (&rsComm);
#endif
#ifdef SYS_TIMING
    printSysTiming ("irodsAgent", "initAgent", 0);
#endif

    if (status < 0) {
	sendVersion (rsComm.sock, SYS_AGENT_INIT_ERR, 0, NULL, 0);
        cleanupAndExit (status);
    }

    /* move configConnectControl behind initAgent for now. need zoneName if
     * the user does not specify one in the input */
    initConnectControl ();

    if (rsComm.clientUser.userName[0] != '\0') {
        status = chkAllowedUser (rsComm.clientUser.userName,
         rsComm.clientUser.rodsZone);

        if (status < 0) {
            sendVersion (rsComm.sock, status, 0, NULL, 0);
            cleanupAndExit (status);
	}
    }

    /* send the server version and atatus as part of the protocol. Put
     * rsComm.reconnPort as the status */

    status = sendVersion (rsComm.sock, status, rsComm.reconnPort,
      rsComm.reconnAddr, rsComm.cookie);

    if (status < 0) {
	sendVersion (rsComm.sock, SYS_AGENT_INIT_ERR, 0, NULL, 0);
        cleanupAndExit (status);
    }
#ifdef SYS_TIMING
    printSysTiming ("irodsAgent", "sendVersion", 0);
#endif

    logAgentProc (&rsComm);

    status = agentMain (&rsComm);

    cleanupAndExit (status);

    return (status);
}
Exemplo n.º 6
0
/*
 * Main routine of our mini time server
 */
int
main(int argc, char* argv[])
{
	establishRedirection("mtimesrv.log", REDIR_OUT_APPEND, STDOUT_FILENO | STDERR_FILENO);

	printf("\nMicro Time Server\nVersion: %s\n\n", MTIMESRV_VERSION);

	init();
	daemonize();

	/* main server loop */
	while(1)
	{
		ipc_packet_data.sem_id  = status.sem_id;
		ipc_packet_data.reqresp = &request;
		
		if(receiveRequest(&ipc_packet_data) < 0)
		{
			ipcerror("mtimesrv::main():receiveRequest() - failed");
			exit(1);
		}
		
		/* Dispatch requests */
		switch(request.command)
		{
			case IDLE:
				printf("Idle\n");
				fflush(stdout);
				break;

			case TIME:
				sendTime();
				break;

			case OPEN:
				registerClient();
				break;

			case VERSION:
				sendVersion();
				break;

			case TERMINATE:
				terminate();
				break;

			case PING:
				processPing();
				break;

			default:
				printf("Unsupported command (%d) from a client (PID=%d)... Ignored.\n", request.command, request.client_pid);
				fflush(stdout);
				break;
		}

		/* Reset the request buffer */
		memset(&request, 0, sizeof(request_t));
	}

	return 0;
}
Exemplo n.º 7
0
Arquivo: capdl.c Projeto: scan/seL4
void capDL(void)
{
    int result;
    int done = 0;
    while (done == 0) {
        unsigned char c;
        do {
            c = getDebugChar();
        } while (c != START);
        do {
            result = getDecodedChar(&c);
            if (result) {
                continue;
            }
            switch (c) {
            case PD_COMMAND: {
                /*pgdir */
                unsigned long arg;
                result = getArg(&arg);
                if (result) {
                    continue;
                }
                sendPD(arg);
                putDebugChar(END);
            }
            break;
            case PT_COMMAND: {
                /*pg table */
                unsigned long arg;
                result = getArg(&arg);
                if (result) {
                    continue;
                }
                sendPT(arg);
                putDebugChar(END);
            }
            break;
            case ASID_POOL_COMMAND: {
                /*asid pool */
                unsigned long arg;
                result = getArg(&arg);
                if (result) {
                    continue;
                }
                sendASIDPool(arg);
                putDebugChar(END);
            }
            break;
            case IO_PT_COMMAND: {
                /*io pt table */
                unsigned long address, level;
                result = getArg(&address);
                if (result) {
                    continue;
                }
                result = getArg(&level);
                if (result) {
                    continue;
                }
                sendIOPT(address, level);
                putDebugChar(END);
            }
            break;
            case IO_SPACE_COMMAND: {
                /*io space */
                unsigned long arg;
                result = getArg(&arg);
                if (result) {
                    continue;
                }
                sendIOSpace(arg);
                putDebugChar(END);
            }
            break;
            case RQ_COMMAND: {
                /*runqueues */
                sendRunqueues();
                putDebugChar(END);
                result = 0;
            }
            break;
            case EP_COMMAND: {
                /*endpoint waiters */
                unsigned long arg;
                result = getArg(&arg);
                if (result) {
                    continue;
                }
                sendEPQueue(arg);
                putDebugChar(END);
            }
            break;
            case CN_COMMAND: {
                /*cnode */
                unsigned long address, sizebits;
                result = getArg(&address);
                if (result) {
                    continue;
                }
                result = getArg(&sizebits);
                if (result) {
                    continue;
                }

                sendCNode(address, sizebits);
                putDebugChar(END);
            }
            break;
            case IRQ_COMMAND: {
                sendIRQNode();
                putDebugChar(END);
                result = 0;
            }
            break;
            case VERSION_COMMAND: {
                sendVersion();
                putDebugChar(END);
            }
            break;
            case DONE: {
                done = 1;
                putDebugChar(END);
            }
            default:
                result = 0;
                break;
            }
        } while (result);
    }
}
Exemplo n.º 8
0
int main(int argc, char *argv[]) {
	int ret; //fuer getopt funktion
	char player = '3';
	char gameId[15];
	char *confDateiName = malloc(256);
	strcpy(confDateiName, "client.conf");
	pid_t pid;

  //Config-Datei einlesen und struct betanken
	log_printf(LOG_DEBUG,"Using config-file %s\n",confDateiName);
	configstruct = get_config(confDateiName);

	log_printf(LOG_PRINTF,"\n");

	//11-stellige Game-Id aus Kommandozeile auslesen
	if (argc < 2) {
		printf("Keine Game-Id angegeben!\n");
		help();
		exit(EXIT_FAILURE);
	}
	strcpy(gameId,argv[1]);
	
	if(strlen(gameId) != 11) {
		printf("Game-Id muss 11-stellig sein!\n");
		help();
		exit(EXIT_FAILURE);
	}

	//optional gewunschte Spielernummer, config Dateiname oder log Level einlesen 
	while ((ret=getopt(argc, argv, "p:c:l:")) != -1) {
	switch (ret) {
	case 'p':
		player = optarg[0];
		if (player!='0' && player != '1') {
			printf("Es gibt nur 2 Spieler! 0 oder 1 eingeben!\n");
			help();
			exit(EXIT_FAILURE);
		}
		break;
	case 'c':
		strcpy(confDateiName, optarg);
		break;
	case 'l':
		configstruct.loglevel = atoi(optarg);
		break;
	default:
		help();
		exit(EXIT_FAILURE);
	}
	}

	//Shared-Memory erstellen 
	//shmSegment() um die ID zu erstellen -> vor fork()
	int shmid = shmSegment(sizeof(struct shmInfos));

	//shmAnbinden(shmid); um es an den Prozess zu binden
	shmPtr = shmAnbinden(shmid);

	//shm automatisch entfernen, wenn alle prozesse detached sind
	shmDelete(shmid);
	
	//Pipe anlegen
	int pipe_fd[2];
	if(pipe(pipe_fd)<0){
		log_printf(LOG_ERROR,"Fehler bei Pipe anlegen");
	};

	// zweiten Prozess erstellen.
	// Connector ist der Kindprozess
	// Thinker der Elternprozess
	switch (pid = fork ()) {
	case -1:
		log_printf (LOG_ERROR,"Fehler bei fork()\n");
		break;
	case 0: // Connector
		shmPtr->pid1=pid;
		char *getText;
		
		//Verbindung mit Server herstellen
		netConnect(configstruct.port, configstruct.hostname);

		while (1) {
			getText = netReadLine();

			if (strncmp(getText, "+ MNM ",6) == 0) {
				//+ MNM Gameserver v1.0 accepting connections
				sendVersion();
			} else if (strncmp(getText, "+ Clie",6) == 0) {
				//+ Client version accepted - please send Game-ID to join
				sendGameId(gameId);
			} else if (strncmp(getText, "+ PLAY",6) == 0) {
				//+ PLAYING Quarto
				parseGamekind(getText, shmPtr);
				sendPlayer(player, shmPtr);
			} else if (strncmp(getText, "+ ENDP",6) == 0) {
				//+ ENDPLAYERS
				//noop
			} else if (strncmp(getText, "+ MOVE",6) == 0) {
				//+ MOVE 3000
				parseMovetimeout(getText, shmPtr);
			} else if (strncmp(getText, "+ NEXT",6) == 0) {
				//+ NEXT 7
				parseNext(getText, shmPtr);
			} else if (strncmp(getText, "+ FIEL",6) == 0) {
				//+ FIELD 4,4
				parseField(getText);
			} else if (strncmp(getText, "+ ENDF",6) == 0) {
				//+ ENDFIELD
        if (shmPtr->gameover != 1) {
  				sendThinking();
        }
			} else if (strncmp(getText, "+ OKTH",6) == 0) {
				
				//Hier Zug erhalten und per sendMove(stein, naechsterstein) senden
				if(ueberwacheFd(pipe_fd,getText)==1){
					log_printf(LOG_DEBUG,"Gandalf hat gesprochen und wurde vor dem ertrinken gerettet!\n");
					sendMove(getText);
				}
				else{
					log_printf(LOG_PRINTF,"Gandalf ist ersoffen\n");
				}
			} else if (strncmp(getText, "+ WAIT",6) == 0) {
				//+ WAIT
				sendOkwait();
			} else if (strncmp(getText, "+ GAME",6) == 0) {
				//+ GAMEOVER [[ hh Spielernummer des Gewinners ii hh Spielername des Gewinners ii ]]
        shmPtr->gameover = 1;
				parseGameover(getText);
			} else if (strncmp(getText, "+ QUIT",6) == 0) {
				//+ QUIT
				netDisconnect();
				break;
			} else if (strncmp(getText, "-",1) == 0) {
				//Well, f**k.

				//aufraeumen + signal an parent schicken, damit der sich beendet
				netDisconnect();
				free(confDateiName);
				kill(getppid(),SIGCHLD);
				break;
			}
		}

		break;

	default: // Thinker
		
		shmPtr->pid0=pid;

		//wenn das Signal kommt, dass er denken soll
		signal(SIGUSR1, signalHandler);
		//wenn das Signal vom Kind kommt, dass er sich beenden soll (wegen Fehler)
		signal(SIGCHLD, endHandler);
		
		while (1){
			// Auf Signal warten	
			pause();
			
			log_printf(LOG_DEBUG,"thinker hat fertig gedacht\n");
			// In die Pipe schreiben
			pipe_write(pipe_fd);
		}

		if (wait (NULL) != pid) {
			log_printf(LOG_ERROR,"Fehler beim Warten auf den Kindprozess\n");
			return EXIT_FAILURE;
		}
		break;
	}

	return 0;
}
Exemplo n.º 9
0
int
xmsgServerMain() {
    int status = 0;
    rsComm_t rsComm;
    rsComm_t svrComm;	/* rsComm is connection to icat, svrComm is the
                         * server's listening socket */
    fd_set sockMask;
    int numSock;

    initThreadEnv();
    initXmsgHashQue();

    status = startXmsgThreads();

    if ( status < 0 ) {
        rodsLog( LOG_ERROR,
                 "xmsgServerMain: startXmsgThreads error. status = %d", status );
        return status;
    }

    status = initRsComm( &rsComm );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "xmsgServerMain: initRsComm error. status = %d",
                 status );
        return status;
    }

    status = initRsComm( &svrComm );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "xmsgServerMain: initRsComm error. status = %d",
                 status );
        return status;
    }

    status = initAgent( RULE_ENGINE_NO_CACHE, &rsComm );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "xmsgServerMain: initAgent error. status = %d",
                 status );
        return status;
    }


    // =-=-=-=-=-=-=-
    // handle negotiations with the client regarding TLS if requested
    irods::error ret;

    // =-=-=-=-=-=-=-
    // manufacture a network object for comms
    irods::network_object_ptr net_obj;
    ret = irods::network_factory( &rsComm, net_obj );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
    }

    std::string neg_results;
    ret = irods::client_server_negotiation_for_server( net_obj, neg_results );
    if ( !ret.ok() || neg_results == irods::CS_NEG_FAILURE ) {
        irods::log( PASS( ret ) );
        // =-=-=-=-=-=-=-
        // send a 'we failed to negotiate' message here??
        // or use the error stack rule engine thingie
        irods::log( PASS( ret ) );
        sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
        cleanupAndExit( ret.code() );

    }
    else {
        // =-=-=-=-=-=-=-
        // copy negotiation results to comm for action by network objects
        snprintf( rsComm.negotiation_results, sizeof( rsComm.negotiation_results ),
                  "%s", neg_results.c_str() );
        //rsComm.ssl_do_accept = 1;

    }

    int xmsg_port = 0;
    ret = irods::get_server_property<
          int > (
              irods::CFG_XMSG_PORT,
              xmsg_port );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return ret.code();

    }

    /* open  a socket and listen for connection */
    svrComm.sock = sockOpenForInConn(
                       &svrComm,
                       &xmsg_port,
                       NULL,
                       SOCK_STREAM );

    if ( svrComm.sock < 0 ) {
        rodsLog( LOG_NOTICE, "xmsgServerMain: sockOpenForInConn error. status = %d",
                 svrComm.sock );
        exit( 1 );
    }

    listen( svrComm.sock, MAX_LISTEN_QUE );

    FD_ZERO( &sockMask );

    rodsLog( LOG_NOTICE, "xmsgServer version %s is up", RODS_REL_VERSION );

    while ( 1 ) {       /* infinite loop */
        FD_SET( svrComm.sock, &sockMask );
        while ( ( numSock = select( svrComm.sock + 1, &sockMask,
                                    ( fd_set * ) NULL, ( fd_set * ) NULL, ( struct timeval * ) NULL ) ) < 0 ) {

            if ( errno == EINTR ) {
                rodsLog( LOG_NOTICE, "xmsgServerMain: select() interrupted" );
                FD_SET( svrComm.sock, &sockMask );
                continue;
            }
            else {
                rodsLog( LOG_NOTICE, "xmsgServerMain: select() error, errno = %d", errno );
                return -1;
            }
        }

        const int newSock = rsAcceptConn( &svrComm );

        if ( newSock < 0 ) {
            rodsLog( LOG_NOTICE,
                     "xmsgServerMain: acceptConn () error, errno = %d", errno );
            continue;
        }

        addReqToQue( newSock );

        if ( loopCnt > 0 ) {
            loopCnt--;
            if ( loopCnt == 0 ) {
                return 0;
            }
        }


    }
    return 0;
}
Exemplo n.º 10
0
bool UserPlugin::onIq(gloox::Stanza* s)
{
	QString xmlns=QString::fromStdString(s->xmlns());
	AsyncRequest* req=bot()->asyncRequests()->byStanza(s);

	if (s->subtype()==gloox::StanzaIqGet)
	{
		if (s->subtype()!=gloox::StanzaIqResult && xmlns=="jabber:iq:version")
		{
			//We should send our version
			sendVersion(s);
			return true;
		}
		if (xmlns=="http://jabber.org/protocol/disco#items")
		{
			//Disco items request. Report error;
			gloox::Stanza *st=gloox::Stanza::createIqStanza(s->from(),
					s->findAttribute("id"), gloox::StanzaIqError,
					xmlns.toStdString());
			bot()->client()->send(st);
		}
		if (s->subtype() != gloox::StanzaIqResult && xmlns=="jabber:iq:time" )
		{
			//We should send our time (XEP-0090)
			sendTime(s);
			return true;
		}
		if (req)
			bot()->asyncRequests()->removeAll(req);
		return true;
	}

	if (!req)
		return false;
	if (req->plugin()!=this)
		return false;

	gloox::Tag* query=s->findChild("query", "xmlns", xmlns.toStdString());
	if (!query)
	{
		reply(req->stanza(), "Error");
		bot()->asyncRequests()->removeAll(req);
		delete req;
		return true;
	}
	if (xmlns=="jabber:iq:time")
	{
		QString msg, time;
		QString src = bot()->JIDtoNick(QString::fromStdString(s->from().full()));

		gloox::Tag *display = query->findChild("display");

		if(display) {
			assert(display);
			time = QString::fromStdString(display->cdata());
		}

		if( time.isEmpty() )
		{
			gloox::Tag *tz = query->findChild("tz");
			if(tz) {
				assert(tz);
				time = QString::fromStdString(tz->cdata());
			}
		}
		if( time.isEmpty() )
		{
			gloox::Tag *utc = query->findChild("utc");
			if(utc) {
				assert(utc);
				QString time = utcToString(
					QString::fromStdString(utc->cdata()).trimmed(),
					"ddd, dd MMM yyyy HH:mm:ss");

				msg=QString("at %1 there is %2 +0000")
					.arg(QString::fromStdString(s->from().full()))
					.arg(time);
			}
		}
		else {
			if ( msg.isEmpty() && src.isEmpty() )
				msg=QString("It's %1 on your watch").arg(time);
			else if( msg.isEmpty() )
				msg=QString("It's %1 on %2's watch").arg(time).arg(src);
			if( time.isEmpty() )
				msg="responce with no data.";

		}
		if( s->subtype()==gloox::StanzaIqResult && s->error() == gloox::StanzaErrorUndefined )
			reply( req->stanza(), msg );
		else if( s->error() == gloox::StanzaErrorRemoteServerNotFound )
			reply( req->stanza(), "Recipient is not in the conference room" );
		else if( s->error() == gloox::StanzaErrorFeatureNotImplemented )
			reply( req->stanza(), "Feature Not Implemented" );
		else reply( req->stanza(), "Unable to get time" );
	}
	if (xmlns=="jabber:iq:version")
	{
		if (req->name()=="PING")
		{
			QString msg;
			QString src=bot()->JIDtoNick(QString::fromStdString(s->from().full()));
			double delay=(double)req->time().time().msecsTo(QTime::currentTime());
			delay/=1000.0;

			if (s->subtype()==gloox::StanzaIqResult)
				msg=QString("Pong from %1 after %2 secs.").arg(src).arg(delay);
			else
				msg=QString("Pong from %1's server after %2 secs.").arg(src).arg(delay);
			reply(req->stanza(), msg);
		}
		else if (s->subtype()==gloox::StanzaIqResult)
		{
			QString name;
			QString version;
			QString os;
			gloox::Tag* t;

			t=query->findChild("name");
			if (t)
				name=QString::fromStdString(t->cdata());
			t=query->findChild("version");
			if (t)
				version=QString::fromStdString(t->cdata());
			t=query->findChild("os");
			if (t)
				os=QString::fromStdString(t->cdata());
			QString res=name;
			if (!version.isEmpty())
				res+=QString(" %1").arg(version);
			if (!os.isEmpty())
				res+=QString(" // %1").arg(os);

			QString src=bot()->JIDtoNick(QString::fromStdString(s->from().full()));
			if (!src.isEmpty())
				src+=" uses ";
			src+=res;

			reply(req->stanza(), src);
		}
		else
		{
			//TODO: Error handling
			reply(req->stanza(), "Unable to get version");
		}
	}
	if (xmlns=="http://jabber.org/protocol/disco#items")
	{
		if (s->subtype()==gloox::StanzaIqError)
			reply(req->stanza(), "Unable to query");
		else
		{
			QList<gloox::Tag*> lst=
					QList<gloox::Tag*>::fromStdList(query->children());
			QStringList strings;
			bool safeJid=req->name().indexOf('@')<0;
			int noval=0;
			for (int i=0; i<lst.count(); i++)
			{
				QString name=
						QString::fromStdString(lst[i]->findAttribute("name"));
				QString jid=
						QString::fromStdString(lst[i]->findAttribute("jid"));
				if (name.isEmpty())
					name=jid;
				if (name.isEmpty())
					continue;
				QString cnt=getValue(name, "^.*\\(([^\\)]+)\\)$");
				if (cnt.isEmpty())
				{
					cnt="0";
					noval++;
				}
				else
					name=getValue(name,"^(.*)\\([^\\)]+\\)$").trimmed();
				bool ok=true;
				cnt.toInt(&ok);
				if (!ok)
					cnt="0";
				cnt=cnt.rightJustified(8, '0', true);
				if (name!=jid && safeJid)
					name+=QString(" [%1]").arg(jid);
				strings.append(QString("%1 %2").arg(cnt).arg(name));
			}
			strings.sort();
			QStringList replyList;
			bool haveValues;
			if (lst.count())
			{
				double perc=((double)noval)/((double)(lst.count()));
				haveValues=perc<0.2;
			}

			int idx=strings.count()-1;
			for (int i=0; i<strings.count(); i++)
			{
				int curIdx=haveValues ? idx : i;
				int value=strings[curIdx].section(' ',0,0).toInt();
				QString name=strings[curIdx].section(' ', 1);
				idx--;
				QString item=QString("%1) %2").arg(i+1).arg(name);
				if (haveValues)
					item+=QString(": %1").arg(value);
				replyList.append(item);
				if (replyList.count()>=100)
				{
					replyList.append("...");
					break;
				}
			}
			reply(req->stanza(), "Disco items:\n"+replyList.join("\n"));
		}
	}
	if (xmlns=="http://jabber.org/protocol/stats")
	{
		// Got statistic to display?
		if (s->subtype()==gloox::StanzaIqError)
			reply(req->stanza(), "Unable to query");
		else
		{
			std::list<gloox::Tag*> childList=query->children();
			QStringList statItemList;
			bool haveValues=true;
			for (std::list<gloox::Tag*>::iterator it=childList.begin(); it!=childList.end(); ++it)
			{
				gloox::Tag* child=*it;
				if (child->name()!="stat")
					continue;
				QString item=QString::fromStdString(child->findAttribute("name"));
				QString value=QString::fromStdString(child->findAttribute("value"));
				if (!value.isEmpty())
				{
					item+=QString(": %1").arg(value);
					QString units=QString::fromStdString(child->findAttribute("units"));
					if (!units.isEmpty())
						item+=QString(" %1").arg(units);
				}
				else
				{
					gloox::Tag* err=child->findChild("error");
					if (err)
					{
						value=QString::fromStdString(err->cdata());
						if (value.isEmpty())
							value=QString::fromStdString(err->xml());
						item+=QString(": %1").arg(value);
					}
				}
				if (value.isEmpty())
					haveValues=false;
				statItemList.append(item);
			}
			if (req->name()=="STAT" && !haveValues)
			{
				// Resubmit query with values information
				std::string id=bot()->client()->getID();
				gloox::Stanza *st2=gloox::Stanza::createIqStanza(s->from(),
					id, gloox::StanzaIqGet, xmlns.toStdString());
				gloox::Tag* query2=st2->findChild("query", "xmlns", xmlns.toStdString());
				assert(query2);
				for (QStringList::iterator it=statItemList.begin(); it!=statItemList.end(); ++it)
				{
					QString statItem=*it;
					query2->addChild(new gloox::Tag("stat","name",statItem.toStdString()));
				}
				st2->finalize();
				gloox::Stanza *sf=new gloox::Stanza(req->stanza());
				sf->addAttribute("id", id);
				AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600);
				req->setName("STAT2");
				bot()->asyncRequests()->append(req);
				bot()->client()->send(st2);
			}
			else
			{
				reply(req->stanza(), QString("Statistic:\n%1").arg(statItemList.join("\n")));
			}
		}
	}

	if (xmlns=="jabber:iq:last")
	{
		QString value=QString::fromStdString(query->findAttribute("seconds"));
		bool ok=true;
		int res=value.toInt(&ok);
		if (ok==false || value.isEmpty())
			reply(req->stanza(),"Unable to query");
		else
			reply(req->stanza(), secsToString(res));
	}

	bot()->asyncRequests()->removeAll(req);
	delete req;
	return true;
}
Exemplo n.º 11
0
int
main(int argc, char **argv)
{
    int     team, s_type;
    char   *dpyname = NULL;
    int     usage = 0;
    int     err = 0;
    char   *name, *ptr, *cp;
    struct passwd *pwent;
    int     passive = 0;
    int     xpmopt = 1;
    int     useORopt = 0;
    int     useCookieOpt = 0;
    int     dontUseCookieOpt = 0;
/*    char *defaultsFile=NULL;*/

    pseudo[0] = defpasswd[0] = '\0';

    name = *argv++;
    argc--;
    if ((ptr = strrchr(name, '/')) != NULL)
	name = ptr + 1;
    while (*argv) {
	if (**argv != '-') {
	    serverName = *argv;	/* don't abort argument processing */
	    argv++;
	    argc--;
	} else {
	    ++*argv;

	    argc--;
	    ptr = *argv++;
	    while (*ptr) {
		switch (*ptr) {
		case 'C':	/* character name */
		    (void) strncpy(pseudo, *argv, sizeof(pseudo));
		    argv++;
		    argc--;
		    break;

		case 'P':	/* authorization password */
		    (void) strncpy(defpasswd, *argv, sizeof(defpasswd));
		    {
			int     i;
			for (i = 0; (*argv)[i]; i++)
			    (*argv)[i] = 0;
		    }
		    argv++;
		    argc--;
		    break;

		case 'u':
		    usage++;
		    break;
		case 's':
		    if (*argv) {
			xtrekPort = atoi(*argv);
			passive = 1;
			argv++;
			argc--;
		    }
		    break;
		case 'p':
		    if (*argv) {
			xtrekPort = atoi(*argv);
			argv++;
			argc--;
		    }
		    break;
		case 'd':
		    dpyname = *argv;
		    argc--;
		    argv++;
		    break;
		case 'm':
		    usemeta = 1;
		    break;
		case 'h':
		    serverName = *argv;
		    argc--;
		    argv++;
		    break;

		case 't':
		    title = *argv;
		    argc--;
		    argv++;
		    break;
		case 'r':
		    defaultsFile = *argv;
		    argv++;
		    argc--;
		    break;
#ifdef AUTHORIZE
		case 'o':
		    RSA_Client = -1;
		    break;
		case 'R':
		    RSA_Client = -2;
		    break;
#else
		case 'o':
		case 'R':
		    printf("This client does not have binary authorization.\n");
		    break;
#endif
		case 'e':
#ifdef AUTHORIZE
		    checkExpire(1);
#else
		    printf("This client does not RSA verify and will not expire.\n");
#endif
		    exit(0);
		    break;
		case 'f':	/* list ftp sites */
		    fprintf(stderr, "\n\
The newest version of the Paradise client can be found at:\n\
      ftp.netrek.org  in /pub/netrek/paradise/bin/\n");
		    exit(0);
		case 'G':
		    if (*argv) {
			ghoststart++;
			ghost_pno = atoi(*argv);
			printf("Emergency restart being attempted...\n");
			argv++;
			argc--;
		    }
		    break;
		case '2':	/* force paradise */
		    paradise = 1;
		    break;
		case 'F':	/* File playback */
		    if (*argv) {
			playFile = strdup(*argv);
			playback = 1;
			argv++;
			argc--;
		    }
		    break;
		case 'x':
		    xpmopt = 0;
		    break;
		case 'k':		/* cookie mode [BDyess] */
		    useCookieOpt = 1;
		    break;
		case 'K':		/* no-cookies :( [BDyess] */
		    dontUseCookieOpt = 1;
		    break;
		case 'v':
		    verbose_image_loading = 1;
		    break;
		case 'O':		/* turn on GXor image drawing [BDyess]*/
		    useORopt = 1;	
		    break;
                case 'c': 	/* dump .paradiserc defaults [BDyess] */
		    dump_defaults = 1;
		    break;
		default:
		    fprintf(stderr, "%s: unknown option '%c'\n", name, *ptr);
		    err++;
		    break;
		}
		ptr++;
	    }
	}
    }

    inittrigtables();

    initStars();		/* moved from redraw.c at KAO\'s suggestion */

    if (usage || err) {
	printUsage(name);
#ifdef AUTHORIZE
	checkExpire(1);
#endif
	exit(0);
	/* exit(err); Exits from checkExpire */
    }
    defaultsFile = initDefaults(defaultsFile);

    if(xpmopt) xpm = 1;
    else xpm = booleanDefault("xpm",xpm);
    if(xpm) printf("XPM mode enabled.\n");
    /* command line option overrides .paradiserc value [BDyess] */
    if(useORopt) useOR = 1;
    else useOR = booleanDefault("useOR",useOR);
    if(useOR) printf("OR mode enabled.\n");
    if(useOR || !xpm) cookie = 0;	/* default no-cookies unless in XPM
    					   mode w/out OR [BDyess] */
					/* note: need a milk mode :) */
    if(useCookieOpt) cookie = 1;
    else if(dontUseCookieOpt) cookie = 0;
    else cookie = booleanDefault("cookie",cookie);
    if(cookie) printf("Cookie mode enabled.\n");

#ifdef AUTHORIZE
    if (RSA_Client != -1)
	checkExpire(0);
#endif

    /* compatability */
    if (argc > 0)
	serverName = argv[0];

    srandom(getpid() + time((long *) 0));

    if(playback || booleanDefault("playback",0)) {
        defNickName = "playback";
	usemeta=0;
        serverName = "playback";
    } else
    {
        if (serverName) {
	    char    temp[80], *s;
	    sprintf(temp, "server.%s", serverName);
	    if ((s = stringDefault(temp,NULL))) {
		printf("Using nickname \"%s\" for server %s\n", serverName, s);
		defNickName = serverName;
		serverName = s;
		defFlavor = stringDefault("flavor",NULL);
	    }
	}
	if (!serverName) {
	    serverName = stringDefault("server",NULL);
        }
	if (!serverName && !passive) {
	    serverName = DEFAULT_SERVER;
	    usemeta = 1;		/* no server specified, show the menu */
	}
	if (passive)
	    serverName = "passive";	/* newwin gets a wrong title otherwise */

	if (xtrekPort < 0)
	    xtrekPort = intDefault("port", -1);
	if (xtrekPort < 0)
	    xtrekPort = DEFAULT_PORT;
    } /* playback */
    build_default_configuration();

    metaserverAddress = stringDefault("metaserver",
				      "metaserver.netrek.org");
    if (usemeta)
	openmeta();

    W_Initialize(dpyname);

    metaFork = booleanDefault("metaFork", metaFork);
    /* do the metawindow thang */
    if (usemeta) {
	metawindow();
	metainput();
	if (metaFork)
	    W_Initialize(dpyname);
	newwin(dpyname, name);
    } else

	/* this creates the necessary x windows for the game */
	newwin(dpyname, name);

    /* open memory...? */
    openmem();
    if (!startPlayback())
    {
	if (!passive) {
	    serverName = callServer(xtrekPort, serverName);
	} else {
	    connectToServer(xtrekPort);
	}
    }
    sendFeature("FEATURE_PACKETS", 'S', 1, 0, 0);

    timeStart = time(NULL);
    findslot();

    /* sets all the settings from defaults file (.xtrekrc probably) */
    resetDefaults();

#ifdef UNIX_SOUND
    init_sound();
    play_sound(SND_PARADISE);
#endif

    mapAll();
/*    signal(SIGINT, SIG_IGN);*/
    signal(SIGCHLD, reaper);

    /* Get login name */
    if ((pwent = getpwuid(getuid())) != NULL)
	(void) strncpy(login, pwent->pw_name, sizeof(login));
    else
	(void) strncpy(login, "Bozo", sizeof(login));
    login[sizeof(login) - 1] = '\0';

    if (pseudo[0] == '\0') {
	char *freeme;
	strncpy(pseudo, freeme = stringDefault("name",login), sizeof(pseudo));
	free(freeme);
    }
    pseudo[sizeof(pseudo) - 1] = '\0';

    if (defpasswd[0] == '\0') {
	char buf[100];  /* added password by character name -JR */
	sprintf(buf,"password.%s",pseudo);
	if((cp = stringDefault(buf,NULL)) || (cp = stringDefault("password",NULL)))
	    (void) strncpy(defpasswd, cp, sizeof(defpasswd));
    }
    defpasswd[sizeof(defpasswd) - 1] = '\0';

    /*
       sendLoginReq("Gray Lensman", "hh", "sfd", 0); loginAccept = -1; while
       (loginAccept == -1) { socketPause(1,0); readFromServer(); }
    */
    getname(pseudo, defpasswd);
    loggedIn = 1;

    /*
       Set p_hostile to hostile, so if keeppeace is on, the guy starts off
       hating everyone (like a good fighter should)
    */
    me->p_hostile = (1 << number_of_teams) - 1;

    redrawTstats();

    me->p_planets = 0;
    me->p_genoplanets = 0;
    me->p_armsbomb = 0;
    me->p_genoarmsbomb = 0;
    /* Set up a reasonable default */
    me->p_whydead = KNOREASON;
    me->p_teami = -1;
    s_type = defaultShip(CRUISER);	/* from rlb7h 11/15/91 TC */

    if (booleanDefault("netStats", 1))
	startPing();		/* tell the server that we support pings */

    /*
       hack to make galaxy class ships work.  This could be more elegant, but
       the configuration code would have to be modified quite a bit, since
       the client doesn't know if it's on a paradise server until after it
       connects, and it needs the configuration info before it connects.
    */
    init_galaxy_class();

    initkeymap(-1);		/* needs to have ship types initialized -JR */

    setjmp(env);		/* Reentry point of game */

    if (ghoststart) {
	int     i;

	ghoststart = 0;

	for (i = -1; i < 5; i++)
	    if (teaminfo[i].letter == me->p_mapchars[0])
		break;

	me->p_teami = i;

	if (me->p_damage > me->p_ship->s_maxdamage) {
	    me->p_status = POUTFIT;
	} else
	    me->p_status = PALIVE;
    } else
	me->p_status = POUTFIT;

    while (1) {
	switch (me->p_status) {
	case POUTFIT:
	case PTQUEUE:
	    /* give the player the motd and find out which team he wants */
	    new_entrywindow(&team, &s_type);
	    allowPlayerlist = 1;
	    if (W_IsMapped(playerw))
		playerlist();

	    if (!playback)
		if (team == -1) {
		    W_DestroyWindow(w);
		    sendByeReq();
		    sleep(1);
		    printf("OK, bye!\n");
		    EXIT(0);
		}
	    sendVersion();
	    myship = getship(myship->s_type);

	    currentship = myship->s_type;

	    /*
	       sendOptionsPacket(); this would totally blast any flags you
	       had on the server
	    */

	    redrawall = 1;
	    enter();
	    calibrate_stats();
	    W_ClearWindow(w);
	    /*
	       for (i = 0; i < NSIG; i++) { signal(i, SIG_IGN); }
	    */

	    me->p_status = PALIVE;	/* Put player in game */

#ifdef UNIX_SOUND
            kill_sound ();
#endif
            
	    hockeyInit();

	    if (showStats)	/* Default showstats are on. */
		W_MapWindow(statwin);
	    if (showNewStats)	/* default showNewStats are off. [BDyess] */
	        W_MapWindow(newstatwin);

	    if (tryUdp && commMode != COMM_UDP) {
		sendUdpReq(COMM_UDP);
	    }

	    if (tryShort) {
		sendShortReq(SPK_VON);
		tryShort = 0;	/* only try it once */
	    }
	    /* Send request for a full update */
	    if (askforUpdate) {
		if(recv_short)
		    sendShortReq(SPK_SALL);
		else
		    sendUdpReq(COMM_UPDATE);
	    }
	    sendUpdatePacket(1000000 / updateSpeed);

	    W_Deiconify(baseWin);

	    break;
	case PALIVE:
	case PEXPLODE:
	case PDEAD:
	case POBSERVE:

	    /* Get input until the player quits or dies */
	    input();
	    W_ClearWindow(mapw);
	    break;
	default:
	    printf("client has p_status=%d.  how strange\n", me->p_status);
	    me->p_status = POUTFIT;
	}
    }

    /* NOTREACHED */
}
Exemplo n.º 12
0
/* #define SERVER_DEBUG 1   */
int
main( int, char ** ) {

    int status;
    rsComm_t rsComm;
    char *tmpStr;

    ProcessType = AGENT_PT;

    // capture server properties
    irods::server_properties& props = irods::server_properties::getInstance();
    irods::error result = props.capture_if_needed();
    if ( !result.ok() ) {
        irods::log( PASSMSG( "failed to read server configuration", result ) );
    }

#ifdef windows_platform
    iRODSNtAgentInit( argc, argv );
#endif

#ifndef windows_platform
    signal( SIGINT, signalExit );
    signal( SIGHUP, signalExit );
    signal( SIGTERM, signalExit );
    /* set to SIG_DFL as recommended by andy.salnikov so that system()
     * call returns real values instead of 1 */
    signal( SIGCHLD, SIG_DFL );
    signal( SIGUSR1, signalExit );
    signal( SIGPIPE, SIG_IGN );

    // register irods signal handlers
    register_handlers();
#endif

#ifndef windows_platform
#ifdef SERVER_DEBUG
    if ( isPath( "/tmp/rodsdebug" ) ) {
        sleep( 20 );
    }
#endif
#endif

    memset( &rsComm, 0, sizeof( rsComm ) );
    rsComm.thread_ctx = ( thread_context* )malloc( sizeof( thread_context ) );

    status = initRsCommWithStartupPack( &rsComm, NULL );

    // =-=-=-=-=-=-=-
    // manufacture a network object for comms
    irods::network_object_ptr net_obj;
    irods::error ret = irods::network_factory( &rsComm, net_obj );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
    }

    if ( status < 0 ) {
        sendVersion( net_obj, status, 0, NULL, 0 );
        cleanupAndExit( status );
    }

    /* Handle option to log sql commands */
    tmpStr = getenv( SP_LOG_SQL );
    if ( tmpStr != NULL ) {
#ifdef SYSLOG
        int j = atoi( tmpStr );
        rodsLogSqlReq( j );
#else
        rodsLogSqlReq( 1 );
#endif
    }

    /* Set the logging level */
    tmpStr = getenv( SP_LOG_LEVEL );
    if ( tmpStr != NULL ) {
        int i;
        i = atoi( tmpStr );
        rodsLogLevel( i );
    }
    else {
        rodsLogLevel( LOG_NOTICE ); /* default */
    }

#ifdef SYSLOG
    /* Open a connection to syslog */
    openlog( "rodsAgent", LOG_ODELAY | LOG_PID, LOG_DAEMON );
#endif
    status = getRodsEnv( &rsComm.myEnv );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "agentMain :: getRodsEnv failed" );
        sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
        cleanupAndExit( status );
    }

    ret = setRECacheSaltFromEnv();
    if ( !ret.ok() ) {
        rodsLog( LOG_ERROR, "rodsAgent::main: Failed to set RE cache mutex name\n%s", ret.result().c_str() );
        exit( 1 );
    }

    // =-=-=-=-=-=-=-
    // load server side pluggable api entries
    irods::api_entry_table&  RsApiTable   = irods::get_server_api_table();
    irods::pack_entry_table& ApiPackTable = irods::get_pack_table();
    ret = irods::init_api_table(
              RsApiTable,
              ApiPackTable,
              false );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return 1;
    }

    // =-=-=-=-=-=-=-
    // load client side pluggable api entries
    irods::api_entry_table&  RcApiTable = irods::get_client_api_table();
    ret = irods::init_api_table(
              RcApiTable,
              ApiPackTable,
              true );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return 1;
    }




#if RODS_CAT
    if ( strstr( rsComm.myEnv.rodsDebug, "CAT" ) != NULL ) {
        chlDebug( rsComm.myEnv.rodsDebug );
    }
#endif

    status = initAgent( RULE_ENGINE_TRY_CACHE, &rsComm );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR, "agentMain :: initAgent failed: %d", status );
        sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
        cleanupAndExit( status );
    }

    /* move configConnectControl behind initAgent for now. need zoneName if
     * the user does not specify one in the input */
    initConnectControl();

    if ( rsComm.clientUser.userName[0] != '\0' ) {
        status = chkAllowedUser( rsComm.clientUser.userName,
                                 rsComm.clientUser.rodsZone );

        if ( status < 0 ) {
            sendVersion( net_obj, status, 0, NULL, 0 );
            cleanupAndExit( status );
        }
    }

    // =-=-=-=-=-=-=-
    // handle negotiations with the client regarding TLS if requested
    // this scope block makes valgrind happy
    {
        std::string neg_results;
        ret = irods::client_server_negotiation_for_server( net_obj, neg_results );
        if ( !ret.ok() || neg_results == irods::CS_NEG_FAILURE ) {
            irods::log( PASS( ret ) );
            // =-=-=-=-=-=-=-
            // send a 'we failed to negotiate' message here??
            // or use the error stack rule engine thingie
            irods::log( PASS( ret ) );
            sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
            cleanupAndExit( ret.code() );

        }
        else {
            // =-=-=-=-=-=-=-
            // copy negotiation results to comm for action by network objects
            snprintf( rsComm.negotiation_results, sizeof( rsComm.negotiation_results ), "%s", neg_results.c_str() );
            //rsComm.ssl_do_accept = 1;

        }
    }

    /* send the server version and atatus as part of the protocol. Put
     * rsComm.reconnPort as the status */
    ret = sendVersion( net_obj, status, rsComm.reconnPort,
                       rsComm.reconnAddr, rsComm.cookie );

    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 );
        cleanupAndExit( status );
    }

    logAgentProc( &rsComm );

    // call initialization for network plugin as negotiated
    irods::network_object_ptr new_net_obj;
    ret = irods::network_factory( &rsComm, new_net_obj );
    if ( !ret.ok() ) {
        return ret.code();
    }

    ret = sockAgentStart( new_net_obj );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return ret.code();
    }

    new_net_obj->to_server( &rsComm );
    status = agentMain( &rsComm );

    // call initialization for network plugin as negotiated
    ret = sockAgentStop( new_net_obj );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return ret.code();
    }

    new_net_obj->to_server( &rsComm );
    cleanup();
    free( rsComm.thread_ctx );
    free( rsComm.auth_scheme );
    rodsLog( LOG_NOTICE, "Agent exiting with status = %d", status );
    return status;
}