Exemple #1
0
/**
 *
 * @brief check if we reached the end
 */
bool evePosCalc::donefuncAdd(){

    bool done = false;

    if (axisType == eveSTRING){
        sendError(ERROR, "stepfunction add may be used with integer, double or datetime values only");
        done = true;
    }
    else {
        // special treatment for double
        if ((currentPos.getType() == eveDOUBLE)){
            double currentDouble = currentPos.toDouble();
            if (((stepWidth >=0) && ((currentDouble + fabs(1.0e-12 * currentDouble)) >= endPosAbs.toDouble())) ||
                    ((stepWidth < 0) && ((currentDouble - fabs(1.0e-12 * currentDouble)) <= endPosAbs.toDouble()))){
                done = true;
            }
        }
        else if (((stepWidth >=0) && (currentPos >= endPosAbs)) || ((stepWidth < 0) && (currentPos <= endPosAbs))){
            if (currentPos.getType() == eveDateTimeT)
                sendError(DEBUG, QString("at end: current position %1 endPosAbs %2 (%3)").arg(currentPos.toDateTime().toString()).arg(endPosAbs.toDateTime().toString()).arg(stepWidth.toDouble()));
            else
                sendError(DEBUG, QString("at end: current position %1 endPosAbs %2 (%3)").arg(currentPos.toInt()).arg(endPosAbs.toInt()).arg(stepWidth.toDouble()));
            done = true;
        }
    }
    return done;
}
Exemple #2
0
//---------------------------------------------------------------------------
// AGL init
//---------------------------------------------------------------------------
bool Pipe::configInit()
{
    CGDirectDisplayID displayID = CGMainDisplayID();
    const uint32_t device = getPipe()->getDevice();

    if( device != LB_UNDEFINED_UINT32 )
    {
        CGDirectDisplayID *displayIDs = static_cast< CGDirectDisplayID* >(
            alloca( (device+1) * sizeof( displayIDs )));
        CGDisplayCount    nDisplays;

        if( CGGetOnlineDisplayList( device+1, displayIDs, &nDisplays ) !=
            kCGErrorSuccess )
        {
            sendError( ERROR_AGLPIPE_DISPLAYS_NOTFOUND );
            return false;
        }

        if( nDisplays <= device )
        {
            sendError( ERROR_AGLPIPE_DEVICE_NOTFOUND );
            return false;
        }

        displayID = displayIDs[device];
    }

    _setCGDisplayID( displayID );
    LBVERB << "Using CG displayID " << displayID << std::endl;
    return true;
}
Exemple #3
0
/**
 *
 * @param stepfile name of file with steps
 */
