Exemplo n.º 1
0
//再接続します。
void CIRCService::reconnect(void)
{
    if (m_state ==CChatServiceBase::DISCONNECT){
        // 通信を初期化
        CIRCConnection *newConnection = new CIRCConnection;

        newConnection->init(m_id, m_handler);
        newConnection->setHost(m_connect->getHost());
        newConnection->setPort(m_connect->getPort());
        // 前回接続済みのユーザーがサーバー側で切断の完了になってない場合があるので、ユーザー名を変更。
        m_user->setUserName(m_user->getUserName() + "_");

        vector<wxString> channelNames;
        vector<CChannelStatus*> channels = getChannels();
        vector<CChannelStatus*>::iterator it = channels.begin();
        while (it != channels.end()){
            channelNames.push_back((*it)->getChannelName());
            it++;
        }
        this->setSavedChannels(channelNames);
        delete m_connect;
        m_connect = newConnection;
        registerUser(m_user->getUserName(), m_user->getBasic());
        connect();
    }
}
Exemplo n.º 2
0
Arquivo: server.c Projeto: mannias/SO
static void *
executeActions(void *arg){
	Message* msg;
	int client;
	while(1){
		pthread_mutex_lock(&mut);
		msg = popMessage();
		if(msg != NULL){
			if(strcmp(msg->resource, "login") == 0){
				if(strcmp(msg->method, "register") == 0){
					registerUser(msg);
				}else if(strcmp(msg->method, "login") == 0){
					loginUser(msg);
				}
			}else if(strcmp(msg->resource, "user") == 0){
				if(strcmp(msg->method, "fee") == 0){
					sendUserFee(msg);
				}
			}else if(strcmp(msg->resource, "mail") == 0){
				if(strcmp(msg->method, "receive") == 0){
					sendEmails(msg);
				}
			}
			client = getClientCond(msg->referer);
			pthread_cond_signal(&newData[client]);
		}
		else{
			/* Sleep until new Messages */
			printf("Stack Empty, Sleeping\n");
			pthread_cond_wait(&newMessage, &mut);
			printf("Woke up to consume Stack\n");
		}
		pthread_mutex_unlock(&mut);
	}
}
Exemplo n.º 3
0
void ChatTests::initTestCase()
{
    qRegisterMetaType<QSharedPointer<Session> >("QSharedPointer<Session>");
    qRegisterMetaType<QSharedPointer<Chat> >("QSharedPointer<Chat>");
    qRegisterMetaType<QSharedPointer<const User> >("QSharedPointer<const User>");
    qRegisterMetaType<User>("User");
    qRegisterMetaType<QList<QPair<QDateTime, QString> > >(
        "QList<QPair<QDateTime, QString> >");
    qRegisterMetaType<QList<ChatlogEntry> >("QList<ChatlogEntry>");

#ifdef RUN_SERVER
    SPAWN_SERVER(server);
#endif

    registerUser(TEMP_SESSION_USER3);
    registerUser(TEMP_SESSION_USER2);
}
Exemplo n.º 4
0
void ircInterface::onConnectionDeath()
{
	//std::cout << "ircInterface: uh-oh connection died, trying to restablish" <<std::endl;
	ircLog::instance()->logf(FILENAME, "Uh-Oh connection died, trying to restablish");

	//clean up _serverConnection
	_serverConnection->close();
	
	//try and connect again
	bool attempting = false;;
	int attempts = 0;

	if(_autoReconnect)
	{
		do
		{
			
			attempting = false;
			if(connect(_server, _port))
			{
				attempting = true;
				++attempts;
				_serverConnection->close();
				_serverConnection->sleep(AUTO_RECONN_RETRY_INTV);
				continue;

			}
			if(registerUser(_nick, _uname, _rname))
			{
				attempting = true;
				++attempts;
				_serverConnection->close();
				_serverConnection->sleep(AUTO_RECONN_RETRY_INTV);
				continue;
			}

		}
		while(attempting && attempts < MAX_AUTO_RECONN_ATTEMPTS);

		if(!attempting)
		{
			//std::cout << "ircInterface: whew, that was close but we reconnected" <<std::endl;
			ircLog::instance()->logf(FILENAME, "whew, that was close but we reconnected");
			return;
		}
	}

	//notify the client through the event handler.
	std::cerr << "ircInterface: connection lost..." << std::endl;
	ircEvent_connLost e;
	notifyEvent(e);


}
Exemplo n.º 5
0
void MusicUserDialog::firstStatckWidget()
{
    ui->userComboBox->setItemDelegate(new QStyledItemDelegate(ui->userComboBox));
    ui->userComboBox->setStyleSheet(MusicUIObject::MComboBoxStyle01 + MusicUIObject::MItemView01);
    ui->userComboBox->view()->setStyleSheet(MusicUIObject::MScrollBarStyle01);
    ui->passwLineEdit->setStyleSheet(MusicUIObject::MLineEditStyle01);
    ui->loginButton->setStyleSheet(MusicUIObject::MPushButtonStyle08);
    ui->forgotPwdButton->setStyleSheet(MusicUIObject::MPushButtonStyle09);
    ui->registerButton->setStyleSheet(MusicUIObject::MPushButtonStyle09);

    ui->registerButton->setCursor(QCursor(Qt::PointingHandCursor));
    ui->forgotPwdButton->setCursor(QCursor(Qt::PointingHandCursor));
    ui->loginButton->setCursor(QCursor(Qt::PointingHandCursor));
    connect(ui->registerButton, SIGNAL(clicked()), SLOT(registerUser()));
    connect(ui->forgotPwdButton, SIGNAL(clicked()), SLOT(userForgotPasswd()));
    connect(ui->loginButton, SIGNAL(clicked()), SLOT(checkUserLogin()));
}
Exemplo n.º 6
0
void MessageType::onRegister(netlib::connectionPtr conn,RegisterPtr message)
{
    //判断该用户名是否已经存在
    Status status;
    if(isUserExist(message,sql_))
    {
        if(!checkPassword(message))
            status.set_register_(REGISTER::REGISTER_FAIL);
    }
    else
    {
        status.set_register_(REGISTER::REGISTER_SUCCEED);
        //将新用户添加到user表中
        assert(registerUser(message,sql_));
    }
    codec_.fillEmptyBuffer(&conn->outputBuffer_,status);
    conn->send();
}
Exemplo n.º 7
0
void customer() {
    int p=1;
    do {
        printf("\n1. New User? Register!\n");
        printf("2. Old User? Login!\n");
        printf("3. Go back\n");
        printf("Enter choice: ");
        scanf("%d",&c);
        switch(c) {
        case 1:
            registerUser();
            break;
        case 2:
            login();
            break;
        case 3:
            p=0;
            break;
        default:
            printf("\nWrong choice. Enter again.\n");
        }
    } while(p);
}
Exemplo n.º 8
0
int main(int arg, char *argv[]) {
    WSMMessage rxmsg;
    WSMIndication rxpkt;
    //int i, attempts = 10, drops = 0, result;
    int ret = 0;
    struct arguments arg1;
    rxmsg.wsmIndication = &rxpkt;

    /* check for the user input arguments, if it is less than 4 print the usage message */
    if (arg < 4) {
        printf("usage: localrx [user req type<1-auto> <2-unconditional> <3-none>] [imm access] [extended access] [channel <optional>] [PROVIDER MAC <optional>]\n");
        return 0;
    }
    registerLinkConfirm(confirmBeforeJoin); /* Registering the callback function */
    pid = getpid();
    memset(&entry, 0, sizeof(WMEApplicationRequest));
    entry.psid = 10;
    if ((atoi(argv[1]) > USER_REQ_SCH_ACCESS_NONE) || (atoi(argv[1]) < USER_REQ_SCH_ACCESS_AUTO)) {
        printf("User request type invalid: setting default to auto\n");
        entry.userreqtype = USER_REQ_SCH_ACCESS_AUTO;
    } else {
        entry.userreqtype = atoi(argv[1]);
    }
    if (entry.userreqtype == USER_REQ_SCH_ACCESS_AUTO_UNCONDITIONAL) {
        if (arg < 5) {
            printf("channel needed for unconditional access\n");
            return 0;
        } else {
            entry.channel = atoi(argv[4]);
        }
    }

    entry.schaccess = atoi(argv[2]);
    entry.schextaccess = atoi(argv[3]);
    if (arg > 5) {
        strncpy(arg1.macaddr, argv[4], 17);
        set_args(entry.macaddr, &arg1, ADDR_MAC);
    }

    /* Function invokeWAVEDevice(int type, int blockflag)/invokeWAVEDriver(int blockflag) instructs the libwave 
     * to open a connection to a wave device either on the local machine or on a remote machine. 
     * Invoke the wave device before issuing any request to the wave device
     */
    printf("Invoking WAVE driver \n");
    if (invokeWAVEDevice(WAVEDEVICE_LOCAL, 0) < 0) {
        printf("Open Failed. Quitting\n");
        exit(-1);
    }

    /* Registering the user to receive the data from the TX application */
    printf("Registering User %d\n", entry.psid);
    if (registerUser(pid, &entry) < 0) {
        printf("Register User Failed \n");
        printf("Removing user if already present  %d\n", !removeUser(pid, &entry));
        printf("USER Registered %d with PSID =%u \n", registerUser(pid, &entry), entry.psid);
    }

    /* catch control-c and kill signal */
    signal(SIGINT, (void *) sig_int);
    signal(SIGTERM, (void *) sig_term);

    while (1) {
        ret = rxWSMMessage(pid, &rxmsg); /* Function to receive the Data from TX application */
        if (ret > 0) {
            printf("Received WSMP Packet txpower= %d, rateindex=%d Packet No =#%llu#\n", rxpkt.chaninfo.txpower,
                   rxpkt.chaninfo.rate, count++);
            rxWSMIdentity(&rxmsg, 0); //Identify the type of received Wave Short Message.
            if (!rxmsg.decode_status) {
                xml_print(rxmsg); /* call the parsing function to extract the contents of the received message */

            }
        } else {
            blank++;
        }
    }
}
Exemplo n.º 9
0
bool UserRegistration::handleSetRequest(const Swift::JID& from, const Swift::JID& to, const std::string& id, boost::shared_ptr<Swift::InBandRegistrationPayload> payload) {
	if (CONFIG_STRING(m_config, "service.protocol") == "irc") {
		Swift::GetResponder<Swift::InBandRegistrationPayload>::sendError(from, id, ErrorPayload::BadRequest, ErrorPayload::Modify);
		return true;
	}

	std::string barejid = from.toBare().toString();

// 	AbstractUser *user = m_component->userManager()->getUserByJID(barejid);
	if (!CONFIG_BOOL(m_config,"registration.enable_public_registration")) {
		std::list<std::string> const &x = CONFIG_LIST(m_config,"service.allowed_servers");
		if (std::find(x.begin(), x.end(), from.getDomain()) == x.end()) {
// 			Log("UserRegistration", "This user has no permissions to register an account");
			Swift::SetResponder<Swift::InBandRegistrationPayload>::sendError(from, id, ErrorPayload::BadRequest, ErrorPayload::Modify);
			return true;
		}
	}

	UserInfo res;
	bool registered = m_storageBackend->getUser(barejid, res);

	std::string encoding;
	std::string language;

	Form::ref form = payload->getForm();
	if (form) {
		const std::vector<FormField::ref> fields = form->getFields();
		for (std::vector<FormField::ref>::const_iterator it = fields.begin(); it != fields.end(); it++) {
			TextSingleFormField::ref textSingle = boost::dynamic_pointer_cast<TextSingleFormField>(*it);
			if (textSingle) {
				if (textSingle->getName() == "username") {
					payload->setUsername(textSingle->getValue());
				}
				else if (textSingle->getName() == "encoding") {
					encoding = textSingle->getValue();
				}
				continue;
			}

			TextPrivateFormField::ref textPrivate = boost::dynamic_pointer_cast<TextPrivateFormField>(*it);
			if (textPrivate) {
				if (textPrivate->getName() == "password") {
					payload->setPassword(textPrivate->getValue());
				}
				continue;
			}

			ListSingleFormField::ref listSingle = boost::dynamic_pointer_cast<ListSingleFormField>(*it);
			if (listSingle) {
				if (listSingle->getName() == "language") {
					language = listSingle->getValue();
				}
				continue;
			}

			BooleanFormField::ref boolean = boost::dynamic_pointer_cast<BooleanFormField>(*it);
			if (boolean) {
				if (boolean->getName() == "unregister") {
					if (boolean->getValue()) {
						payload->setRemove(true);
					}
				}
				continue;
			}
		}
	}

	if (payload->isRemove()) {
		unregisterUser(barejid);
		Swift::SetResponder<Swift::InBandRegistrationPayload>::sendResponse(from, id, InBandRegistrationPayload::ref());
		return true;
	}

	if (!payload->getUsername() || !payload->getPassword()) {
		Swift::SetResponder<Swift::InBandRegistrationPayload>::sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
		return true;
	}

	// Register or change password
	if (payload->getUsername()->empty() ||
		(payload->getPassword()->empty() && CONFIG_STRING(m_config, "service.protocol") != "twitter" && CONFIG_STRING(m_config, "service.protocol") != "bonjour")
// 		|| localization.getLanguages().find(language) == localization.getLanguages().end()
	)
	{
		Swift::SetResponder<Swift::InBandRegistrationPayload>::sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
		return true;
	}

	if (CONFIG_STRING(m_config, "service.protocol") == "xmpp") {
		// User tries to register himself.
		if ((Swift::JID(*payload->getUsername()).toBare() == from.toBare())) {
			Swift::SetResponder<Swift::InBandRegistrationPayload>::sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
			return true;
		}

		// User tries to register someone who's already registered.
		UserInfo user_row;
		bool registered = m_storageBackend->getUser(Swift::JID(*payload->getUsername()).toBare().toString(), user_row);
		if (registered) {
			Swift::SetResponder<Swift::InBandRegistrationPayload>::sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Modify);
			return true;
		}
	}

	std::string username = *payload->getUsername();
