예제 #1
0
void Geolocation::positionChanged()
{
    ASSERT(isAllowed());

    // Stop all currently running timers.
    stopTimers();

    if (m_isSuspended) {
        m_hasChangedPosition = true;
        return;
    }

    makeSuccessCallbacks();
}
예제 #2
0
파일: RecordSet.cpp 프로젝트: Fangang/poco
std::size_t RecordSet::rowCount() const
{
	poco_assert (extractions().size());
	std::size_t rc = subTotalRowCount();
	if (!isFiltered()) return rc;

	std::size_t counter = 0;
	for (int row = 0; row < rc; ++row)
	{
		if (isAllowed(row)) ++counter;
	}

	return counter;
}
예제 #3
0
파일: Message.cpp 프로젝트: nazgee/libosock
const data_chunk& Message::getDeserializingRemains()
{
	if (!isAllowed(MSG_ALLOWED_REMAINS)) {
		WRN << "Why are you trying to read Remains (again)?" << std::endl;
		itsRemains.clear();
	}
	else {
		DBG << "You can now Pack() again!" << std::endl;
		setAllowed(MSG_ALLOWED_PACK);
		clearAllowed(MSG_ALLOWED_REMAINS);
	}

	return itsRemains;
}
예제 #4
0
    bool Slot::setItem(Item* item)
    {
        if(mItem == item)
            return false;
        if (item)
        {
            if (isAllowed(item) && isEmpty())
            {
                item->removeOldState();
                item->setOwner(mOwner);
                item->setParentSlot(this);
                if (canReady(item))
                    item->setState(GOS_READY);
                else
                    item->setState(GOS_HELD);

                mItem = item;
            }
            else
            {
                LOG_ERROR(Logger::RULES,
                    "Item '" + item->getName() + "' konnte nicht in den Slot '" + mName
                    + "' gelegt werden: " + (isAllowed(item) ? "'falscher Typ' " : "")
                    + (isEmpty() ? "'Slot schon belegt'" : "") + "!");
                return false;
            }
        }
        else
        {
            // this is the case, if the item is removed automatically
            // don't change this without looking at Item::setState
            mItem->removeOldState();
            mItem = NULL;
        }

        return true;
    }
예제 #5
0
파일: format.c 프로젝트: mhl/mysociety-cvs
/*
** Output nText characters zText as HTML.  Do not allow markup other
** than the markup for which isAllowed() returns true.
*/
static void output_restricted_html(const char *zText, int nText){
  int i, j, k;
  cgi_printf("<div>");
  for(i=0; i<nText; i++){
    if( zText[i]!='<' ) continue;
    k = 1 + (zText[i+1]=='/');
    for(j=k; isalnum(zText[i+j]); j++){}
    if( isAllowed(&zText[i+k], j-k) ) continue;
    cgi_printf("%.*s&lt;", i, zText);
    zText += i+1;
    nText -= i+1;
    i = -1;
  }
  cgi_printf("%.*s</div>", i, zText);
}
    KJS::UString JSObjectProxy::toString( KJS::ExecState *exec ) const {
        if ( !exec ) {
            kdWarning() << "JS toString with null state, ignoring" << endl;
            return KJS::UString();
        }
        if ( !isAllowed( exec->interpreter() ) ) {
            kdWarning() << "JS toString request from unknown interpreter, ignoring" << endl;
            return KJS::UString();
        }

        QString s( "%1 (%2)" );
        s = s.arg( obj ? obj->name() : "Dead Object" );
        s = s.arg( obj ? obj->className() : "" );
        return KJS::UString( s );
    }