void evePosCalc::setStepFile(QString stepfilename) {

    if (stepmode != FILE) return;

    posIntList.clear();
    posDoubleList.clear();
    positionList.clear();
    QFileInfo fileInfo(stepfilename);
    if (fileInfo.isRelative()){
        //TODO we might add an absolute Path from environment or parameter
    }
    if (fileInfo.exists() && fileInfo.isReadable()){
        QFile file(fileInfo.absoluteFilePath());
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
            QTextStream inStream(&file);
            bool ok;
            while (!inStream.atEnd()) {
                QString line = inStream.readLine().trimmed();
                if (line.isEmpty()) continue;
                if (axisType == eveINT){
                    int value = line.toInt(&ok);
                    if (ok)
                        posIntList.append(value);
                    else
                        sendError(ERROR, QString("unable to convert >%1< to integer position from file %2").arg(line).arg(fileInfo.absoluteFilePath()));
                } else if (axisType == eveDOUBLE){
                    double value = line.toDouble(&ok);
                    if (ok)
                        posDoubleList.append(value);
                    else
                        sendError(ERROR, QString("unable to convert >%1< to double position from file %2").arg(line).arg(fileInfo.absoluteFilePath()));
                } else if (axisType == eveSTRING){
                    positionList.append(line);
                }
            }
            if((posIntList.count() == 0) && (posDoubleList.count() == 0) && (positionList.count() == 0))
                sendError(ERROR, QString("position file is empty: %1").arg(fileInfo.absoluteFilePath()));
            file.close();
        }
        else {
            sendError(ERROR, QString("unable to open position file %1").arg(fileInfo.absoluteFilePath()));
        }
    }
    else {
        sendError(ERROR, QString("position file does not exist or is not readable: %1").arg(fileInfo.absoluteFilePath()));
    }
    if ((axisType == eveINT) && (posIntList.count() > 0)){
        startPos = posIntList.first();
        endPos = posIntList.last();
        expectedPositions = posIntList.count();
    } else if ((axisType == eveDOUBLE) && (posDoubleList.count() > 0)){
        startPos = posDoubleList.first();
        endPos = posDoubleList.last();
        expectedPositions = posDoubleList.count();
    } else if ((axisType == eveSTRING) && (positionList.count() > 0)){
        startPos = positionList.first();
        endPos = positionList.last();
        expectedPositions = positionList.count();
    }
}
Exemple #4
0
void Geolocation::handleError(PositionError* error)
{
    ASSERT(error);

    GeoNotifierVector oneShotsCopy;
    copyToVector(m_oneShots, oneShotsCopy);

    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.
    GeoNotifierVector oneShotsWithCachedPosition;
    m_oneShots.clear();
    if (error->isFatal())
        m_watchers.clear();
    else {
        // Don't send non-fatal errors to notifiers due to receive a cached position.
        extractNotifiersWithCachedPosition(oneShotsCopy, &oneShotsWithCachedPosition);
        extractNotifiersWithCachedPosition(watchersCopy, 0);
    }

    sendError(oneShotsCopy, error);
    sendError(watchersCopy, error);

    // hasListeners() doesn't distinguish between notifiers due to receive a
    // cached position and those requiring a fresh position. Perform the check
    // before restoring the notifiers below.
    if (!hasListeners())
        stopUpdating();

    // Maintain a reference to the cached notifiers until their timer fires.
    copyToSet(oneShotsWithCachedPosition, m_oneShots);
}
Exemple #5
0
void evePosCalc::setPositionList(QString poslist) {

    if (stepmode != LIST) return;

    positionList = poslist.split(",",QString::SkipEmptyParts);
    foreach (QString value, positionList){
        if (axisType == eveINT){
            bool ok;
            posIntList.append(value.toInt(&ok));
            if (!ok) sendError(ERROR, QString("unable to set %1 as (integer) position").arg(value));
        }
        else if (axisType == eveDOUBLE){
            bool ok;
            posDoubleList.append(value.toDouble(&ok));
            if (!ok) sendError(ERROR, QString("unable to set %1 as (double) position").arg(value));
        }
    }
    if ((axisType == eveINT) && (posIntList.count() > 0)){
        startPos = posIntList.first();
        endPos = posIntList.last();
        expectedPositions = posIntList.count();
    } else if ((axisType == eveDOUBLE) && (posDoubleList.count() > 0)){
        startPos = posDoubleList.first();
        endPos = posDoubleList.last();
        expectedPositions = posDoubleList.count();
    } else if ((axisType == eveSTRING) && (positionList.count() > 0)){
        startPos = positionList.first();
        endPos = positionList.last();
        expectedPositions = positionList.count();
    }
}
Exemple #6
0
bool Window::configInit()
{
    GLXFBConfig* fbConfig = chooseGLXFBConfig();
    if( !fbConfig )
    {
        sendError( ERROR_SYSTEMWINDOW_PIXELFORMAT_NOTFOUND );
        return false;
    }

    GLXContext context = createGLXContext( fbConfig );
    setGLXContext( context );
    if( !context )
    {
        XFree( fbConfig );
        return false;
    }

    bool success = configInitGLXDrawable( fbConfig );
    XFree( fbConfig );

    if( !success || !_impl->xDrawable )
    {
        sendError( ERROR_GLXWINDOW_NO_DRAWABLE );
        return false;
    }

    makeCurrent();
    initGLEW();
    _initSwapSync();
    if( getIAttribute( IATTR_HINT_DRAWABLE ) == FBO )
        success = configInitFBO();

    return success;
}
/**
"SC" — Stepper and Servo Mode Configure

Command: SC,value1,value2<CR>
Response: OK<NL><CR>
Firmware versions: All
Execution: Immediate
Arguments:
value1 is an integer in the range from 0 to 255, which specifies the parameter
that you are adjusting.
value2 is an integer in the range from 0 to 65535. It specifies the value of the
parameter given by value1.
See the list of these parameters (value1) and allowed values (value2), below.
Description:00
This command allows you to configure the motor control modes that the EBB uses,
including parameters of the servo or solenoid motor used for raising and
lowering the pen, and how the stepper motor driver signals are directed.

The set of parameters and their allowed values is as follows:

SC,1,value2 Pen lift mechanism. value2 may be 0, 1 or 2. Early EggBot models
used a small solenoid, driven from an output signal on pin RB4.
SC,1,0 Enable only the solenoid output (RB4) for pen up/down movement.
SC,1,1 Enable only the RC servo output (RB1) for pen up/down movement.
SC,1,2 Enable both the solenoid (RB4) and RC servo (RB1) outputs for pen up/down
movement (default)
SC,2,value2 Stepper signal control. value2 may be 0, 1 or 2.
SC,2,0 Use microcontroller to control on-board stepper driver chips (default)
SC,2,1 Disconnect microcontroller from the on-board stepper motor drivers and
drive external step/direction motor drivers instead. In this mode, you can use
the microcontroller to control external step/direction drivers based on the
following pin assignments:
ENABLE1: RD1
ENABLE2: RA1
STEP1: RC6
DIR1: RC2
STEP2: RA5
DIR2: RA2
Note also that in this mode, you can externally drive the step/direction/enable
lines of the on board stepper motor drivers from the pins of J4 and J5. (Please
refer to the schematic for where these pins are broken out.)
SC,2,2 Disconnect microcontroller from both the built-in motor drivers and
external pins. All step/dir/enable pins on the PIC are set to inputs. This
allows you to control the on-board stepper motor driver chips externally with
your own step/dir/enable signals. Use the pins listed in the schematic from J5
and J4.
SC,4,servo_min Set the minimum value for the RC servo output position. servo_min
may be in the range 1 to 65535, in units of 83 ns intervals. This sets the "Pen
Up" position.
Default: 12000 (1.0 ms) on reset.
SC,5,servo_max Set the maximum value for the RC servo output position. servo_max
may be in the range 1 to 65535, in units of 83 ns intervals. This sets the "Pen
Down" position.
Default: 16000 (1.33 ms) on reset.
SC,8,maximum_S2_channels Sets the number of RC servo PWM channels, each of
S2_channel_duration_ms before cycling back to channel 1 for S2 command. Values
from 1 to 24 are valid for maximum_S2_channels.
Default: 8 on reset.
SC,9,S2_channel_duration_ms Set the number of milliseconds before firing the
next enabled channel for the S2 command. Values from 1 to 6 are valid for
S2_channel_duration_ms.
Default: 3 ms on reset.
SC,10,servo_rate Set rate of change of the servo position, for both raising and
lowering movements. Same units as rate parameter in S2 command.
SC,11,servo_rate_up Set the rate of change of the servo when going up. Same
units as rate parameter in S2 command.
SC,12,servo_rate_down Set the rate of change of the servo when going down. Same
units as rate parameter in S2 command.
SC,13,use_alt_pause - turns on (1) or off (0) alternate pause button function on
RB0. On by default. For EBB v1.1 boards, it uses RB2 instead.
Example: SC,4,8000\r Set the pen-up position to give a servo output of 8000,
about 0.66 ms.
Example: SC,1,1\r Enable only the RC servo for pen lift; disable solenoid
control output.
*/
void EBBParser::parseSC(const char* arg1, const char* arg2)
{
    if (arg1 == NULL || arg2 == NULL) {
        sendError();
        return;
    }

    int cmd = atoi(arg1);
    int value = atoi(arg2);
    switch (cmd) {
    case 4:
        setPenUpPos(value / 240 - 25);
        break;
    case 5:
        setPenDownPos(value / 240 - 25);
        break;
    case 6: // rotMin=value;    ignored
        break;
    case 7: // rotMax=value;    ignored
        break;
    case 11:
        setServoRateUp(value / 5);
        break;
    case 12:
        setServoRateDown(value / 5);
        break;
    default:
        sendError();
        return;
    }
    sendAck();
}
void HttpServerConnection::beginSendData()
{
	if (!server->processRequest(*this, request, response))
	{
		response.notFound();
		sendError();
		return;
	}

	if (!response.hasBody() && (response.getStatusCode() < 100 || response.getStatusCode() > 399))
	{
		// Show default error message
		sendError();
		return;
	}

	debugf("response sendHeader");
	response.sendHeader(*this);

	if (request.isWebSocket())
	{
		debugf("Switched to WebSocket Protocol");
		state = eHCS_WebSocketFrames; // Stay opened
		setTimeOut(0xFFFF);
	}
	else
		state = eHCS_Sending;
}
Exemple #9
0
bool Window::configInitGL( const eq::uint128_t& initId )
{
    if( !GLEW_ARB_shader_objects )
    {
        sendError( ERROR_LIVRE_ARB_SHADER_OBJECTS_MISSING );
        return false;
    }
    if( !GLEW_EXT_blend_func_separate )
    {
        sendError( ERROR_LIVRE_EXT_BLEND_FUNC_SEPARATE_MISSING );
        return false;
    }
    if( !GLEW_ARB_multitexture )
    {
        sendError( ERROR_LIVRE_ARB_MULTITEXTURE_MISSING );
        return false;
    }

    glDisable( GL_DEPTH_TEST );

    if( !eq::Window::configInitGL( initId ))
        return false;
    _impl->configInitGL();
    return true;
}
Exemple #10
0
void Client::handleAuth(char *buff,int len) {
	char response[33],response2[33];
	char gamename[64];
	char keyhash[33];
	memset(&response,0,sizeof(response));
	memset(&response2,0,sizeof(response2));
	if(!find_param("response", buff, response, sizeof(response))) {
		sendError(sd,true,"There was an error parsing a request.",GP_PARSE,1);
		return;
	}
	memset(&gamename,0,sizeof(gamename));
	if(!find_param("gamename", buff, gamename, sizeof(gamename))) {
		sendError(sd,true,"There was an error parsing a request.",GP_PARSE,1);
		return;
	}
	if(game == NULL) {
		game = server.options->gameInfoNameProc(gamename);
	}
	if(game == NULL) {
		sendError(sd,true,"There was an error parsing a request.",GP_PARSE,1);
		return;
	}
	int chrespnum = gs_chresp_num(challenge);
	getResponse(chrespnum,game->secretkey,response2,sizeof(response2));
	if(strcmp(response2,response) != 0) {
		sendError(sd,true,"There was an error parsing a request.",GP_PARSE,1);
		return;
	}
	authenticated = true;
	formatSend(sd,true,2,"\\lc\\2\\sesskey\\%d\\proof\\0\\id\\1",sesskey);
}
Exemple #11
0
int ReadStarDrop::retrieveMeshes(const coDistributedObject *const *&meshSet,
                                 int &numGridSteps, float *&gridTime)
{
    // Mesh must be a time set or a single grid
    const coDistributedObject *obj = p_grid_in->getCurrentObject();

    // retrieve possible scaling attribute from the grid object
    const char *scale = obj->getAttribute("STAR_SCALE8");
    if (scale)
        d_scale = 1.0f / (float)atof(scale);
    else
        d_scale = 1.0f;

    if (!obj->isType("SETELE"))
    {
        if (!obj->isType("UNSGRD"))
        {
            sendError("Object at port %s must be UNSGRD or set of UNSGRD",
                      p_grid_in->getName());
            return FAIL;
        }

        // ok: we don't have a moving grid here.
        static const coDistributedObject *grid[] = { obj };
        meshSet = grid;
        gridTime = new float[1];
        numGridSteps = 1;
        *gridTime = 0.0;
        return SUCCESS;
    }
    else
    {
        /// this is a set, but is it a timestep series with REALTIME attrib?
        meshSet = ((coDoSet *)obj)->getAllElements(&numGridSteps);
        if (numGridSteps < 1)
        {
            sendError("Object at port %s is set with 0 elements", p_grid_in->getName());
            return FAIL;
        }
    }

    gridTime = new float[numGridSteps];
    int i;
    for (i = 0; i < numGridSteps; i++)
    {
        const char *time = meshSet[i]->getAttribute("REALTIME");
        if (!time)
        {
            delete[] gridTime;
            delete[] meshSet;
            sendError("Set at port %s lacks REALTIME attributes",
                      p_grid_in->getName());
            return FAIL;
        }
        gridTime[i] = (float)atof(time);
    }

    return SUCCESS;
}
Exemple #12
0
/**
 * Do some sanity checks and forward message to the proper handler
 */
