예제 #1
0
bool MultiUserChat::setNickName(const QString &ANick)
{
	if (!ANick.isEmpty())
	{
		if (isConnected())
		{
			if (FNickName != ANick)
			{
				Jid userJid(FRoomJid.node(),FRoomJid.domain(),ANick);
				Stanza presence("presence");
				presence.setTo(userJid.full());
				if (FStanzaProcessor->sendStanzaOut(FStreamJid,presence))
				{
					LOG_STRM_INFO(FStreamJid,QString("Change conference nick request sent, room=%1, old=%2, new=%3").arg(FRoomJid.bare(),FNickName,ANick));
					return true;
				}
				LOG_STRM_WARNING(FStreamJid,QString("Failed to send change conference nick request, room=%1").arg(FRoomJid.bare()));
			}
		}
		else
		{
			FNickName = ANick;
			return true;
		}
	}
	else
	{
		REPORT_ERROR("Failed to change conference nick: Nick is empty");
	}
	return false;
}
예제 #2
0
void MainController::handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText) {
	boost::shared_ptr<Presence> presence(new Presence());
	if (show == StatusShow::None) {
		// Note: this is misleading, None doesn't mean unavailable on the wire.
		presence->setType(Presence::Unavailable);
		resetPendingReconnects();
		myStatusLooksOnline_ = false;
		offlineRequested_ = true;
	}
	else {
		offlineRequested_ = false;
		presence->setShow(show);
	}
	presence->setStatus(statusText);
	statusTracker_->setRequestedPresence(presence);
	if (presence->getType() != Presence::Unavailable) {
		profileSettings_->storeInt("lastShow", presence->getShow());
		profileSettings_->storeString("lastStatus", presence->getStatus());
	}
	if (presence->getType() != Presence::Unavailable && !client_->isAvailable()) {
		performLoginFromCachedCredentials();
	} else {
		sendPresence(presence);
	}
}
예제 #3
0
int XmppTaskPresence::ProcessStart() {

  txmpp::scoped_ptr<txmpp::XmlElement> presence(
      new txmpp::XmlElement(txmpp::QN_PRESENCE));
  SendStanza(presence.get());

  return STATE_RESPONSE;
}
예제 #4
0
/**
 * Send future broadcast presence also to this JID.
 * @param jid Non-roster JID to stop receiving global presence updates.
 * @param sendPresence Also send presence type=unavailable immediately to jid.
 */