예제 #7
0
void Geolocation::handlePendingPermissionNotifiers()
{
    // While we iterate through the list, we need not worry about list being modified as the permission 
    // is already set to Yes/No and no new listeners will be added to the pending list
    for (auto& notifier : m_pendingForPermissionNotifiers) {
        if (isAllowed()) {
            // start all pending notification requests as permission granted.
            // The notifier is always ref'ed by m_oneShots or m_watchers.
            if (startUpdating(notifier.get()))
                notifier->startTimerIfNeeded();
            else
                notifier->setFatalError(PositionError::create(PositionError::POSITION_UNAVAILABLE, failedToStartServiceErrorMessage));
        } else
            notifier->setFatalError(PositionError::create(PositionError::PERMISSION_DENIED, permissionDeniedErrorMessage));
    }
}
예제 #8
0
int setTimeout(ScriptState* scriptState, EventTarget& eventTarget, const String& handler, int timeout, const Vector<ScriptValue>&)
{
    ExecutionContext* executionContext = eventTarget.executionContext();
    if (!isAllowed(scriptState, executionContext, true))
        return 0;
    // Don't allow setting timeouts to run empty functions.  Was historically a
    // perfomance issue.
    if (handler.isEmpty())
        return 0;
    if (timeout >= 0 && executionContext->isDocument()) {
        // FIXME: Crude hack that attempts to pass idle time to V8. This should
        // be done using the scheduler instead.
        V8GCForContextDispose::instance().notifyIdle();
    }
    OwnPtrWillBeRawPtr<ScheduledAction> action = ScheduledAction::create(scriptState, handler);
    return DOMTimer::install(executionContext, action.release(), timeout, true);
}
예제 #9
0
void Geolocation::requestUsesCachedPosition(GeoNotifier* notifier) {
  DCHECK(isAllowed());

  notifier->runSuccessCallback(m_lastPosition);

  // If this is a one-shot request, stop it. Otherwise, if the watch still
  // exists, start the service to get updates.
  if (m_oneShots.contains(notifier)) {
    m_oneShots.remove(notifier);
  } else if (m_watchers.contains(notifier)) {
    if (notifier->options().timeout())
      startUpdating(notifier);
    notifier->startTimer();
  }

  if (!hasListeners())
    stopUpdating();
}
예제 #10
0
void Geolocation::positionChanged(PassRefPtr<Geoposition> newPosition)
{
    m_positionCache->setCachedPosition(newPosition.get());

    // Stop all currently running timers.
    stopTimers();
    
    if (!isAllowed()) {
        // requestPermission() will ask the chrome for permission. This may be
        // implemented synchronously or asynchronously. In both cases,
        // makeSuccessCallbacks() will be called if permission is granted, so
        // there's nothing more to do here.
        requestPermission();
        return;
    }

    makeSuccessCallbacks();
}
예제 #11
0
int
ShellExporter::exporte(string oldSession, string &content){
  vector<string>::iterator iter;
  vector<string> line;

  // Init the script
  content = "#!/bin/sh";
  content += " \n";

  // Check the user is alloed to export
  if (!muser.isAdmin() && !isAllowed(oldSession, muser)){
    throw IMSVishnuException(ERRCODE_INVEXPORT, "The user is not allowed to export this session");
  }

  // Check the session is closed
  if (!isClosed(oldSession)) {
    throw IMSVishnuException(ERRCODE_INVEXPORT, "The session id is invalid");
  }

  // The request, ordered by starttime (=submission)
  string req = "SELECT command.ctype, command.description, command.starttime from "
    " command, vsession where vsession.numsessionid=command.vsession_numsessionid and "
    " vsession.vsessionid='"+oldSession+"' order by starttime asc";

  boost::scoped_ptr<DatabaseResult> result (mdatabase->getResult(req.c_str()));

  // Adding all the results to the content
  for (size_t i = 0 ; i<result->getNbTuples(); i++) {
    line.clear();
    line = result->get(i);
    iter = line.begin();
    //MAPPER CREATION
    try {
      CmdType type = static_cast<CmdType>(convertToInt(*iter));
      Mapper* mapper = MapperRegistry::getInstance()->getMapper(getMapperName(type));
    content += mapper->decode(*(++iter));
    } catch (SystemException &e) {
      throw (e);
    }
    content += " \n";
  }

  return 0;
}
예제 #12
0
void Geolocation::handlePendingPermissionNotifiers()
{
    // While we iterate through the list, we need not worry about list being modified as the permission 
    // is already set to Yes/No and no new listeners will be added to the pending list
    GeoNotifierSet::const_iterator end = m_pendingForPermissionNotifiers.end();
    for (GeoNotifierSet::const_iterator iter = m_pendingForPermissionNotifiers.begin(); iter != end; ++iter) {
        GeoNotifier* notifier = iter->get();

        if (isAllowed()) {
            // start all pending notification requests as permission granted.
            // The notifier is always ref'ed by m_oneShots or m_watchers.
            if (startUpdating(notifier))
                notifier->startTimerIfNeeded();
            else
                notifier->setFatalError(PositionError::create(PositionError::POSITION_UNAVAILABLE, ASCIILiteral(failedToStartServiceErrorMessage)));
        } else
            notifier->setFatalError(PositionError::create(PositionError::PERMISSION_DENIED, ASCIILiteral(permissionDeniedErrorMessage)));
    }
}
예제 #13
0
Geoposition* Geolocation::lastPosition()
{
    ASSERT(isAllowed());

#if ENABLE(CLIENT_BASED_GEOLOCATION)
    if (!m_frame)
        return 0;

    Page* page = m_frame->page();
    if (!page)
        return 0;

    m_lastPosition = createGeoposition(page->geolocationController()->lastPosition());
#else
    m_lastPosition = m_service->lastPosition();
#endif

    return m_lastPosition.get();
}
예제 #14
0
void Geolocation::startRequest(GeoNotifier *notifier)
{
    // Check whether permissions have already been denied. Note that if this is the case,
    // the permission state can not change again in the lifetime of this page.
    if (isDenied())
        notifier->setFatalError(PositionError::create(PositionError::PERMISSION_DENIED, permissionDeniedErrorMessage));
    else if (haveSuitableCachedPosition(notifier->options()))
        notifier->setUseCachedPosition();
    else if (notifier->hasZeroTimeout())
        notifier->startTimerIfNeeded();
    else if (!isAllowed()) {
        // if we don't yet have permission, request for permission before calling startUpdating()
        m_pendingForPermissionNotifiers.add(notifier);
        requestPermission();
    } else if (startUpdating(notifier))
        notifier->startTimerIfNeeded();
    else
        notifier->setFatalError(PositionError::create(PositionError::POSITION_UNAVAILABLE, failedToStartServiceErrorMessage));
}
    void JSObjectProxy::put( KJS::ExecState *exec,
                             const KJS::Identifier &p, const KJS::Value &v,
                             int attr ) {
        if ( !isAllowed( exec->interpreter() ) ) {
            kdWarning() << "JS put request from unknown interpreter, ignoring" << endl;
            return ;
        }

        if ( !policy->hasCapability( JSSecurityPolicy::CapabilitySetProperties ) ) {
            ObjectImp::put( exec, p, v, attr );
            return ;
        }

        if ( !obj ) {
            kdDebug( 80001 ) << "JS setting '" << p.ascii() << "' but qobj has died" << endl;
            ObjectImp::put( exec, p, v, attr );
            return ;
        }

        // Properties
        QMetaObject *meta = obj->metaObject();
        int propIndex = meta->findProperty( p.ascii(), true );
        if ( propIndex != -1 ) {
            QVariant val = convertToVariant( exec, v );
            if ( meta->property(propIndex, true)->isEnumType() ) {
                obj->setProperty( p.ascii(), val.toUInt() );
            } else if ( val.isValid() ) {
                obj->setProperty( p.ascii(), val );
            } else {
                kdWarning(80001) << "Error setting value." << endl;
            }
        } else {
            ObjectImp::put( exec, p, v, attr );
        }

        if ( jspart->factory() ->eventMapper() ->isEventHandler( p ) ) {
            if ( evproxy.isNull() )
                evproxy = new KJSEmbed::JSObjectEventProxy( this );
            evproxy->addFilter( jspart->factory() ->eventMapper() ->findEventType( p ) );
            kdDebug( 80001 ) << "Adding event handler " << p.ascii() << endl;
        }
    }