void MsgpackIODevice::dispatch(msgpack_object& req)
{
	//
	// neovim msgpack rpc calls are
	// [type(int), msgid(int), method(int), args(array)]
	//

	if (req.type != MSGPACK_OBJECT_ARRAY) {
		qDebug() << "Received Invalid msgpack: not an array";
		return;
	}

	if (req.via.array.size < 3 || req.via.array.size > 4) {
		qDebug() << "Received Invalid msgpack: message len MUST be 3 or 4";
		return;
	}

	if (req.via.array.ptr[0].type != MSGPACK_OBJECT_POSITIVE_INTEGER) {
		qDebug() << "Received Invalid msgpack: msg type MUST be an integer";
		return;
	}
	uint64_t type = req.via.array.ptr[0].via.u64;

	switch(type) {
	case 0:
		if (req.via.array.ptr[1].type != MSGPACK_OBJECT_POSITIVE_INTEGER) {
			qDebug() << "Received Invalid request: msg id MUST be a positive integer";
			sendError(req, tr("Msg Id must be a positive integer"));
			return;
		}
		if (req.via.array.ptr[2].type != MSGPACK_OBJECT_BIN &&
				req.via.array.ptr[2].type != MSGPACK_OBJECT_STR) {
			qDebug() << "Received Invalid request: method MUST be a String" << req.via.array.ptr[2];
			sendError(req, tr("Method id must be a positive integer"));
			return;
		}
		if (req.via.array.ptr[3].type != MSGPACK_OBJECT_ARRAY) {
			qDebug() << "Invalid request: arguments MUST be an array";
			sendError(req, tr("Paremeters must be an array"));
			return;
		}
		dispatchRequest(req);
		break;
	case 1:
		if (req.via.array.ptr[1].type != MSGPACK_OBJECT_POSITIVE_INTEGER) {
			qDebug() << "Received Invalid response: msg id MUST be a positive integer";
			return;
		}
		dispatchResponse(req);
		break;
	case 2:
		dispatchNotification(req);
		break;
	default:
		qDebug() << "Unsupported msg type" << type;
	}
}
Exemple #13
0
void Guitest::simulateError(){
    QString error1 = "Testing error";
    emit sendError(error1);
    QCOMPARE(gui->getStatusLabelText(), error1);
    QCOMPARE(gui->getStatusLabelText().contains("anything else..."), QBool(false));
    connectionsConnectButton();
    QString error2 = "Error to be posted in the message window";
    emit sendError(error2);
    QCOMPARE(gui->getMessageWindowText().contains(error2), QBool(true));
    QCOMPARE(gui->getMessageWindowText().contains("anything else..."), QBool(false));
}
Exemple #14
0
void Updater::run() {
    connect(ai, SIGNAL(startUpdate(QList<FileUpdate>)), this, SLOT(startUpdate(QList<FileUpdate>)));
    connect(dm, SIGNAL(downloadsFinished(QList<FileUpdate>)), this, SLOT(downloadFinished(QList<FileUpdate>)));
    connect(ai, SIGNAL(applicationClosed(bool)), this, SLOT(startExchange(bool)));
    connect(ai, SIGNAL(executableChanged(QString)), this, SLOT(setExecutable(QString)));
    connect(fh, SIGNAL(exchangingFinished(bool)), this, SLOT(exchangeFinished(bool)));
    connect(dm, SIGNAL(error(QString)), ai, SLOT(sendError(QString)));
    connect(fh, SIGNAL(error(QString)), ai, SLOT(sendError(QString)));

    connect(ai, SIGNAL(close()), this, SLOT(closeRequested()));
}
Exemple #15
0
void operationThread::moveCopy(){
    //перемещение\копирование
    while(!param->files.isEmpty()){
        if(canceled)
            return;

        QFileInfo tmp(param->dest);
        QDir();
        if (!tmp.exists())
            if (!mkDir(tmp))
            {
                sendError(trUtf8("Не удалось создать папку назначения"));
                /*не удалось создать папку назначения, ошибка-завершение*/
                return;
            }

        if (param->files.first().isDir()&&!param->files.first().isSymLink()){


            if (param->files.first().absoluteFilePath()==param->dest){
                sendError(trUtf8("Невозможно скопировать папку в саму себя"));

                return;
            }
            if (!mkDir(param->files.first())){
                sendError(trUtf8("Не удалось создать папку"));
                return;
            }

            dirRound(param->files.first().absoluteFilePath());
            if (canceled) return;
            if (param->type!=0) {
                QString dirName=param->files.first().absoluteFilePath();
                system("rm -rf \""+dirName.toLocal8Bit()+"\"");
            }
        }
        else{
            copyFile(param->files.first());
            if (canceled) return;
            if (param->type==2){
                QFile f(param->files.first().absoluteFilePath());
                f.remove();
            }

            if (param->type==1){
                QFile f(param->files.first().absoluteFilePath());
                f.remove();
            }
        }

        param->files.pop_front();

    }
}
void ServerThread::readyRead()
{
        if(!isInitialized)
    {
        initialize();
        return;
    }

    QDataStream input(s);
    s->waitForReadyRead();
    MessageEnvelop e;
    try
    {
        input >> e;
    }
    catch(MessageException e)
    {
        qDebug() << "Hackers are strong "
                 << "But I'm stronger";
        return;
        //sendError("Telnet Cannot kill me");
    }

    switch (e.getRequestType())
    {
    case SEND_LOGIN_TO_SERVER:
    case PING:
    case OK:
        return;
    case REQUEST_CALL_TO_CLIENT_FROM_SERVER:
        qDebug() << "Connection init";
        return requestCall(e.getName());
    case REQUEST_CLIENT_LIST_FROM_SERVER:
        return sendError("The List will be sent M'kay");
    case SEND_DENIED_RESPONSE_TO_COMMUNICATION:
        sendConnectionDenied();
        return;
    case SEND_SUCCESS_RESPONSE_TO_COMMUNICATION:
        qDebug() << "Connection Granted";
        ConnectionGranted(e.getPassword());
        return;

    case SEND_LOGOUT_REQUEST:
        logout();
        return;
    case END_OF_CALL_TO_CLIENT:
    case ERROR_SERVER_RESPONSE:
        return sendError("Only me can communicate on port 666 MUHEHEHE");
    default:
        return sendError("Unrecognized messsage type M'kay");
    }


}
Exemple #17
0
static void dropPermissions(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc)
{
    struct Context* const ctx = (struct Context*) vctx;
    struct Jmp jmp;
    Jmp_try(jmp) {
        Security_dropPermissions(&jmp.handler);
    } Jmp_catch {
        sendError(jmp.message, txid, ctx->admin);
        return;
    }
    sendError("none", txid, ctx->admin);
}
Exemple #18
0
static void noFiles(Dict* args, void* vcontext, String* txid)
{
    struct Context* const ctx = (struct Context*) vcontext;
    struct Jmp jmp;
    Jmp_try(jmp) {
        Security_noFiles(&jmp.handler);
    } Jmp_catch {
        sendError(jmp.message, txid, ctx->admin);
        return;
    }
    sendError("none", txid, ctx->admin);
}
Exemple #19
0
eveSMMotor::~eveSMMotor() {
    sendError(DEBUG, 0, QString("Deleting Motor %1").arg(name));
    try
    {
        if (triggerTrans != NULL) delete triggerTrans;
        if (unitTrans != NULL) delete unitTrans;
    }
    catch (std::exception& e)
    {
        sendError(FATAL, 0, QString("C++ Exception in ~eveSMMotor %1").arg(e.what()));
    }
}
void ServerThread::registerNewClient(MessageEnvelop &e)
{
    if(database->existsUser(e.getName().toStdString()))
    {
        sendError("The Username already exists M'kay, pick another one M'kay");
        emit error(this->s->error());
        return;
    }
    std::ifstream rand("/dev/urandom",std::ios::binary);
    char * newSalt = new char[8];
    rand.read(newSalt, 8);
    rand.close();
    char * corrSalt = getAscii85(newSalt, 8);
    delete[] newSalt;


    std::string s(e.getPassword().toStdString()), qCorrSalt(corrSalt);
    s = s + qCorrSalt;

    free(corrSalt);
    unsigned char hash[32];
    char *printableHash;

    sha2((unsigned char *) s.c_str(), s.length(), hash, 0);
    printableHash = getAscii85((char*) hash, 32);
    QString pass(printableHash), Qsalt(qCorrSalt.c_str());
    try
    {
        database->insertUser(e.getName().toStdString(), pass.toStdString(),
                         Qsalt.toStdString());
    }
    catch(SqlConnection::SqlException e)
    {
        sendError("The user was not added");
        emit error(this->s->error());
        return;
    }

    QByteArray b;
    QDataStream outStr(&b, QIODevice::WriteOnly);
    MessageEnvelop ret(REGISTER_APROOVED);

    isInitialized = false;
    outStr << ret;

    this->s->write(b);





}
Exemple #21
0
static void chroot(Dict* args, void* vctx, String* txid, struct Allocator* requestAlloc)
{
    struct Context* const ctx = Identity_check((struct Context*) vctx);
    struct Jmp jmp;
    Jmp_try(jmp) {
        String* root = Dict_getStringC(args, "root");
        Security_chroot(root->bytes, &jmp.handler);
    } Jmp_catch {
        sendError(jmp.message, txid, ctx->admin);
        return;
    }
    sendError("none", txid, ctx->admin);
}
Exemple #22
0
static void setUser(Dict* args, void* vcontext, String* txid)
{
    struct Context* const ctx = (struct Context*) vcontext;
    struct Jmp jmp;
    Jmp_try(jmp) {
        String* user = Dict_getString(args, String_CONST("user"));
        Security_setUser(user->bytes, ctx->logger, &jmp.handler);
    } Jmp_catch {
        sendError(jmp.message, txid, ctx->admin);
        return;
    }
    sendError("none", txid, ctx->admin);
}
Exemple #23
0
void Channel::sendError(int id, std::string ref,std::string msg,Result code)
{
    Json::Value error;
    if(m_StaticResult[ref].isMember("error")){
        error = m_StaticResult[ref]["error"];
        error["code"]=code;
        error["message"]=msg;
        sendError(id,error);
    }
    else{
        sendError(code,id,m_sComponentName+"."+ref,msg);
    }
}
void MediaDownload::incomingData(const QByteArray &data, unsigned position)
{
    QMutexLocker l(&m_bufferLock);
    bool emitFileSize = false;

    if (position+data.size() > m_fileSize)
    {
        qDebug() << "MediaDownload: file size is less than write position, adjusting size";
        m_fileSize = position + data.size();
        if (!m_bufferFile.resize(m_fileSize))
        {
            sendError(QLatin1String("Buffering failed: ") + m_bufferFile.errorString());
            return;
        }
        emitFileSize = true;
    }

    Q_ASSERT(m_bufferFile.size() == m_fileSize);

    if (!m_bufferFile.seek(position))
    {
        sendError(QLatin1String("Buffer write failed: ") + m_bufferFile.errorString());
        return;
    }

    qint64 re = m_bufferFile.write(data);
    if (re < 0)
    {
        sendError(QLatin1String("Buffer write failed: ") + m_bufferFile.errorString());
        return;
    }

    if (!m_bufferFile.flush())
        qDebug() << "MediaDownload: Buffer flush after write failed (non-critical):" << m_bufferFile.errorString();

    Q_ASSERT(re == data.size());

    m_bufferRanges.insert(Range::fromStartSize(position, re));

    if (m_writePos == position)
        m_writePos += re;

    m_downloadedSize += re;

    l.unlock();

    if (emitFileSize)
        emit fileSizeChanged(m_fileSize);

    m_bufferWait.wakeAll();
}
Exemple #25
0
/* Check requested username */
int validUsername (char *username, int client) {
   if (sanitizeInput(username, 1)) {
      sendError("Invalid characters in username.", client);
      return 0;
   }
   if (strlen(username) < 3) {
      sendError("Username is too short.", client);
      return 0;
   }
   if (strlen(username) > USERNAME_LENGTH) {
      sendError("Username is too long.", client);
      return 0;
   }
   return 1;
}
Exemple #26
0
/* Check requested room name */
int validRoomname (char *roomname, int client) {
   if (sanitizeInput(roomname, 1)) {
      sendError("Invalid characters in room name.", client);
      return 0;
   }
   if (strlen(roomname) < 3) {
      sendError("Requested room name is too short.", client);
      return 0;
   }
   if (strlen(roomname) > ROOMNAME_LENGTH) {
      sendError("Requested room name is too long.", client);
      return 0;
   }
   return 1;
}
Exemple #27
0
bool GLWindow::_createFBO( util::FrameBufferObject*& fbo, const int samplesSize)
{
    const PixelViewport& pvp = getPixelViewport();
    const GLuint colorFormat = getColorFormat();

    int depthSize = getIAttribute( WindowSettings::IATTR_PLANES_DEPTH );
    if( depthSize == AUTO )
        depthSize = 24;

    int stencilSize = getIAttribute( WindowSettings::IATTR_PLANES_STENCIL );
    if( stencilSize == AUTO )
        stencilSize = 1;

    fbo = new util::FrameBufferObject( _impl->glewContext,
                                       samplesSize ? GL_TEXTURE_2D_MULTISAMPLE
                                                  : GL_TEXTURE_RECTANGLE_ARB );
    Error error = fbo->init( pvp.w, pvp.h, colorFormat, depthSize,
                             stencilSize, samplesSize );
    if( !error )
        return true;

    if( getIAttribute( WindowSettings::IATTR_PLANES_STENCIL ) == AUTO )
        error = fbo->init( pvp.w, pvp.h, colorFormat, depthSize, 0,
                           samplesSize );

    if( !error )
        return true;

    sendError( error.getCode( ));
    delete fbo;
    fbo = 0;
    return false;
}
Exemple #28
0
//----------------------------------------------------------------------
// configInit
//----------------------------------------------------------------------
bool Window::configInit( const uint128_t& initID )
{
    if( !getPixelViewport().isValid( ))
    {
        sendError( ERROR_WINDOW_PVP_INVALID );
        return false;
    }

    LBASSERT( !_systemWindow );

    int glMajorVersion = 1;
    int glMinorVersion = 1;
    if( getPipe()->getSystemPipe()->getMaxOpenGLVersion() != AUTO )
    {
        float maj, min;
        min = modff( getPipe()->getSystemPipe()->getMaxOpenGLVersion(), &maj );
        glMajorVersion = static_cast< int >( maj );
        glMinorVersion = static_cast< int >( min*10.f );
    }

    if( getIAttribute( WindowSettings::IATTR_HINT_OPENGL_MAJOR ) == AUTO )
        setIAttribute( WindowSettings::IATTR_HINT_OPENGL_MAJOR, glMajorVersion);
    if( getIAttribute( WindowSettings::IATTR_HINT_OPENGL_MINOR ) == AUTO )
        setIAttribute( WindowSettings::IATTR_HINT_OPENGL_MINOR, glMinorVersion);

    return configInitSystemWindow( initID ) && configInitGL( initID );
}
Exemple #29
0
static void allowConnection(Dict* args, void* vcontext, String* txid)
{
    struct Context* context = (struct Context*) vcontext;
    String* publicKeyOfAuthorizedNode =
        Dict_getString(args, String_CONST("publicKeyOfAuthorizedNode"));
    String* ip6Address = Dict_getString(args, String_CONST("ip6Address"));
    String* ip4Address = Dict_getString(args, String_CONST("ip4Address"));
    uint8_t pubKey[32];
    uint8_t ip6Addr[16];

    uint8_t ip6ToGive[16];
    uint8_t ip4ToGive[4];

    char* error;
    int ret;
    if (!ip6Address && !ip4Address) {
        error = "Must specify ip6Address or ip4Address";
    } else if ((ret = Key_parse(publicKeyOfAuthorizedNode, pubKey, ip6Addr)) != 0) {
        error = Key_parse_strerror(ret);
    } else if (ip6Address && evutil_inet_pton(AF_INET6, ip6Address->bytes, ip6ToGive) < 1) {
        error = "malformed ip6Address";
    } else if (ip4Address && evutil_inet_pton(AF_INET, ip4Address->bytes, ip4ToGive) < 1) {
        error = "malformed ip4Address";
    } else {
        int conn = IpTunnel_allowConnection(pubKey,
                                            (ip6Address) ? ip6ToGive : NULL,
                                            (ip4Address) ? ip4ToGive : NULL,
                                            context->ipTun);
        sendResponse(conn, txid, context->admin);
        return;
    }

    sendError(error, txid, context->admin);
}
/*! STAT (return file/dir information)
*/
void QwsClientSocket::handleMessageSTAT(const QwMessage &message)
{
    QwsFile targetFile;
    targetFile.localFilesRoot = filesRootPath;
    targetFile.setRemotePath(message.stringArg(0));

    if (!targetFile.loadFromLocalPath()) {
        sendError(Qw::ErrorFileOrDirectoryNotFound);
        return;
    }

    // Try to load additional information from the database
    targetFile.loadMetaInformation();

    // Send file info reply
    QwMessage reply("402");
    reply.appendArg(targetFile.remotePath());
    reply.appendArg(QString::number(targetFile.type()));
    reply.appendArg(QString::number(targetFile.size()));
    reply.appendArg(targetFile.created().toUTC().toString(Qt::ISODate)+"+00:00");
    reply.appendArg(targetFile.modified().toUTC().toString(Qt::ISODate)+"+00:00");
    reply.appendArg(targetFile.checksum());
    reply.appendArg(targetFile.comment());
    sendMessage(reply);
}