void DirectedPresenceSender::removeDirectedPresenceReceiver(const JID& jid, SendPresence sendPresence) {
    directedPresenceReceivers.erase(jid);
    if (sendPresence == AndSendPresence && sender->isAvailable()) {
        std::shared_ptr<Presence> presence(new Presence());
        presence->setType(Presence::Unavailable);
        presence->setTo(jid);
        sender->sendPresence(presence);
    }
}
예제 #5
0
void MainController::performLoginFromCachedCredentials() {
	if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS) && password_.empty()) {
		/* Then we can't try to login again. */
		return;
	}
	/* If we logged in with a bare JID, and we have a full bound JID, re-login with the
	 * bound JID to try and keep dynamically assigned resources */
	JID clientJID = jid_;
	if (boundJID_.isValid() && jid_.isBare() && boundJID_.toBare() == jid_) {
		clientJID = boundJID_;
	}

	if (!statusTracker_) {
		statusTracker_  = new StatusTracker();
	}
	if (!clientInitialized_) {
		storages_ = storagesFactory_->createStorages(jid_.toBare());
		certificateStorage_ = certificateStorageFactory_->createCertificateStorage(jid_.toBare());
		certificateTrustChecker_ = new CertificateStorageTrustChecker(certificateStorage_);

		client_ = boost::make_shared<Swift::Client>(clientJID, createSafeByteArray(password_.c_str()), networkFactories_, storages_);
		clientInitialized_ = true;
		client_->setCertificateTrustChecker(certificateTrustChecker_);
		client_->onDataRead.connect(boost::bind(&XMLConsoleController::handleDataRead, xmlConsoleController_, _1));
		client_->onDataWritten.connect(boost::bind(&XMLConsoleController::handleDataWritten, xmlConsoleController_, _1));
		client_->onDisconnected.connect(boost::bind(&MainController::handleDisconnected, this, _1));
		client_->onConnected.connect(boost::bind(&MainController::handleConnected, this));

		client_->setSoftwareVersion(CLIENT_NAME, buildVersion);

		client_->getVCardManager()->onVCardChanged.connect(boost::bind(&MainController::handleVCardReceived, this, _1, _2));
		presenceNotifier_ = new PresenceNotifier(client_->getStanzaChannel(), notifier_, client_->getMUCRegistry(), client_->getAvatarManager(), client_->getNickResolver(), client_->getPresenceOracle(), networkFactories_->getTimerFactory());
		presenceNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1));
		eventNotifier_ = new EventNotifier(eventController_, notifier_, client_->getAvatarManager(), client_->getNickResolver());
		eventNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1));
		if (certificate_) {
			client_->setCertificate(certificate_);
		}
		boost::shared_ptr<Presence> presence(new Presence());
		presence->setShow(static_cast<StatusShow::Type>(profileSettings_->getIntSetting("lastShow", StatusShow::Online)));
		presence->setStatus(profileSettings_->getStringSetting("lastStatus"));
		statusTracker_->setRequestedPresence(presence);
	} else {
		/* In case we're in the middle of another login, make sure they don't overlap */
		client_->disconnect();
	}
	systemTrayController_->setConnecting();
	if (rosterController_) {
		rosterController_->getWindow()->setConnecting();
	}
	ClientOptions clientOptions = clientOptions_;
	bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS);
	clientOptions.forgetPassword = eagle;
	clientOptions.useTLS = eagle ? ClientOptions::RequireTLS : clientOptions_.useTLS;
	client_->connect(clientOptions);
}
예제 #6
0
ProxyObjectPtr HostedObject::self(const SpaceObjectReference& sor)
{
    ProxyManagerPtr proxy_man = presence(sor);
    if (!proxy_man) return ProxyObjectPtr();
    ProxyObjectPtr proxy_obj = proxy_man->getProxyObject(sor);



    return proxy_obj;
}
예제 #7
0
void Swiftob::handleConnected() {
	std::cout << "Connected" << std::endl;
	if (options_.count("init") > 0) {}{ /* FIXME: Not ready for persistence yet*/
		users_->clearAll();
		users_->addUser(Users::User(Swift::JID(options_["initial-owner"].as<std::string>()), Users::User::Owner));
	}
	Swift::Presence::ref presence(new Swift::Presence());
	presence->setStatus("Online and botty");
	client_->getPresenceSender()->sendPresence(presence);
}
예제 #8
0
int JabberMenuRevokeAuth( WPARAM wParam, LPARAM lParam )
{
	HANDLE hContact;
	DBVARIANT dbv;

	if (( hContact=( HANDLE ) wParam )!=NULL && jabberOnline ) {
		if ( !JGetStringT( hContact, "jid", &dbv )) {
			XmlNode presence( "presence" ); presence.addAttr( "to", dbv.ptszVal ); presence.addAttr( "type", "unsubscribed" );
			JabberSend( jabberThreadInfo->s, presence );
			JFreeVariant( &dbv );
	}	}

	return 0;
}
예제 #9
0
bool OneWireSlave::waitForRequest(bool ignore_errors) {
    errno = ONEWIRE_NO_ERROR;
    for (;;) {
        if (!waitReset(0) )
            continue;
        if (!presence() )
            continue;
        if (recvAndProcessCmd() )
            return TRUE;
        else if ((errno == ONEWIRE_NO_ERROR) || ignore_errors)
            continue;
        else
            return FALSE;
    }
}
예제 #10
0
void MyXmppClient::error(QXmppClient::Error e) {
    QString errString;
    if( e == QXmppClient::SocketError ) errString = "SOCKET_ERROR";
    else if( e == QXmppClient::KeepAliveError ) errString = "KEEP_ALIVE_ERROR";
    else if( e == QXmppClient::XmppStreamError ) errString = "XMPP_STREAM_ERROR";

    if( !errString.isNull() ) {
        QXmppPresence pr = xmppClient->clientPresence();
        this->presenceReceived( pr );
        QXmppPresence presence( QXmppPresence::Unavailable );
        this->clearPresence();
        xmppClient->setClientPresence( presence );

        emit errorHappened(m_accountId,errString);
    }
}
예제 #11
0
void
client_actions(int fd){

    char *tag;

    tag=xmlgetfirsttagname(client[fd].buffer);

    switch (client[fd].state) {

        case STREAM: {
            /* setup a new stream */
            printf("STREAM\n");          
            stream(fd);
        } break;

        case LOGIN: {
            /* perform login procedures */
            printf("LOGIN\n");          

            if (!strcmp(tag,"iq"))
                client_login(fd);
            else
                unknown_msg(fd);

        } break;

        case CHAT: {
            printf("CHAT\n");          

            if (!strcmp(tag,"iq"))
                iq(fd);
            else if (!strcmp(tag,"presence"))
                presence(fd);
            else if (!strcmp(tag,"message"))
                message(fd);
            else
                unknown_msg(fd);
        } break;

    } /* end case */

    free(tag);
    
} /* end client actions */
예제 #12
0
QString QTextDocumentExtra::toXml() const
{
    QHash<QString,QString> t;
    t.insert(QDOCUMENT_VERSION_XML_TAG, d->xmlVersion);
    t.insert(QDOCUMENT_PRESENCE_XML_TAG,QString::number(presence()));
    t.insert(QDOCUMENT_PRIORITY_XML_TAG, QString::number(priority()));
    t.insert(QDOCUMENT_EXTRA_XML_TAG, "");
    t.insert(QDOCUMENT_HTML_XML_TAG, toHtml());
    QDomDocument doc;
    QDomElement main = doc.createElement(QDOCUMENT_GENERAL_XML_TAG);
    doc.appendChild(main);
    foreach( const QString &k, t.keys() ) {
        QDomElement data = doc.createElement(k);
        QDomText dataText = doc.createTextNode(t.value(k));
        main.appendChild(data);
        data.appendChild(dataText);
    }
    return doc.toString(4);
}
예제 #13
0
void QXmppStreamManagement::ackReceived(const QDomElement &element)
{
    const QString h = element.attribute("h");
    debug(QString("SM ACK RECV h=%1 outbound count=%2").arg(h).arg(QString::number(d->outboundCounter)));
    int handled = h.toInt();

    QMapIterator <int, QXmppStanza*> i(d->outboundBuffer);
    const QXmppStanza *stanza = NULL;
    while (i.hasNext()) {
        i.next();
        if(i.key()<= handled)
        {
            stanza = i.value();
            switch (stanza->getStanzaType())
            {
                case QXmppStanza::Message:
                {
                    QXmppMessage message(static_cast<QXmppMessage const &> (*stanza));
                    emit messageAcknowledged(message, true);
                    break;
                }
                case QXmppStanza::Iq:
                {
                    QXmppIq iq(static_cast<QXmppIq const &> (*stanza));
                    emit iqAcknowledged(iq, true);
                    break;
                }
                case QXmppStanza::Presence:
                {
                    QXmppPresence presence(static_cast<QXmppPresence const &>(*stanza));
                    emit presenceAcknowledged(presence, true);
                    break;
                }
                default:
                    break;
           }

           d->outboundBuffer.remove(i.key());
           delete stanza;
           debug(QString("SM h:%1 removed from the buffer").arg(i.key()));
       }
    }
}
예제 #14
0
void QXmppStreamManagement::socketDisconnected()
{
    // If resume is enabled the buffer is not emptied until the resume is attempted
    if(!d->resumeEnabled)
    {
        QMapIterator <int, QXmppStanza*> i(d->outboundBuffer);
        const QXmppStanza *stanza = NULL;
        while (i.hasNext()) {
            i.next();
            stanza = i.value();
            switch (stanza->getStanzaType())
            {
                case QXmppStanza::Message:
                {
                    QXmppMessage message(static_cast<QXmppMessage const &> (*stanza));
                    emit messageAcknowledged(message, false);
                    break;
                }
                case QXmppStanza::Iq:
                {
                    QXmppIq iq(static_cast<QXmppIq const &> (*stanza));
                    emit iqAcknowledged(iq, false);
                    break;
                }
                case QXmppStanza::Presence:
                {
                    QXmppPresence presence(static_cast<QXmppPresence const &>(*stanza));
                    emit presenceAcknowledged(presence, false);
                    break;
                }
                default:
                    break;
            }
            d->outboundBuffer.remove(i.key());
            delete stanza;
            debug(QString("SM h:%1 removed from the buffer").arg(i.key()));
        }
    }else{
        d->resumming = true;
    }


}
예제 #15
0
파일: problem29.cpp 프로젝트: stdk/euler
std::vector<size_t> preprocess(size_t limit) {
    size_t max_power = log2(limit);
    std::vector<size_t> result;
    result.reserve(max_power);

    //std::cerr << "Need " << max_power*limit << " bits" << std::endl;
    std::vector<bool> presence(max_power*limit+1);

    size_t count = 0;
    for(size_t p=1;p<=max_power;p++) {
        for(size_t i=2;i<=limit;i++) {
            if(!presence[p*i]) {
                count++;
                presence[p*i] = true;
            }
        }
        result.push_back(count);
    }

    return result;
}
ContactInfoDialog::ContactInfoDialog(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, QWidget *parent)
    : QDialog(parent)
    , d(new Private(this))
{
#if 0   // Editing contacts is not yet supported in TpQt
    /* Whether contact is the user himself */
    d->editable = (contact == account->connection()->selfContact());
#endif
    d->editable = false;
    d->account = account;
    d->contact = KTp::ContactPtr::qObjectCast(contact);

    d->buttonBox = new QDialogButtonBox(this);


    if (d->editable) {
        d->buttonBox->setStandardButtons(QDialogButtonBox::Save | QDialogButtonBox::Close);
    } else {
        d->buttonBox->setStandardButtons(QDialogButtonBox::Close);
    }

    connect(d->buttonBox, &QDialogButtonBox::clicked, this, &ContactInfoDialog::slotButtonClicked);

    setMaximumSize(sizeHint());

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setSpacing(30);

    /* Title - presence icon, alias, id */
    KTitleWidget *titleWidget = new KTitleWidget(this);
    KTp::Presence presence(contact->presence());
    titleWidget->setPixmap(presence.icon().pixmap(32, 32), KTitleWidget::ImageLeft);
    titleWidget->setText(contact->alias());
    titleWidget->setComment(contact->id());
    layout->addWidget(titleWidget);

    /* 1st column: avatar; 2nd column: details */
    d->columnsLayout = new QHBoxLayout();
    d->columnsLayout->setSpacing(30);
    layout->addLayout(d->columnsLayout);

    /* Make sure the contact has all neccessary features ready */
    Tp::PendingContacts *op = contact->manager()->upgradeContacts(
            QList<Tp::ContactPtr>() << contact,
            Tp::Features() << Tp::Contact::FeatureAvatarData
                           << Tp::Contact::FeatureInfo);
    connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onContactUpgraded(Tp::PendingOperation*)));

    /* State Info - there is no point showing this information when it's about ourselves */
    if (!d->editable) {
        d->stateLayout = new QFormLayout();
        d->stateLayout->setSpacing(10);
        layout->addLayout(d->stateLayout);

        // Fetch roster feature, if it is supported, but not loaded
        Tp::ConnectionPtr conn = contact->manager()->connection();
        if(!conn->actualFeatures().contains(Tp::Connection::FeatureRoster) && !conn->missingFeatures().contains(Tp::Connection::FeatureRoster)) {
            Tp::PendingReady *pr = conn->becomeReady(Tp::Features() << Tp::Connection::FeatureRoster);

            connect(pr, SIGNAL(finished(Tp::PendingOperation*)),
                    SLOT(onFeatureRosterReady(Tp::PendingOperation*)));
        } else {
            d->loadStateRows();
        }
    }

    layout->addWidget(d->buttonBox);
}
예제 #17
0
bool OneWireSlave::presence() {
    return presence(25);
}
예제 #18
0
int jabber_presence(struct stream_s *stream,xmlnode tag){
char *type;
char *from;
char *to;
xmlnode prio_n;
xmlnode show_n;
xmlnode status_n;
char *show,*status;
int priority;
char *tmp;
User *u;

	type=xmlnode_get_attrib(tag,"type");
	from=xmlnode_get_attrib(tag,"from");
	to=xmlnode_get_attrib(tag,"to");

	if (from) u=user_get_by_jid(from);
	else u=NULL;
	user_load_locale(u);

	if (!acl_is_allowed(from,tag)){
		if (type && !strcmp(type,"error")){
			debug("Ignoring forbidden presence error");
			return -1;
		}
		if (!from) return -1;
		presence_send_error(stream,to,from,405,_("Not allowed"));
		return -1;
	}

	show_n=xmlnode_get_tag(tag,"show");
	if (show_n) show=xmlnode_get_data(show_n);
	else show=NULL;

	status_n=xmlnode_get_tag(tag,"status");
	if (status_n) status=xmlnode_get_data(status_n);
	else status=NULL;

	prio_n=xmlnode_get_tag(tag,"priority");
	if (prio_n){
		tmp=xmlnode_get_data(prio_n);
		if (tmp) priority=atoi(tmp);
		else priority=-1;
	}
	else priority=-1;

	if (!type) type="available";

	if (!from || !to){
		if (strcmp(type,"error"))
			presence_send_error(stream,to,from,406,_("Not Acceptable"));
		g_warning(N_("Bad <presence/>: %s"),xmlnode2str(tag));
		return -1;
	}

	if (!jid_is_my(to)){
		if (strcmp(type,"error"))
			presence_send_error(stream,to,from,406,_("Not Acceptable"));
		g_warning(N_("Wrong 'to' in %s"),xmlnode2str(tag));
		return -1;
	}

	if (!strcmp(type,"available")){
		if (jid_has_uin(to))
			return presence_direct_available(stream,from,to);
		else
			return presence(stream,from,to,1,show,status,priority);
	}
	else if (!strcmp(type,"unavailable")){
		if (jid_has_uin(to))
			return presence_direct_unavailable(stream,from,to);
		else
			return presence(stream,from,to,0,show,status,priority);
	}
	if (!strcmp(type,"invisible")){
		if (jid_has_uin(to))
			return presence_direct_unavailable(stream,from,to);
		else
			return presence(stream,from,to,-1,show,status,priority);
	}
	else if (!strcmp(type,"subscribe"))
		return presence_subscribe(stream,from,to);
	else if (!strcmp(type,"unsubscribe"))
		return presence_unsubscribe(stream,from,to);
	else if (!strcmp(type,"subscribed"))
		return presence_subscribed(stream,from,to);
	else if (!strcmp(type,"unsubscribed"))
		return presence_unsubscribed(stream,from,to);
	else if (!strcmp(type,"probe"))
		return presence_probe(stream,from,to);
	else if (!strcmp(type,"error")){
		g_warning(N_("Error presence received: %s"),xmlnode2str(tag));
		return 0;
	}

	g_warning(N_("Unsupported type in %s"),xmlnode2str(tag));
	presence_send_error(stream,to,from,501,_("Not Implemented"));
	return -1;
}
예제 #19
0
파일: rw.c 프로젝트: ah42/CUDALucas
/*  0: no more input; 1: trouble; 2: resuming from a partial (RI) result; 3: other data for exponent */
int input( int argc, char **argv , EXPONENT *q, UL *n, UL *j, double *err, double **x, EXPONENT last,
		char *M , FILE **infp, FILE **outfp, FILE **dupfp, const char *version_info) {
	
	if (q == NULL || M == NULL || infp == NULL || outfp == NULL || dupfp == NULL) return 1;
	
	static bool first_time_here = true; /* first call to input() in this program? */
	char *tmpstr = NULL;
	if (first_time_here) {
		gettimeofday(&start_time, NULL);
		if (((tmpstr = getenv("FFTLUCAS_CHECKPOINT")) != NULL) && (sscanf(tmpstr, SCANF_FMT_UL, &chkpnt_iterations) != 1 || chkpnt_iterations < (UL)5000)) {
			if (!isdigit(tmpstr[0]))
				fprintf(stderr, "%s: non-numeric FFTLUCAS_CHECKPOINT; using 5000\n", program_name);
			chkpnt_iterations = (UL)5000;
		}
	}  
	
	int sBL, sD; /* sizeof(BIG_LONG), sizeof(double), and */
	long RHM;     /* ROUNDED_HALF_MANTISSA as read from input */
	UL tmp2;
	FILE *tmpfp = NULL;
	int partial; /* are we resuming a partially computed LL test? */
	int i = EOF;
	/* these last three are needed by LL tests only to skip parts of the input appropriately */
	char str[1]; /* for reading the ending 's' of 'trials' from input (usually the server) */
	
get_next_q: /* all but one goto to here are just before a return if (*q < start_range || *q > stop_range); */
            /*  the single exception is reading a DATABASE file that has exponents that do not fit in a UL */

	UL tmp = 0;
	static int arg = 0; /* subscript of argv; will be incremented immediately */
	if ((*infp == NULL || feof(*infp)) && argv != NULL && argv[arg] != NULL)
		arg++;
	
	while (argv != NULL && argv[arg] != NULL && argv[arg][0] == '\0')
		arg++;
	
	if ((argv == NULL || argv[arg] == NULL) && (*infp == NULL || feof(*infp))) {
		if (first_time_here) {
			*infp  = stdin;
			*outfp = stdout;
		} else
			return 0; /* nothing else to read; must be done; only return(0) when no -n is given */
	}
	
	while (arg < argc && argv != NULL && argv[arg] != NULL && ((*infp == NULL && tmp == (UL)0) || (*infp != NULL && feof(*infp)) || first_time_here)) {
		if (*infp != NULL && *infp != stdin && feof(*infp)) {
			fclose(*infp);
			*infp = NULL;
		}
		if (*outfp != NULL && *outfp != stdout && *outfp != stderr && ferror(*outfp)) {
			fclose(*outfp);
			*outfp = NULL;
		}
		switch (argv[arg][0]) {
			case '\0': /* empty argument: pretend it's a lone dash */
				*infp = stdin;
				first_time_here = false;
				if (arg > 1)
					fprintf(stderr, "Warning: reading from stdin due to NULL argument or no file arguments\n");
				break;
			case '-': /* leading dash: some sort of option */
				/* set tmpstr to point at the option's likely argument to simplify things later */
				if (argv[arg][1] != '\0') {       /* could skip this except: */
					if (argv[arg][2] != '\0') /* can't check this unless prior condition is true */
						tmpstr = argv[arg] + 2;
					else if (arg + 1 < argc)
						tmpstr = argv[arg + 1];
					else
						tmpstr = NULL;
				}
				
				switch (argv[arg][1]) {
					case '\0': /* just a dash: read stdin */
						*infp = stdin;
						first_time_here = 0;
						/*!!kludge to undo increment just after this switch so increment at EOF will be correct */
						/*!! and to match argv[arg] being the name of the open file in the named file case */
						arg--;
						break;
					case 'b': /* binary checkpoint format */
						chkpnt_fmt = CHKPNT_BINARY;
						break;
					case 'c': /* check point iterations */
						if (tmpstr == NULL || sscanf(tmpstr, SCANF_FMT_UL, &chkpnt_iterations) != 1)
							chkpnt_iterations = (UL)5000;
						else
							if (tmpstr != NULL && tmpstr == argv[arg + 1])
								arg++;
						break;
					case 'D': // msft
						if (tmpstr == NULL || sscanf(tmpstr, "%d", &device_number) != 1)
							device_number = 0;
						else
							if (tmpstr != NULL && tmpstr == argv[arg + 1])
								arg++;
						break;
					/* case 'd': is with case 'o': because they share code */
					case 'o': case 'd': /* 'o'utput and 'd'uplicate output files */
						i = argv[arg][1];
						if (tmpstr == NULL) {
							fprintf(stderr, "%s: no file name after -%c\n%s", program_name, i, Options);
							exit(1);
						}
						if (!strcmp(tmpstr, "stdout") || /* rest of condition is "-o-", "-o -", "-o -anythingelse" */
								(i == 'o' && (!strcmp(tmpstr, "-") || (argv[arg][2] == '\0' && argv[arg + 1][0] == '-'))))
							tmpfp = stdout; /* that 'rest' of the condition avoids "-ofile -n", "-o-file", etc */
						else
							if (!strcmp(tmpstr, "stderr") || (i == 'd' && (!strcmp(tmpstr, "-") || (argv[arg][2] == '\0' && argv[arg + 1][0] == '-'))))
								tmpfp = stderr;
							else
								if ((tmpfp = fopen(tmpstr, "a")) == NULL) {
									fprintf(stderr, "%s: could not open '%s' for append\n", program_name, tmpstr);
									perror(tmpstr);
									exit(errno);
								}
						if (tmpstr == argv[arg + 1] && (tmpstr[0] != '-' || tmpstr[1] == '\0'))
							arg++;
						if (i == 'o') { /* normal output */
							if (*outfp != NULL && *outfp != stdout && *outfp != stderr)
								fclose(*outfp);
							*outfp = tmpfp;
							if (*dupfp == *outfp)
								*dupfp = NULL; /* no point in duplicating the output to the same descriptor */
						} else { /* duplicate output, usually to get local copy when the normal output is via TCP/IP */
							if (*dupfp != NULL && *dupfp != stdout && *dupfp != stderr)
								fclose(*dupfp);
							if (tmpfp == *outfp)
								tmpfp = NULL;
							*dupfp = tmpfp;
						}
						tmpfp = NULL;
						break;
					case 'r':
						if (tmpstr == NULL || !isascii(tmpstr[0]) || !isdigit(tmpstr[0]) ||
								(tmpstr == argv[arg + 1] &&
								 (argv[arg + 2] == NULL || !isascii(argv[arg + 2][0]) || !isdigit(argv[arg + 2][0]))) ||
								(tmpstr != argv[arg + 1] &&
								 (argv[arg + 1] == NULL || !isascii(argv[arg + 1][0]) || !isdigit(argv[arg + 1][0])))) {
							fprintf(stderr, "%s: -r requires two numeric arguments\n%s", program_name, Options);
							exit(1);
						}
						sscanf(tmpstr, SCANF_FMT_UL, &start_range);
						if (tmpstr == argv[++arg])
							sscanf(argv[++arg], SCANF_FMT_UL, &stop_range);
						else
							sscanf(argv[arg], SCANF_FMT_UL, &stop_range);
						if (start_range < (UL)31 || stop_range > (~(UL)0)/2 || start_range > stop_range) {
							fprintf(stderr, "%s: -r start too small, stop too large, or start > stop\n", program_name);
							exit(1);
						}
						break;
					case 't':
						print_times = 1;
						break;
					case 'v':
						fprintf(stderr, "%s version information:\n %s\n", program_name, version_info);
						exit(0);
					default:
						fprintf(stderr, "%s: unknown option: '%s'\n%s", program_name, argv[arg], Options);
						exit(1);
				}
				arg++;
				break;
			default: /* anything except a leading '-' */
				tmpstr = argv[arg];
				char buffer[CHKPNT_FILENAME_LENGTH];
				tmpfp = fopen(tmpstr, "rb");
				if (tmpfp == NULL) {
					sprintf(buffer, "c%s", tmpstr);
					tmpfp = fopen(buffer,"rb");
					if (tmpfp == NULL) {
						sprintf(buffer, "t%s", tmpstr);
						tmpfp = fopen(buffer, "rb");
						if (tmpfp != NULL)
							fprintf(stdout, "%s: Resuming from backup checkpoint file %s\n", program_name, buffer);
						else
							fprintf(stderr, "%s: Could not find a checkpoint file to resume from\n", program_name);
					} else
						fprintf(stdout, "%s: Resuming from checkpoint file %s\n", program_name, buffer);
				} else
					fprintf(stdout, "%s: Resuming from checkpoint file %s\n", program_name, tmpstr);
				
				if (tmpfp != NULL) {
					*infp = tmpfp;
					first_time_here = 0;
					tmpfp = NULL;
				} else
					if (sscanf(argv[arg], SCANF_FMT_UL, &tmp) == 1) {
						*q = tmp;
						*infp = NULL;
						first_time_here = 0;
					} else {
						fprintf(stderr, "%s: tried to read '%s' as a check point file or list of exponents\n%s",
								program_name, argv[arg], Options);
						perror(program_name);
						exit(errno == 0 ? 1 : errno);
					}
				break;
		}
	}
	if (*infp == NULL && first_time_here) *infp = stdin;
	if (*outfp == NULL) *outfp = stdout;
	first_time_here = false;
	
	if (*infp != NULL && fscanf(*infp, " trial%c", str) == 1 && str[0] == 's') {
		/* gobble the digits, including any leading whitespace and escaped linefeeds and returns */
		while (((i = fgetc(*infp)) != EOF && isascii(i) && isspace(i)) || (i == '\\' && ((i = fgetc(*infp)) == '\n' || i == '\r')));
		while ((i != EOF && isascii(i) && isdigit(i)) || (i == '\\' && ((i = fgetc(*infp)) == '\n' || i == '\r')))
			i = fgetc(*infp);
	}   
	
	if (*infp == NULL || fscanf(*infp, SCANF_FMT_UL, q) == 1) { /* if there's no input file, *q is from the command line */
		if (*q < (UL)31) {
			fprintf(stderr, "%s: exponent " PRINTF_FMT_UL " is too small to test\n", program_name, *q);
			return(1);
		}
		if (*infp != NULL)
			switch (i = fgetc(*infp)) {
				default: /* unknown format; presume it's just a list of exponents */
					ungetc(i, *infp);
					/* fall thru */
				case '\n': /* list of exponents */
				case ' ':
					*M = 'U';
					break;
			}
		if (n != NULL) { /* must be LL testing, not factoring */
			if (*q < start_range || *q > stop_range)
				goto get_next_q;
			*M = 'U';
			if (last >= *q) { /* reset n in case it's too big for this new exponent */
				*n = 8L;
			}
			sprintf(chkpnt_cfn, "c" PRINTF_FMT_UL, *q);
			sprintf(chkpnt_tfn, "t" PRINTF_FMT_UL, *q);
			/*!!see if the checkpoint files already exist and continue from them? */
			/*!!can't easily use *infp to do it since that would lose track of where we are in the current input */
			/*!!would help to have new read_chkpoint() and save_chkpoint() functions */
			/*!!new good_chkpoint() function that returns flag: is checkpoint data just read consistent? */
			return(3);
		}
		return(1); /* incorrect call since we must be doing LL tests */
	}
	
	if (fscanf(*infp, "M(" SCANF_FMT_UL " )%c", q, M) == 2) {
		if (*q < (UL)31 || presence("UHIEeoqGCDdPJcLMlm", *M) == NULL) {
			fprintf(stderr, "%s: invalid data (exponent or letter 'code')\n", program_name);
			return(1); /* different format or error */
		}

		if (n != NULL) {
			while ((i = fgetc(*infp)) != EOF && i != '\n'); /* rest of line is useless to LL testers */ /*!!unless to make sure it's factored far enough */
			if (*q < start_range || *q > stop_range)
				goto get_next_q;
			if (last >= *q) { /* reset n in case it's too big for this new exponent */
				*n = 8L;
			}
			sprintf(chkpnt_cfn, "c" PRINTF_FMT_UL, *q);
			sprintf(chkpnt_tfn, "t" PRINTF_FMT_UL, *q);
			return(3);
		}
		return(1); /* incorrect call */
	}
	
	if (feof(*infp)) /* this was already checked except in the case of whitespace */
		goto get_next_q; /*  - including a solitary return or LF - in front of EOF */
	/* everything else is for Lucas-Lehmer testers */
	if (x == NULL) /* no place to store pointer to FFT array from checkpoint */
		return(1); /* then the caller goofed; let them know */
	/* check for printable/human readable checkpoint header; partial will become 7 if so */
	partial = fscanf(*infp, SCANF_FMT_ONE, q, n, j, err, &sBL, &sD, &RHM);
	if (partial < 0) {
		if (ferror(*infp)) return 1;
		else goto get_next_q; /* would be return(0) except that there might be more command line to parse */
	}
	
	if (partial == 0 && !ferror(*infp)) { /* check for binary checkpoint format */
		int r = read_check_point(*infp, q, n, j, err, x);
		if(r) {
			*infp = NULL;
			return r;
		}
	}
	
	if (partial != 7 || *n < ((double)(*q))/ROUNDED_HALF_MANTISSA + 4 || *q < (UL)31 || *q % 2 == 0 ||
			*j >= *q || *j < 1 || *err > 0.49 || (*err > 0.3 && *q < (UL)10000) || (sizeof(BIG_LONG) != sBL &&
				sBL != 4 && sBL != 8) || sizeof(double) != sD || ROUNDED_HALF_MANTISSA != RHM) {
		fprintf(stderr, "%s: inconsistent RI header (initial line)\n", program_name);
		return(1);
	}
	
	for (tmp2 = *n; (tmp2 & 1) == 0; tmp2 >>= 1);
	
	if (tmp2 != 1 && tmp2 != 3 && tmp2 != 5 && tmp2 != 7) {
		fprintf(stderr, "%s: inconsistent RI input; FFT run length not a power of 2\n", program_name);
		return(1);
	}
	while (*n < ((double)(*q))/ROUNDED_HALF_MANTISSA + 4.0)
		*n <<= 1;
	if (*x != NULL)
		free((char *)*x);
	
	if (((*x) = (double *)calloc((size_t)(*n + *n), sizeof(double))) == NULL) {
		perror(program_name);
		fprintf(stderr, "%s: cannot get memory for FFT array\n", program_name);
		return(1);
	}
	for (tmp2 = 0; tmp2 < *n; tmp2++)
		if (fscanf(*infp, SCANF_FMT_TWO, x[0] + tmp2) != 1) {
			perror(program_name);
			fprintf(stderr, "%s: error reading RI input (middle lines)\n", program_name);
			return(1);
		}
	
	if (fscanf(*infp, " RI " PRINTF_FMT_UL " done", &tmp2) != 1) {
		perror(program_name);
		fprintf(stderr, "%s: error reading RI input (last line)\n", program_name);
		return(1);
	}
	if (*q != tmp2) {
		fprintf(stderr, "%s: inconsistent RI input (last line)\n", program_name);
		return(1);
	}
	
	sprintf(chkpnt_cfn, "c" PRINTF_FMT_UL, *q);
	sprintf(chkpnt_tfn, "t" PRINTF_FMT_UL, *q);
	fclose (*infp);
	
	return 2; /*!!could get_next_q here also, but skip an incomplete checkpoint?? */
}
예제 #20
0
bool MultiUserChat::sendPresence(int AShow, const QString &AStatus)
{
	if (FStanzaProcessor)
	{
		Jid userJid(FRoomJid.node(),FRoomJid.domain(),FNickName);

		Stanza presence("presence");
		presence.setTo(userJid.full());

		QString showText;
		bool isConnecting = true;
		switch (AShow)
		{
		case IPresence::Online:
			showText = QString::null;
			break;
		case IPresence::Chat:
			showText = "chat";
			break;
		case IPresence::Away:
			showText = "away";
			break;
		case IPresence::DoNotDisturb:
			showText = "dnd";
			break;
		case IPresence::ExtendedAway:
			showText = "xa";
			break;
		default:
			isConnecting = false;
			showText = "unavailable";
		}

		if (!isConnecting)
			presence.setType("unavailable");
		else if (!showText.isEmpty())
			presence.addElement("show").appendChild(presence.createTextNode(showText));

		if (!AStatus.isEmpty())
			presence.addElement("status").appendChild(presence.createTextNode(AStatus));

		if (!isConnected() && isConnecting)
		{
			FRoomError = XmppError::null;
			emit chatAboutToConnect();

			QDomElement xelem = presence.addElement("x",NS_MUC);
			if (FHistory.empty || FHistory.maxChars>0 || FHistory.maxStanzas>0 || FHistory.seconds>0 || FHistory.since.isValid())
			{
				QDomElement histElem = xelem.appendChild(presence.createElement("history")).toElement();
				if (!FHistory.empty)
				{
					if (FHistory.maxChars > 0)
						histElem.setAttribute("maxchars",FHistory.maxChars);
					if (FHistory.maxStanzas > 0)
						histElem.setAttribute("maxstanzas",FHistory.maxStanzas);
					if (FHistory.seconds > 0)
						histElem.setAttribute("seconds",FHistory.seconds);
					if (FHistory.since.isValid())
						histElem.setAttribute("since",DateTime(FHistory.since).toX85UTC());
				}
				else
				{
					histElem.setAttribute("maxchars",0);
				}
			}
			if (!FPassword.isEmpty())
				xelem.appendChild(presence.createElement("password")).appendChild(presence.createTextNode(FPassword));
			if (FDiscovery && !FDiscovery->hasDiscoInfo(streamJid(),roomJid()))
				FDiscovery->requestDiscoInfo(streamJid(),roomJid());
		}
		else if (isConnected() && !isConnecting)
		{
			emit chatAboutToDisconnect();
		}

		if (FStanzaProcessor->sendStanzaOut(FStreamJid,presence))
		{
			LOG_STRM_INFO(FStreamJid,QString("Presence sent to conference, room=%1, show=%2").arg(FRoomJid.bare()).arg(AShow));
			FConnected = isConnecting;
			return true;
		}
		else
		{
			LOG_STRM_WARNING(FStreamJid,QString("Failed to send presence to conference, room=%1, show=%2").arg(FRoomJid.bare()).arg(AShow));
		}
	}
	else
	{
		REPORT_ERROR("Failed to send presence to conference: Required interfaces not found");
	}
	return false;
}