예제 #16
0
void Geolocation::requestUsesCachedPosition(GeoNotifier* notifier)
{
    // This is called asynchronously, so the permissions could have been denied
    // since we last checked in startRequest.
    if (isDenied()) {
        notifier->setFatalError(PositionError::create(PositionError::PERMISSION_DENIED, permissionDeniedErrorMessage));
        return;
    }

    m_requestsAwaitingCachedPosition.add(notifier);

    // If permissions are allowed, make the callback
    if (isAllowed()) {
        makeCachedPositionCallbacks();
        return;
    }

    // Request permissions, which may be synchronous or asynchronous.
    requestPermission();
}
예제 #17
0
파일: menu.cpp 프로젝트: cgloeckner/SfmlExt
void Input::handle(sf::Uint32 unicode) {
	auto text = getString();
	bool allowed = true;
	if (unicode == '\b') {
		// handle backspace
		text = text.substring(0u, text.getSize() - 1u);
	} else {
		allowed = isAllowed(unicode);
		if (allowed) {
			// add character
			text += unicode;
		}
	}
	if (allowed) {
		setString(text);
	}
	if (typing != nullptr) {
		typing(unicode, allowed);
	}
}
bool TableModelVariables::canDropMimeData(const QMimeData *data, Qt::DropAction action, int, int, const QModelIndex &) const
{
	if (_dragActions == Qt::CopyAction && _dropActions == Qt::MoveAction && action == Qt::MoveAction) // if delete
		return true;

	if (data->hasFormat(_mimeType))
	{
		QByteArray encodedData = data->data(_mimeType);

		Terms variables;
		variables.set(encodedData);

		foreach (const Term &variable, variables)
		{
			if ( ! isAllowed(variable))
				return false;
		}

		return true;
	}
예제 #19
0
/*---------------------------------------------------------------------------*/
static void receiver(struct simple_udp_connection *c, const uip_ipaddr_t *sender_addr, uint16_t sender_port, const uip_ipaddr_t *receiver_addr, uint16_t receiver_port, const uint8_t *data, uint16_t datalen)
{
	C(data)[datalen] = '\0';
	int id;
	char cmd = jsonData(C(data), "cmd")[0];
	uip_ipaddr_t addr;

	if(cmd == 'g'){ /* GET SENSOR STATUS */
		id = atoi(jsonData(C(data),"id"));
		sensorsList[id].status = atoi(jsonData(C(data),"st"));
		if(sensorsList[id].type == SENSOR_NONE)
			sensorsList[id].type = atoi(jsonData(C(data),"ty"));
		sensorsList[id].lastTime = 0;
		sensorsList[id].failedTimeouts = 0;

		updateDataToServer(C(data)); /* SEND DATA TO RASPBERRY PI */
	}else if(cmd == 'c'){
		id = atoi(jsonData(C(data),"id"));
		sensorsList[id].status = atoi(jsonData(C(data),"st"));
		sensorsList[id].lastTime = 0;
		sensorsList[id].failedTimeouts = 0;

		if(isAllowed(jsonData(C(data),"key")) == 0)
			return;

		uip_create_linklocal_allnodes_mcast(&addr);
		if(isAlarmEnabled == 0){ /* ALARM IS DISABLED */
			isAlarmEnabled = 1;
			sprintf(string6LOWPAN,"{\"cmd\":\"l\"}");

		}else{ /*ALARM IS ENABLED*/
			isAlarmEnabled = 0;
			sprintf(string6LOWPAN,"{\"cmd\":\"u\"}");

		}
		simple_udp_sendto(&broadcast_connection, string6LOWPAN, strlen(string6LOWPAN), &addr);

		updateDataToServer(C(data));
		updateDataToServer(C(string6LOWPAN));
	}
}
예제 #20
0
void Geolocation::makeSuccessCallbacks(Geoposition& position)
{
    ASSERT(lastPosition());
    ASSERT(isAllowed());
    
    auto oneShotsCopy = copyToVector(m_oneShots);
    
    GeoNotifierVector watchersCopy;
    m_watchers.getNotifiersVector(watchersCopy);
    
    // Clear the lists before we make the callbacks, to avoid clearing notifiers
    // added by calls to Geolocation methods from the callbacks, and to prevent
    // further callbacks to these notifiers.
    m_oneShots.clear();

    sendPosition(oneShotsCopy, position);
    sendPosition(watchersCopy, position);

    if (!hasListeners())
        stopUpdating();
}
예제 #21
0
bool RecordSet::moveFirst()
{
	if (subTotalRowCount() > 0)
	{
		if (!isFiltered())
		{
			_currentRow = 0;
			return true;
		}

		std::size_t currentRow = 0;
		while (!isAllowed(currentRow))
		{
			if (currentRow >= subTotalRowCount() - 1) return false;
			++currentRow;
		}

		_currentRow = currentRow;
		return true;
	}
	else return false;
}
예제 #22
0
bool RecordSet::moveLast()
{
	if (subTotalRowCount() > 0)
	{
		std::size_t currentRow = subTotalRowCount() - 1;
		if (!isFiltered())
		{
			_currentRow = currentRow;
			return true;
		}

		while (!isAllowed(currentRow))
		{
			if (currentRow <= 0) return false;
			--currentRow;
		}

		_currentRow = currentRow;
		return true;
	}
	else return false;
}
예제 #23
0
void Geolocation::setIsAllowed(bool allowed)
{
    // Protect the Geolocation object from garbage collection during a callback.
    Ref<Geolocation> protect(*this);

    // This may be due to either a new position from the service, or a cached
    // position.
    m_allowGeolocation = allowed ? Yes : No;
    
    if (m_isSuspended)
        return;

    // Permission request was made during the startRequest process
    if (!m_pendingForPermissionNotifiers.isEmpty()) {
        handlePendingPermissionNotifiers();
        m_pendingForPermissionNotifiers.clear();
        return;
    }

    if (!isAllowed()) {
        RefPtr<PositionError> error = PositionError::create(PositionError::PERMISSION_DENIED,  ASCIILiteral(permissionDeniedErrorMessage));
        error->setIsFatal(true);
        handleError(error.get());
        m_requestsAwaitingCachedPosition.clear();
        m_hasChangedPosition = false;
        m_errorWaitingForResume = nullptr;

        return;
    }

    // If the service has a last position, use it to call back for all requests.
    // If any of the requests are waiting for permission for a cached position,
    // the position from the service will be at least as fresh.
    if (lastPosition())
        makeSuccessCallbacks();
    else
        makeCachedPositionCallbacks();
}
int RegistrationHandler::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 6)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 6;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< bool*>(_v) = isAllowed(); break;
        case 1: *reinterpret_cast< QString*>(_v) = statusMessage(); break;
        case 2: *reinterpret_cast< bool*>(_v) = isTemporaryError(); break;
        }
        _id -= 3;
    } else if (_c == QMetaObject::WriteProperty) {
        _id -= 3;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 3;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
예제 #25
0
void Geolocation::startRequest(GeoNotifier *notifier)
{
    if (frame()->settings()->strictPowerfulFeatureRestrictions()) {
        String errorMessage;
        if (!executionContext()->isSecureContext(errorMessage)) {
            notifier->setFatalError(PositionError::create(PositionError::POSITION_UNAVAILABLE, errorMessage));
            return;
        }
    }

    if (RuntimeEnabledFeatures::restrictIFramePermissionsEnabled()) {
        // TODO(keenanb): kill the request if the parent is blocking the requester
        Element* owner = document()->ownerElement();
        if (owner && owner->hasAttribute(HTMLNames::permissionsAttr)) {
            String errorMessage = "A cross-origin iframe needs its permissions attribute properly set in order to use the geolocation API.";
            notifier->setFatalError(PositionError::create(PositionError::POSITION_UNAVAILABLE, errorMessage));
            return;
        }
    }

    // Check whether permissions have already been denied. Note that if this is the case,
    // the permission state can not change again in the lifetime of this page.
    if (isDenied())
        notifier->setFatalError(PositionError::create(PositionError::PERMISSION_DENIED, permissionDeniedErrorMessage));
    else if (haveSuitableCachedPosition(notifier->options()))
        notifier->setUseCachedPosition();
    else if (!notifier->options().timeout())
        notifier->startTimer();
    else if (!isAllowed()) {
        // if we don't yet have permission, request for permission before calling startUpdating()
        m_pendingForPermissionNotifiers.add(notifier);
        requestPermission();
    } else if (startUpdating(notifier))
        notifier->startTimer();
    else
        notifier->setFatalError(PositionError::create(PositionError::POSITION_UNAVAILABLE, failedToStartServiceErrorMessage));
}
예제 #26
0
bool Geolocation::startUpdating(GeoNotifier* notifier)
{
#if ENABLE(CLIENT_BASED_GEOLOCATION)
    // FIXME: Pass options to client.

    if (!isAllowed()) {
        m_startRequestPermissionNotifier = notifier;
        requestPermission();
        return true;
    }
    
    if (!m_frame)
        return false;

    Page* page = m_frame->page();
    if (!page)
        return false;

    page->geolocationController()->addObserver(this);
    return true;
#else
    return m_service->startUpdating(notifier->m_options.get());
#endif
}
예제 #27
0
int main(int argc, char *argv[]) {
    srand(argc * 17);
    if (/*argc != 3 &&*/ argc != 4) {  // TODO: non-implemented case
        printUsage(argv[0]);
        exit(EXIT_FAILURE);
    }
    else {
        const char *sampleDirectory = strdup(argv[1]);
        const char *resultFile = strdup(argv[2]);
        const char *modelFile = "";
        if (argc == 4) {
            modelFile = strdup(argv[3]);
        }

        try {
            ImageSet images(sampleDirectory);
            PatchPositions result(resultFile);

            std::vector <std::string> names = images.getNames();
            std::vector <std::vector <double> > descriptorSet;
            std::vector <int> answerSet;
            std::cerr << names.size() << " files are found." << std::endl;
            int progress = 0;
            for (std::vector <std::string>::iterator imageName = names.begin();
                 imageName != names.end();
                 ++imageName) {
                progress += 1;
                Sample sample(images.getImage(*imageName));

                std::vector <Rectangle> pRects = result.getPositions(*imageName);
                std::vector <int> pPos(pRects.size());
                for (int i = 0; i < (int)pRects.size(); i++) {
                    pPos[i] = pRects[i].left();
                }
                std::sort(pPos.begin(), pPos.end());

                // Pedestrian patches
                std::cerr << "\b\b\b\b\b" << 100 * progress / names.size() << " %";
                for (std::vector <int>::iterator pos = pPos.begin(); pos != pPos.end(); ++pos) {
                    descriptorSet.push_back(sample.getDescriptor(*pos));
                    answerSet.push_back(ANSWER_PEDESTRIAN);
                }

                // Background patches
                std::vector <bool> isAllowed(sample.maximalShift(), true);
                for (std::vector <int>::iterator pos = pPos.begin(); pos != pPos.end(); ++pos) {
                    int start = std::max(0, *pos - PATCH_WIDTH / 2);
                    int end = std::min(*pos + PATCH_WIDTH / 2, (int)isAllowed.size());
                    for (int i = start; i < end; i++) {
                        isAllowed[i] = false;
                    }
                }
                int bgCount = 0;
                for (int i = 0; i < (int)isAllowed.size(); i++) {
                    if (isAllowed[i]) {
                        bgCount += 1;
                    }
                }
                if (bgCount != 0) {
                    for (int bgNum = 0; bgNum < BACKGROUND_PER_SAMPLE; bgNum++) {
                        int number = rand() % bgCount + 1;
                        int x = -1;
                        do {
                            x += 1;
                            while (!isAllowed[x]) {
                                x += 1;
                            }
                            number -= 1;
                        } while (number > 0);
                        descriptorSet.push_back(sample.getDescriptor(x));
                        answerSet.push_back(ANSWER_BACKGROUND);
                    }
                }
            }
            std::cerr << "\b\b\b\b\b";

            std::cerr << "There are " << descriptorSet.size() << " pathces." << std::endl;

            LinearSVM(descriptorSet, answerSet, 1.0).save(modelFile);
        }
        catch (const char *e) {
            std::cerr << "Error: " << e << std::endl;
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}
예제 #28
0
파일: worker.cpp 프로젝트: HunterChen/zurl
	void start(const QVariant &vrequest, Mode mode)
	{
		outSeq = 0;
		outCredits = 0;
		quiet = false;

		ZhttpRequestPacket request;
		if(!request.fromVariant(vrequest))
		{
			log_warning("failed to parse zurl request");

			QVariantHash vhash = vrequest.toHash();
			rid = vhash.value("id").toByteArray();
			toAddress = vhash.value("from").toByteArray();
			QByteArray type = vhash.value("type").toByteArray();
			if(!toAddress.isEmpty() && type != "error" && type != "cancel")
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			}
			else
			{
				cleanup();
				QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection);
			}

			return;
		}

		rid = request.id;
		toAddress = request.from;
		userData = request.userData;
		sentHeader = false;
		stuffToRead = false;
		bytesReceived = 0;

		ignorePolicies = request.ignorePolicies;

		if(request.uri.isEmpty())
		{
			log_warning("missing request uri");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		QString scheme = request.uri.scheme();
		if(scheme == "https" || scheme == "http")
		{
			transport = HttpTransport;
		}
		else if(scheme == "wss" || scheme == "ws")
		{
			transport = WebSocketTransport;
		}
		else
		{
			log_warning("unsupported scheme");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		if(transport == WebSocketTransport && mode != Worker::Stream)
		{
			log_warning("websocket must be used from stream interface");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		int defaultPort;
		if(scheme == "https" || scheme == "wss")
			defaultPort = 443;
		else // http || wss
			defaultPort = 80;

		HttpHeaders headers = request.headers;

		if(transport == HttpTransport)
		{
			// fire and forget
			if(mode == Worker::Stream && (rid.isEmpty() || toAddress.isEmpty()))
				quiet = true;

			// streaming only allowed on streaming interface
			if(mode == Worker::Stream)
				outStream = request.stream;
			else
				outStream = false;

			if(request.method.isEmpty())
			{
				log_warning("missing request method");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			log_info("IN id=%s, %s %s", request.id.data(), qPrintable(request.method), request.uri.toEncoded().data());

			// inbound streaming must start with sequence number of 0
			if(mode == Worker::Stream && request.more && request.seq != 0)
			{
				log_warning("streamed input must start with seq 0");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			// can't use these two together
			if(mode == Worker::Single && request.more)
			{
				log_warning("cannot use streamed input on router interface");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			bodySent = false;

			inSeq = request.seq;

			if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
				return;
			}

			QByteArray hostHeader = request.uri.host().toUtf8();

			// only tack on the port if it isn't being overridden
			int port = request.uri.port(defaultPort);
			if(request.connectPort == -1 && port != defaultPort)
				hostHeader += ":" + QByteArray::number(port);

			headers.removeAll("Host");
			headers += HttpHeader("Host", hostHeader);

			hreq = new HttpRequest(dns, this);
			connect(hreq, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
			connect(hreq, SIGNAL(readyRead()), SLOT(req_readyRead()));
			connect(hreq, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
			connect(hreq, SIGNAL(error()), SLOT(req_error()));

			maxResponseSize = request.maxSize;
			sessionTimeout = request.timeout;

			if(!request.connectHost.isEmpty())
				hreq->setConnectHost(request.connectHost);
			if(request.connectPort != -1)
				request.uri.setPort(request.connectPort);

			hreq->setIgnoreTlsErrors(request.ignoreTlsErrors);
			if(request.followRedirects)
				hreq->setFollowRedirects(8);

			if(request.credits != -1)
				outCredits += request.credits;
		}
		else // WebSocketTransport
		{
			log_info("IN id=%s, %s", request.id.data(), request.uri.toEncoded().data());

			// inbound streaming must start with sequence number of 0
			if(request.seq != 0)
			{
				log_warning("websocket input must start with seq 0");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			if(toAddress.isEmpty())
			{
				log_warning("websocket input must provide from address");

				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
				return;
			}

			inSeq = request.seq;

			if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
				return;
			}

			QByteArray hostHeader = request.uri.host().toUtf8();

			// only tack on the port if it isn't being overridden
			int port = request.uri.port(defaultPort);
			if(request.connectPort == -1 && port != defaultPort)
				hostHeader += ":" + QByteArray::number(port);

			headers.removeAll("Host");
			headers += HttpHeader("Host", hostHeader);

			ws = new WebSocket(dns, this);
			connect(ws, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
			connect(ws, SIGNAL(connected()), SLOT(ws_connected()));
			connect(ws, SIGNAL(readyRead()), SLOT(ws_readyRead()));
			connect(ws, SIGNAL(framesWritten(int)), SLOT(ws_framesWritten(int)));
			connect(ws, SIGNAL(peerClosing()), SLOT(ws_peerClosing()));
			connect(ws, SIGNAL(closed()), SLOT(ws_closed()));
			connect(ws, SIGNAL(error()), SLOT(ws_error()));

			if(!request.connectHost.isEmpty())
				ws->setConnectHost(request.connectHost);
			if(request.connectPort != -1)
				request.uri.setPort(request.connectPort);

			ws->setIgnoreTlsErrors(request.ignoreTlsErrors);
			ws->setMaxFrameSize(config->sessionBufferSize);

			if(request.credits != -1)
				outCredits += request.credits;
		}

		httpActivityTimer = new QTimer(this);
		connect(httpActivityTimer, SIGNAL(timeout()), SLOT(httpActivity_timeout()));
		httpActivityTimer->setSingleShot(true);
		httpActivityTimer->start(config->activityTimeout * 1000);

		if(sessionTimeout != -1)
		{
			httpSessionTimer = new QTimer(this);
			connect(httpSessionTimer, SIGNAL(timeout()), SLOT(httpSession_timeout()));
			httpSessionTimer->setSingleShot(true);
			httpSessionTimer->start(sessionTimeout);
		}

		if(transport == WebSocketTransport || (transport == HttpTransport && mode == Worker::Stream))
		{
			expireTimer = new QTimer(this);
			connect(expireTimer, SIGNAL(timeout()), SLOT(expire_timeout()));
			expireTimer->setSingleShot(true);
			expireTimer->start(SESSION_EXPIRE);

			keepAliveTimer = new QTimer(this);
			connect(keepAliveTimer, SIGNAL(timeout()), SLOT(keepAlive_timeout()));
			keepAliveTimer->start(SESSION_EXPIRE / 2);
		}

		if(transport == HttpTransport)
		{
			if(!request.body.isEmpty() && !request.more && !headers.contains("Content-Length"))
				headers += HttpHeader("Content-Length", QByteArray::number(request.body.size()));

			bool hasOrMightHaveBody = (!request.body.isEmpty() || request.more);

			hreq->start(request.method, request.uri, headers, hasOrMightHaveBody);

			if(hasOrMightHaveBody)
			{
				if(!request.body.isEmpty())
					hreq->writeBody(request.body);

				if(!request.more)
				{
					bodySent = true;
					hreq->endBody();
				}
			}
			else
				bodySent = true;

			if(mode == Stream)
			{
				if(request.more)
				{
					// send cts
					ZhttpResponsePacket resp;
					resp.type = ZhttpResponsePacket::Credit;
					resp.credits = config->sessionBufferSize;
					writeResponse(resp);
				}
				else
				{
					// send ack
					ZhttpResponsePacket resp;
					resp.type = ZhttpResponsePacket::KeepAlive;
					writeResponse(resp);
				}
			}
		}
		else // WebSocketTransport
		{
			ws->start(request.uri, headers);
		}
	}
예제 #29
0
	void start(const QVariant &vrequest, Mode mode)
	{
		outSeq = 0;

		ZurlRequestPacket request;
		if(!request.fromVariant(vrequest))
		{
			log_warning("failed to parse zurl request");

			QVariantHash vhash = vrequest.toHash();
			rid = vhash.value("id").toByteArray();
			assert(!rid.isEmpty()); // app layer ensures this
			receiver = vhash.value("sender").toByteArray();
			bool cancel = vhash.value("cancel").toBool();
			if(!receiver.isEmpty() && !cancel)
			{
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			}
			else
			{
				cleanup();
				QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection);
			}

			return;
		}

		rid = request.id;
		receiver = request.sender;
		outCredits = 0;
		userData = request.userData;
		quiet = false;
		sentHeader = false;
		stuffToRead = false;
		bytesReceived = 0;

		ignorePolicies = request.ignorePolicies;

		// streaming only allowed on streaming interface
		if(mode == Worker::Stream)
			outStream = request.stream;
		else
			outStream = false;

		// some required fields
		if(request.method.isEmpty() || request.uri.isEmpty())
		{
			log_warning("missing request method or missing uri");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		log_info("IN id=%s, %s %s", request.id.data(), qPrintable(request.method), request.uri.toEncoded().data());

		// inbound streaming must start with sequence number of 0
		if(mode == Worker::Stream && request.more && request.seq != 0)
		{
			log_warning("streamed input must start with seq 0");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		// fire and forget
		if(mode == Worker::Stream && receiver.isEmpty())
			quiet = true;

		// can't use these two together
		if(mode == Worker::Single && request.more)
		{
			log_warning("cannot use streamed input on router interface");

			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request"));
			return;
		}

		bodySent = false;

		inSeq = request.seq;

		if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost)))
		{
			QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation"));
			return;
		}

		hreq = new HttpRequest(dns, this);
		connect(hreq, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &)));
		connect(hreq, SIGNAL(readyRead()), SLOT(req_readyRead()));
		connect(hreq, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
		connect(hreq, SIGNAL(error()), SLOT(req_error()));
		maxResponseSize = request.maxSize;
		if(!request.connectHost.isEmpty())
			hreq->setConnectHost(request.connectHost);

		hreq->setIgnoreTlsErrors(request.ignoreTlsErrors);

		if(request.credits != -1)
			outCredits += request.credits;

		HttpHeaders headers = request.headers;
		// ensure content-length (or overwrite it, if not streaming input)
		if((request.method == "POST" || request.method == "PUT") && (!headers.contains("content-length") || !request.more))
			headers += HttpHeader("Content-Length", QByteArray::number(request.body.size()));

		timer = new QTimer(this);
		connect(timer, SIGNAL(timeout()), SLOT(timer_timeout()));
		timer->setSingleShot(true);
		timer->start(config->sessionTimeout * 1000);

		hreq->start(request.method, request.uri, headers);

		// note: unlike follow-up requests, the initial request is assumed to have a body.
		//   if no body field is present, we act as if it is present but empty.

		if(!request.body.isEmpty())
		{
			if(request.more && !request.headers.contains("content-length"))
			{
				log_warning("streamed input requires content-length");
				QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "length-required"));
				return;
			}

			hreq->writeBody(request.body);
		}

		if(!request.more)
		{
			bodySent = true;
			hreq->endBody();
		}
		else
		{
			// send cts
			ZurlResponsePacket resp;
			resp.credits = config->sessionBufferSize;
			writeResponse(resp);
		}
	}
예제 #30
0
int main( int argc, char* args[] )
{
    //Initialize all SDL subsystems
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
        return 1;
    }

    //Set up the screen
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //If there was an error in setting up the screen
    if( screen == NULL )
    {
        return 1;
    }

    //Set the window caption
    SDL_WM_SetCaption( "Donkey Kong", NULL );

    //Load the images
    SDL_Surface* mario = load_image("img/mario.bmp" );
    Uint32 colorkey = SDL_MapRGB(mario->format, 0, 255, 0);
    SDL_SetColorKey(mario, SDL_SRCCOLORKEY, colorkey);

    SDL_Surface* tonneau = load_image("img/todd.bmp");
    colorkey = SDL_MapRGB( tonneau->format, 4, 242, 77 );
    SDL_SetColorKey(tonneau, SDL_SRCCOLORKEY, colorkey);

    SDL_Surface* sol = load_image("img/sol.bmp");
    colorkey = SDL_MapRGB( sol->format, 0, 0, 0);
    SDL_SetColorKey(sol, SDL_SRCCOLORKEY, colorkey);

    SDL_Surface* echelle = load_image("img/echelle.bmp");
    colorkey = SDL_MapRGB( echelle->format, 0, 0, 0);
    SDL_SetColorKey(sol, SDL_SRCCOLORKEY, colorkey);


    mariow = mario->w;

    sol_rect.minx = 0;
    sol_rect.maxx = SCREEN_WIDTH;
    sol_rect.miny = SCREEN_HEIGHT - sol->h - mario->h - 5;
    sol_rect.maxy = SCREEN_HEIGHT - sol->h - mario->h + 5;

    ech_rect.minx = 500;
    ech_rect.maxx = ech_rect.minx + echelle->w;
    ech_rect.miny = sol_rect.maxy - echelle->h;
    ech_rect.maxy = sol_rect.maxy;


    //Apply the message to the screen

    int mariox = 0;
    int marioy = SCREEN_HEIGHT - sol->h - mario->h;
    int tonnx = 200;
    int tonny = 10;

    int echellex = 500;

    int quit = 0;
    while (!quit) {

        /* Update the screen */
        // fill the screen with black
        SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
        // dessiner le sol
        int x;
        for (x = 0; x < SCREEN_WIDTH; x += sol->w) {
            apply_surface(x, SCREEN_HEIGHT-sol->h, sol, screen);
        }
        // dessiner l'echelle
        apply_surface(echellex, SCREEN_HEIGHT-sol->h-echelle->h, echelle, screen);

        // dessiner le mario
        apply_surface(mariox, marioy, mario, screen );
        // dessiner le tonneau
        apply_surface(tonnx,  tonny,  tonneau, screen);
        // maj l'ecran
        if( SDL_Flip( screen ) == -1 )
        {
            return 1;
        }

        // Attendre un 10eme de seconde
        SDL_Delay( 100 ); // en milli-secondes

        // handle events
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = 1;
            }
        }
        Uint8 *keyState = SDL_GetKeyState(0);
        if (keyState[SDLK_ESCAPE]) {  // echap = quitter le jeu
            quit = 1;
        }

        // bouger le mario
        if (keyState[SDLK_LEFT]) { // bouge vers la gauche
            mariox -= 10;
            if (!isAllowed(mariox, marioy)) mariox += 10;
        }
        if (keyState[SDLK_RIGHT]) { // bouge vers la droite
            mariox += 10;
            if (!isAllowed(mariox, marioy)) mariox -= 10;
        }
        if (keyState[SDLK_UP]) {
            marioy -= 10;
            if (!isAllowed(mariox, marioy)) marioy += 10;
        }
        if (keyState[SDLK_DOWN]) {
            marioy += 10;
            if (!isAllowed(mariox, marioy)) marioy -= 10;
        }

        // bouger le tonneau
        tonny += 15;
        if (tonny > SCREEN_HEIGHT) tonny = 0;

    }

    //Free the surfaces
    SDL_FreeSurface(echelle);
    SDL_FreeSurface(sol);
    SDL_FreeSurface(tonneau);
    SDL_FreeSurface(mario);

    //Quit SDL
    SDL_Quit();

    return 0;
}