// 	m_component->protocol()->prepareUsername(username);

	std::string newUsername(username);
	if (!CONFIG_STRING(m_config, "registration.username_mask").empty()) {
		newUsername = CONFIG_STRING(m_config, "registration.username_mask");
// 		replace(newUsername, "$username", username.c_str());
	}

// 	if (!m_component->protocol()->isValidUsername(newUsername)) {
// 		Log("UserRegistration", "This is not valid username: "******"registration.reg_allowed_usernames").empty() &&
// 		!g_regex_match_simple(CONFIG_STRING(m_config, "registration.reg_allowed_usernames"), newUsername.c_str(),(GRegexCompileFlags) (G_REGEX_CASELESS | G_REGEX_EXTENDED), (GRegexMatchFlags) 0)) {
// 		Log("UserRegistration", "This is not valid username: "******"UserRegistration", "changing user password: "******", " << username);
		res.jid = barejid;
		res.password = *payload->getPassword();
		res.language = language;
		res.encoding = encoding;
		m_storageBackend->setUser(res);
		onUserUpdated(res);
	}

	Swift::SetResponder<Swift::InBandRegistrationPayload>::sendResponse(from, id, InBandRegistrationPayload::ref());
	return true;
}
Exemplo n.º 10
0
/*处理与客户传输数据的线程*/
void *handleRequest(int *fd)
{
	int sockfd,ret,n;
	
	/*声明消息变量*/
	Message message;
	
	/*声明消息缓冲区*/
	char buf[MAX_LINE];
	
	//客户端的套接字地址
	struct sockaddr_in cliaddr;
	socklen_t len;
	sockfd = *fd;
	
	//获取客户的ip地址和端口号
	len = sizeof(cliaddr);
	if(getpeername(sockfd,(struct sockaddr *)&cliaddr,&len) < 0)
	{
		perror("getpeername error: ");
		printf("\n\n");
	}
	
	
	while(1){
		//接受用户发送的消息
		memset(buf,0,MAX_LINE);
		memset(&message,0,sizeof(message));
		n = readn(sockfd,buf,sizeof(message));
		if(n == sizeof(message)){
			//printf("已经接收了%d字节数据\n",n);
			//printf("消息类型%d\n",message.msgType);
		}
		if(n <= 0)
		{
			//关闭当前描述符,向客户端发送FIN
			fflush(stdout);
			close(sockfd);
			*fd = -1;
			//打印发送者的IP
			printf("来自%s的断开连接!\n\n",inet_ntoa(cliaddr.sin_addr));
			pthread_exit(NULL);//此线程退出
			return NULL;
		}
		
		memcpy(&message,buf,sizeof(message));
		message.sendAddr = cliaddr;
		
		//printf("消息类型%d\n",message.msgType);
		switch(message.msgType)
		{
			case REGISTER:{
				printf("\n来自%s注册申请!\n",inet_ntoa(message.sendAddr.sin_addr));
				ret = registerUser(&message,sockfd);//交由sqlite3数据库处理
				//if(ret == FAILED)break;
				memset(&message,0,sizeof(message));
				message.msgType = RESULT;
				message.msgRet = ret;
				printf("%s\n",stateMsg(ret));
				strcpy(message.content , stateMsg(ret));
				memset(buf,0,MAX_LINE);
				memcpy(buf,&message,sizeof(message));
				/*发送操作结果消息*/
				if(writen(sockfd,buf,sizeof(message)) < 0){
					perror("send error: ");
					printf("\n\n");
					exit(1);
				}
				printf("注册:%s\n", stateMsg(message.msgRet));
				break;
			}
			 case LOGIN:{
				User user;
				printf("来自%s的登录请求!\n",inet_ntoa(message.sendAddr.sin_addr));
				ret = loginUser(&message,sockfd,&user);//交由sqlite3数据库处理
				//if(ret == FAILED)break;//客户登录界面突然退出
				memset(&message,0,sizeof(message));
				message.msgType = RESULT;
				message.msgRet = ret;
				strcpy(message.content,stateMsg(ret));
				memset(buf,0,MAX_LINE);
				memcpy(buf,&message,sizeof(message));
				//发送操作结果消息
				if(writen(sockfd,buf,sizeof(message)) < 0){
					perror("send error: ");
					printf("\n\n");
					exit(1);
				}
				//printf("登录:%s\n",stateMsg(ret));
				if(ret == SUCCESS){
					//进入服务器聊天模式
					ret = enterChat(&sockfd);
					if(ret == FAILED){//客户enterChat界面突然退出
						printf("\033[;31m%s\033[0m退出登录\n",user.userName);
						userList = deleteNode(userList , &user);
						printf("来自%s的断开连接!\n\n",inet_ntoa(cliaddr.sin_addr));
						pthread_exit(NULL);//此线程退出
						return NULL;
					}
				}
				break;
			} 
			default:
				printf("unknown operator.\n");
				//close(sockfd);
				break;
		}
	}
	
	//关闭当前描述符,向客户端发送FIN
	close(sockfd);
	*fd = -1;
	return NULL;
}
Exemplo n.º 11
0
int
main(int   argc,
     char* argv[])
{
  struct prg_data        prg;
  struct sigListenConfig lconf;
  prg.sigData  = calloc( 1, sizeof(struct sig_data) );
  prg.mediaCnf = calloc( 1, sizeof(struct mediaConfig) );
  /* struct mediaConfig     mconf; */
  /* struct addrinfo     servinfo, * p; */

  /* Intializes random number generator */
  time_t t;
  srand( (unsigned) time(&t) );

  /* struct sockaddr_storage taddr; */
  /* Set up the pointer(s).. */
  lconf.prg = &prg;
  /* lconf.mconf = &mconf; */

  pthread_t sigSocketListenThread;

  pthread_t stunTickThread;
  pthread_t iceTickThread;
  /* pthread_t turnTickThread; */

  if (argc < 3)
  {
    fprintf(stderr,"usage: icebox hostname user remoteuser\n");
    exit(1);
  }

  lconf.sigsock             = createTcpSocket(argv[1], SERVERPORT);
  lconf.signal_path_handler = signalPathHandler;

  /* lconf.msock = createUdpSocket(argv[1], */
  /*                              STUNPORT, */
  /*                              "turnclient", */
  /*                              0, */
  /*                              &servinfo, */
  /*                              &p); */
  /* if (lconf.msock == -1) */
  /* { */
  /*  return 1; */
  /* } */
  /* else if (lconf.msock == -2) */
  /* { */
  /*  return 2; */
  /* } */
  pthread_create(&sigSocketListenThread, NULL, sigSocketListen, (void*)&lconf);

  strncpy(prg.user, argv[2], MAX_USER_LEN);

  registerUser(&prg.sigData->state, lconf.sigsock, prg.user);

  /* Setup ICE */
  ICELIB_CONFIGURATION iceConfig;
  iceConfig.tickIntervalMS       = 20;
  iceConfig.keepAliveIntervalS   = 15;
  iceConfig.maxCheckListPairs    = ICELIB_MAX_PAIRS;
  iceConfig.aggressiveNomination = false;
  iceConfig.iceLite              = false;
  iceConfig.logLevel             = ICELIB_logDebug;
  /* iceConfig.logLevel = ICELIB_logDisable; */

  prg.mediaCnf->icelib = malloc( sizeof(ICELIB_INSTANCE) );
  ICELIB_Constructor(prg.mediaCnf->icelib,
                     &iceConfig);

  /* ICELIB_setCallbackLog(prg.mediaCnf->icelib, */
  /*                     ICELIB_printLog, */
  /*                     NULL, */
  /*                     ICELIB_logDebug); */

  ICELIB_setCallbackOutgoingBindingRequest(prg.mediaCnf->icelib,
                                           sendConnectivityCheck,
                                           &prg);

  ICELIB_setCallbackOutgoingBindingResponse(prg.mediaCnf->icelib,
                                            sendConnectivityResp,
                                            &prg);
  ICELIB_setCallbackConnecitivityChecksComplete(prg.mediaCnf->icelib,
                                                complete,
                                                &prg);
  ICELIB_setCallbackNominated(prg.mediaCnf->icelib,
                              nominated,
                              &prg);
  ICELIB_setCallbackOutgoingCancelRequest(prg.mediaCnf->icelib,
                                          cancelSTUNtrans,
                                          &prg);
  /* Setup stun */
  StunClient_Alloc(&prg.mediaCnf->stunInstance);

  /* StunClient_RegisterLogger(prg.mediaCnf->stunInstance, */
  /*                          stunLog, */
  /*                          &prg); */

  /* Signal path set up, time to gather the candidates */
  /* Turn setup */



  /* if ( 0 != getSockaddrFromFqdn( (struct sockaddr*)&taddr, argv[1] ) ) */
  /* { */
  /*  printf("Error getting TURN Server IP\n"); */
  /*  return 1; */
  /* } */

  /* TurnClient_StartAllocateTransaction(&lconf.turnInst, */
  /*                                    50, */
  /*                                    turnInfoFunc, */
  /*                                    "icebox", */
  /*                                      &lconf.msock, / * *userCtx * / */
  /*                                    (struct sockaddr*)&taddr, */
  /* /                                  "test\0", / *argv[2],* / */
  /*                                "pass\0", / *argv[2],* / */
  /*                              AF_INET, */
  /*                            turnSendFunc, */
  /*                          turnCbFunc, */
  /*                        false, */
  /*                      0); */


  /* pthread_create(&turnTickThread, NULL, tickTurn, (void*)lconf.turnInst); */
  pthread_create(&stunTickThread, NULL, tickStun,
                 (void*)prg.mediaCnf->stunInstance);
  pthread_create(&iceTickThread,  NULL, tickIce, (void*)prg.mediaCnf->icelib);

  if (argc == 4)
  {
    /* Ok got nothing better to do. Busywaiting */
    while (prg.sigData->state != REGISTERED)
    {
    }

    char* sdp = NULL;
    harvest(prg.mediaCnf->icelib);
    printf("Completed harvesting\n");
    crateCandidateJson(prg.mediaCnf->icelib, &sdp);

    /* Start to listen here.. */
    pthread_create(&prg.mediaCnf->mSocketListenThread, NULL, mSocketListen,
                   (void*)prg.mediaCnf);
    inviteUser(&prg.sigData->state, lconf.sigsock, argv[3], prg.user, sdp);

    if (sdp != NULL)
     {
     free(sdp);
     }

  }


  /* Just wait a bit for now.. */
  sleep(100);
  printf("Done sleeping teardown\n");
  close(lconf.sigsock);
  StunClient_free(prg.mediaCnf->stunInstance);
  free(prg.mediaCnf);
  free(prg.sigData->sdp);
  free(prg.sigData->msgBuf);
  free(prg.sigData);
  return 0;
}
Exemplo n.º 12
0
/*********************************************
函数名:main
功能:聊天室客户端main函数入口
参数:参数个数argc 用户链接地址argv
返回值:正常退出返回 0 否则返回 1
**********************************************/
int main(int argc , char *argv[])
{
	int sockfd , choice , ret; //choice代表用户在主界面所做选择,ret代表操作结果
	struct sockaddr_in servaddr;
	struct hostent *host;
	
	/*声明消息变量*/
	Message message;
	/*声明消息缓冲区*/
	char buf[MAX_LINE];

	/*UserInfo*/
	User user;
	strcpy(user.userName , "***");
	user.speak = 1;

	
    /*判断是否为合法输入*/
    if(argc != 2)
    {
        perror("usage:tcpcli <IPaddress>");
        exit(1);
    }//if

	while(1)
	{
		 /*(1) 创建套接字*/
		if((sockfd = socket(AF_INET , SOCK_STREAM , 0)) == -1)
		{
			perror("socket error");
			exit(1);
		}//if

		/*(2) 设置链接服务器地址结构*/
		bzero(&servaddr , sizeof(servaddr));		/*清空地址结构*/
		servaddr.sin_family = AF_INET;				/*使用IPV4通信域*/
		servaddr.sin_port = htons(PORT);			/*端口号转换为网络字节序*/
		//servaddr.sin_addr = *((struct in_addr *)host->h_addr);		/*可接受任意地址*/
		if(inet_pton(AF_INET , argv[1] , &servaddr.sin_addr) < 0)
		{
			printf("inet_pton error for %s\n",argv[1]);
			exit(1);
		}//if

		 /*(3) 发送链接服务器请求*/
		if( connect(sockfd , (struct sockaddr *)&servaddr , sizeof(servaddr)) < 0)
		{
			perror("connect error");
			exit(1);
		}//if	

		/*(4) 显示聊天室主界面*/		
		mainInterface();	
		setbuf(stdin,NULL); //是linux中的C函数,主要用于打开和关闭缓冲机制
		scanf("%d",&choice);
		setbuf(stdin,NULL);
		while(choice != 1 && choice != 2 && choice != 3 && choice !=4)
		{
			printf("未找到命令,请重新输入!\n");
			setbuf(stdin,NULL); //是linux中的C函数,主要用于打开和关闭缓冲机制
			scanf("%d",&choice);
			setbuf(stdin,NULL);
		}//while

		/*清空缓冲区*/		
		switch(choice)
		{		
		case REGISTER:	/*注册请求*/		
			memset(&message , 0 , sizeof(message));
			memset(buf , 0 , MAX_LINE);		
			message.msgType = REGISTER;
			strcpy(message.content , "");
			message.sendAddr = servaddr;
			/*首先向服务器发送注册请求*/		
			memcpy(buf , &message , sizeof(message));	
			send(sockfd , buf , sizeof(buf) , 0);	
			registerUser(sockfd);
			//goto sign;
			break;
		case LOGIN:		/*登陆请求*/
			memset(&message , 0 , sizeof(message));
			memset(buf , 0 , MAX_LINE);
			message.msgType = LOGIN;
			strcpy(message.content , "");
			message.sendAddr = servaddr;
			/*向服务器发送登陆请求*/
			memcpy(buf , &message , sizeof(message));
			send(sockfd , buf , sizeof(buf) , 0);
			loginUser(sockfd);					
			break;	
		case HELP:		/*帮助请求,显示帮助界面*/
            helpInterface(); 
			//goto sign;                                                                
			break;
		case EXIT:
			close(sockfd);
			printf("退出聊天室!\n");
			exit(0);	/*用户退出*/
			break;
		default:
			printf("unknown operation.\n");
			//goto sign;
			break;	
		}//switch	
	}//while	
	close(sockfd);
	return 0;	
}
Exemplo n.º 13
0
bool GlooxRegisterHandler::handleIq(const Tag *iqTag) {
	Log("GlooxRegisterHandler", iqTag->findAttribute("from") << ": iq:register received (" << iqTag->findAttribute("type") << ")");

	JID from(iqTag->findAttribute("from"));

	if (CONFIG().protocol == "irc") {
		sendError(400, "bad-request", iqTag);
		return false;
	}
	
	AbstractUser *user = Transport::instance()->userManager()->getUserByJID(from.bare());
	if (!Transport::instance()->getConfiguration().enable_public_registration) {
		std::list<std::string> const &x = Transport::instance()->getConfiguration().allowedServers;
		if (std::find(x.begin(), x.end(), from.server()) == x.end()) {
			Log("GlooxRegisterHandler", "This user has no permissions to register an account");
			sendError(400, "bad-request", iqTag);
			return false;
		}
	}

	const char *_language = user ? user->getLang() : Transport::instance()->getConfiguration().language.c_str();

	// send registration form
	if (iqTag->findAttribute("type") == "get") {
		Tag *reply = new Tag( "iq" );
		reply->addAttribute( "id", iqTag->findAttribute("id") );
		reply->addAttribute( "type", "result" );
		reply->addAttribute( "to", iqTag->findAttribute("from") );
		reply->addAttribute( "from", Transport::instance()->jid() );
		Tag *query = new Tag( "query" );
		query->addAttribute( "xmlns", "jabber:iq:register" );
		UserRow res = Transport::instance()->sql()->getUserByJid(from.bare());

		std::string instructions = CONFIG().reg_instructions.empty() ? PROTOCOL()->text("instructions") : CONFIG().reg_instructions;
		std::string usernameField = CONFIG().reg_username_field.empty() ? PROTOCOL()->text("username") : CONFIG().reg_username_field;

		if (res.id == -1) {
			Log("GlooxRegisterHandler", "* sending registration form; user is not registered");
			query->addChild( new Tag("instructions", tr(_language, instructions)) );
			query->addChild( new Tag("username") );
			if (CONFIG().protocol != "twitter" && CONFIG().protocol != "bonjour")
				query->addChild( new Tag("password") );
		}
		else {
			Log("GlooxRegisterHandler", "* sending registration form; user is registered");
			query->addChild( new Tag("instructions", tr(_language, instructions)) );
			query->addChild( new Tag("registered") );
			query->addChild( new Tag("username", res.uin));
			if (CONFIG().protocol != "twitter" && CONFIG().protocol != "bonjour")
				query->addChild( new Tag("password"));
		}

		Tag *x = new Tag("x");
		x->addAttribute("xmlns", "jabber:x:data");
		x->addAttribute("type", "form");
		x->addChild( new Tag("title", tr(_language, _("Registration"))));
		x->addChild( new Tag("instructions", tr(_language, instructions)) );

		Tag *field = new Tag("field");
		field->addAttribute("type", "hidden");
		field->addAttribute("var", "FORM_TYPE");
		field->addChild( new Tag("value", "jabber:iq:register") );
		x->addChild(field);

		field = new Tag("field");
		field->addAttribute("type", "text-single");
		field->addAttribute("var", "username");
		field->addAttribute("label", tr(_language, usernameField));
		field->addChild( new Tag("required") );
		if (res.id!=-1)
			field->addChild( new Tag("value", res.uin) );
		x->addChild(field);

		if (CONFIG().protocol != "twitter" && CONFIG().protocol != "bonjour") {
			field = new Tag("field");
			field->addAttribute("type", "text-private");
			field->addAttribute("var", "password");
			field->addAttribute("label", tr(_language, _("Password")));
			x->addChild(field);
		}

		field = new Tag("field");
		field->addAttribute("type", "list-single");
		field->addAttribute("var", "language");
		field->addAttribute("label", tr(_language, _("Language")));
		if (res.id!=-1)
			field->addChild( new Tag("value", res.language) );
		else
			field->addChild( new Tag("value", Transport::instance()->getConfiguration().language) );
		x->addChild(field);

		std::map <std::string, std::string> languages = localization.getLanguages();
		for (std::map <std::string, std::string>::iterator it = languages.begin(); it != languages.end(); it++) {
			Tag *option = new Tag("option");
			option->addAttribute("label", (*it).second);
			option->addChild( new Tag("value", (*it).first) );
			field->addChild(option);
		}

		field = new Tag("field");
		field->addAttribute("type", "text-single");
		field->addAttribute("var", "encoding");
		field->addAttribute("label", tr(_language, _("Encoding")));
		if (res.id!=-1)
			field->addChild( new Tag("value", res.encoding) );
		else
			field->addChild( new Tag("value", Transport::instance()->getConfiguration().encoding) );
		x->addChild(field);

		if (res.id != -1) {
			field = new Tag("field");
			field->addAttribute("type", "boolean");
			field->addAttribute("var", "unregister");
			field->addAttribute("label", tr(_language, _("Remove your registration")));
			field->addChild( new Tag("value", "0") );
			x->addChild(field);
		}

		query->addChild(x);
		reply->addChild(query);
		Transport::instance()->send( reply );
		return true;
	}
	else if (iqTag->findAttribute("type") == "set") {
		bool remove = false;
		Tag *query;
		Tag *usernametag;
		Tag *passwordtag;
		Tag *languagetag;
		Tag *encodingtag;
		std::string username("");
		std::string password("");
		std::string language("");
		std::string encoding("");

		UserRow res = Transport::instance()->sql()->getUserByJid(from.bare());
		
		query = iqTag->findChild( "query" );
		if (!query) return true;

		Tag *xdata = query->findChild("x", "xmlns", "jabber:x:data");
		if (xdata) {
			if (query->hasChild( "remove" ))
				remove = true;
			for (std::list<Tag*>::const_iterator it = xdata->children().begin(); it != xdata->children().end(); ++it) {
				std::string key = (*it)->findAttribute("var");
				if (key.empty()) continue;

				Tag *v = (*it)->findChild("value");
				if (!v) continue;

				if (key == "username")
					username = v->cdata();
				else if (key == "password")
					password = v->cdata();
				else if (key == "language")
					language = v->cdata();
				else if (key == "encoding")
					encoding = v->cdata();
				else if (key == "unregister")
					remove = atoi(v->cdata().c_str());
			}
		}
		else {
			if (query->hasChild( "remove" ))
				remove = true;
			else {
				usernametag = query->findChild("username");
				passwordtag = query->findChild("password");
				languagetag = query->findChild("language");
				encodingtag = query->findChild("encoding");

				if (languagetag)
					language = languagetag->cdata();
				else
					language = Transport::instance()->getConfiguration().language;

				if (encodingtag)
					encoding = encodingtag->cdata();
				else
					encoding = Transport::instance()->getConfiguration().encoding;

				if (usernametag==NULL || (passwordtag==NULL && CONFIG().protocol != "twitter" && CONFIG().protocol != "bonjour")) {
					sendError(406, "not-acceptable", iqTag);
					return false;
				}
				else {
					username = usernametag->cdata();
					if (passwordtag)
						password = passwordtag->cdata();
					if (username.empty() || (password.empty() && CONFIG().protocol != "twitter" && CONFIG().protocol != "bonjour")) {
						sendError(406, "not-acceptable", iqTag);
						return false;
					}
				}
			}
		}

		if (Transport::instance()->getConfiguration().protocol == "xmpp") {
			// User tries to register himself.
			if ((JID(username).bare() == from.bare())) {
				sendError(406, "not-acceptable", iqTag);
				return false;
			}

			// User tries to register someone who's already registered.
			UserRow user_row = Transport::instance()->sql()->getUserByJid(JID(username).bare());
			if (user_row.id != -1) {
				sendError(406, "not-acceptable", iqTag);
				return false;
			}
		}

		if (remove) {
			unregisterUser(from.bare());

			Tag *reply = new Tag("iq");
			reply->addAttribute( "type", "result" );
			reply->addAttribute( "from", Transport::instance()->jid() );
			reply->addAttribute( "to", iqTag->findAttribute("from") );
			reply->addAttribute( "id", iqTag->findAttribute("id") );
			Transport::instance()->send( reply );

			return true;
		}

		// Register or change password

		std::string jid = from.bare();

		if (username.empty() || (password.empty() && CONFIG().protocol != "twitter" && CONFIG().protocol != "bonjour") || localization.getLanguages().find(language) == localization.getLanguages().end()) {
			sendError(406, "not-acceptable", iqTag);
			return false;
		}

		Transport::instance()->protocol()->prepareUsername(username);

		std::string newUsername(username);
		if (!CONFIG().username_mask.empty()) {
			newUsername = CONFIG().username_mask;
			replace(newUsername, "$username", username.c_str());
		}

		if (!Transport::instance()->protocol()->isValidUsername(newUsername)) {
			Log("GlooxRegisterHandler", "This is not valid username: "******"bad-request", iqTag);
			return false;
		}

#if GLIB_CHECK_VERSION(2,14,0)
		if (!CONFIG().reg_allowed_usernames.empty() &&
			!g_regex_match_simple(CONFIG().reg_allowed_usernames.c_str(), newUsername.c_str(),(GRegexCompileFlags) (G_REGEX_CASELESS | G_REGEX_EXTENDED), (GRegexMatchFlags) 0)) {
			Log("GlooxRegisterHandler", "This is not valid username: "******"bad-request", iqTag);
			return false;
		}
#endif
		if (res.id == -1) {
			res.jid = from.bare();
			res.uin = username;
			res.password = password;
			res.language = language;
			res.encoding = encoding;
			res.vip = 0;

			registerUser(res);
		}
		else {
			// change passwordhttp://soumar.jabbim.cz/phpmyadmin/index.php
			Log("GlooxRegisterHandler", "changing user password: "******", " << username);
			res.jid = from.bare();
			res.password = password;
			res.language = language;
			res.encoding = encoding;
			Transport::instance()->sql()->updateUser(res);
		}

		Tag *reply = new Tag( "iq" );
		reply->addAttribute( "id", iqTag->findAttribute("id") );
		reply->addAttribute( "type", "result" );
		reply->addAttribute( "to", iqTag->findAttribute("from") );
		reply->addAttribute( "from", Transport::instance()->jid() );
		Transport::instance()->send( reply );

		return true;
	}
	return false;
}
///
/// \brief Client::Client
/// \param parent
/// constructor for the Client class
Client::Client(QWidget *parent)
:   QDialog(parent), networkSession(0)
{
    // Setting up widgets for the login window
    // set labels
    m_userLabel = new QLabel(tr("Email: "));
    m_passwordLabel = new QLabel(tr("Password: "******"IP: "));
    m_portLabel = new QLabel(tr("Port: "));
    m_loginStatusLabel = new QLabel(tr("Please fill in IP and port and press Connect."));

    // setup edits
    m_hostEdit = new QLineEdit;
    m_portEdit = new QLineEdit;
    m_portEdit->setValidator(new QIntValidator(1, 65535, this));
    m_userEdit = new QLineEdit;
    m_passwordEdit = new QLineEdit;

    // connect labels to edits
    m_userLabel->setBuddy(m_userEdit);
    m_passwordLabel->setBuddy(m_passwordEdit);
    m_hostLabel->setBuddy(m_hostEdit);
    m_portLabel->setBuddy(m_portEdit);

    // setup buttons
    m_registerBtn = new QPushButton(tr("Register"));
    m_loginBtn = new QPushButton(tr("Log in"));
    m_connectBtn = new QPushButton(tr("Connect"));

    // initial button settings
    m_connectBtn->setDefault(true);
    //m_loginBtn->setEnabled(false);
    m_registerBtn->setEnabled(false);

    // button box
    buttonBox = new QDialogButtonBox;
    buttonBox->addButton(m_connectBtn, QDialogButtonBox::ActionRole);
    buttonBox->addButton(m_registerBtn, QDialogButtonBox::ActionRole);
    buttonBox->addButton(m_loginBtn, QDialogButtonBox::ActionRole);

    // connect button press signals to slots
    connect(m_connectBtn, SIGNAL(clicked()), this, SLOT(startConnection()));
    connect(m_registerBtn, SIGNAL(clicked()), this, SLOT(registerUser()));
    connect(m_loginBtn, SIGNAL(clicked()), this, SLOT(login()));

    // read from server when server sends data
    m_tcpSocket = new QTcpSocket(this);
    connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(readServerResponse()));
    connect(m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
                this, SLOT(displayError(QAbstractSocket::SocketError)));

    // put widgets on a window
    //QGridLayout *loginLayout = new QGridLayout;

    loginLayout.addWidget(m_hostLabel, 0, 0);
    loginLayout.addWidget(m_hostEdit, 0, 1);
    loginLayout.addWidget(m_portLabel, 1, 0);
    loginLayout.addWidget(m_portEdit, 1, 1);
    loginLayout.addWidget(m_userLabel, 2, 0);
    loginLayout.addWidget(m_userEdit, 2, 1);
    loginLayout.addWidget(m_passwordLabel, 3, 0);
    loginLayout.addWidget(m_passwordEdit, 3, 1);
    loginLayout.addWidget(m_loginStatusLabel, 4, 0, 1, 2);
    loginLayout.addWidget(buttonBox, 5, 0, 1, 2);
    setLayout(&loginLayout);

    // set up the inbox
    m_inbox = new QListWidget();
    QObject::connect(m_inbox, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(viewMessage(QListWidgetItem*)));
    m_inbox->setStyleSheet("QListWidget::item{border-bottom:1px solid black;}");

    m_viewingSent = 0;

    // test code for setting up emails
    Email* e1 = new Email();
    e1->setFrom("John");
    e1->setSubject("money");
    e1->setMessage("Yo n***a, you betta give me my money!");
    e1->setRead(false);
    e1->setText(e1->getFrom() + " | " + e1->getSubject());
    e1->setData(12, 1);
    e1->setID(1);
    Email* e2 = new Email();
    e2->setFrom("Simon");
    e2->setSubject("hangout");
    e2->setMessage("Hey man, do you want to hangout?");
    e2->setRead(false);
    e2->setText(e2->getFrom() + " | " + e2->getSubject());
    m_emails.append(e1);
    m_emails.append(e2);
    e2->setData(12, 2);
    e2->setID(2);

}
Exemplo n.º 15
0
/*处理客户请求的线程*/
void* handleRequest(int *fd)
{
	int sockfd , ret , n;
	/*声明消息变量*/
	Message message;
	/*声明消息缓冲区*/
	char buf[MAX_LINE];

	sockfd = *fd;

	memset(buf , 0 , MAX_LINE);
	memset(&message , 0 , sizeof(message));

	//接收用户发送的消息
	n = recv(sockfd , buf , sizeof(buf)+1 , 0);
	if(n <= 0)
	{
		//关闭当前描述符,并清空描述符数组 
		fflush(stdout);
		close(sockfd);
		*fd = -1;
		printf("来自%s的退出请求!\n", inet_ntoa(message.sendAddr.sin_addr));		
		return NULL;			
	}//if				
	else{
		memcpy(&message , buf , sizeof(buf));				
		/*为每个客户操作链接创建一个线程*/					
		switch(message.msgType)
		{
		case REGISTER:						
			{
				printf("来自%s的注册请求!\n", inet_ntoa(message.sendAddr.sin_addr));
				ret = registerUser(&message , sockfd);
				memset(&message , 0 , sizeof(message));
				message.msgType = RESULT;
				message.msgRet = ret;
				strcpy(message.content , stateMsg(ret));		
				memset(buf , 0 , MAX_LINE);
				memcpy(buf , &message , sizeof(message));						
				/*发送操作结果消息*/
				send(sockfd , buf , sizeof(buf) , 0);
				printf("注册:%s\n", stateMsg(ret));	
				close(sockfd);
				*fd = -1;
				return NULL;
				break;
			}//case
		case LOGIN:
			{
				printf("来自%s的登陆请求!\n", inet_ntoa(message.sendAddr.sin_addr));
				ret = loginUser(&message , sockfd);							
				memset(&message , 0 , sizeof(message));
				message.msgType = RESULT;
				message.msgRet = ret;
				strcpy(message.content , stateMsg(ret));							
				memset(buf , 0 , MAX_LINE);
				memcpy(buf , &message , sizeof(message));						
				/*发送操作结果消息*/
				send(sockfd , buf , sizeof(buf) , 0);
				printf("登录:%s\n", stateMsg(ret));
				/*进入服务器处理聊天界面*/
				enterChat(&sockfd);												
				break;
			}//case			
		default:
			printf("unknown operation.\n");
			break;
		}//switch					
	}//else				

	close(sockfd);
	*fd = -1;
	return NULL;
}