• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ setError函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中setError函数的典型用法代码示例。如果您正苦于以下问题:C++ setError函数的具体用法?C++ setError怎么用?C++ setError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了setError函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: data

void PtexMainWriter::finish()
{
    // do nothing if there's no new data to write
    if (!_hasNewData) return;

    // copy missing faces from _reader
    if (_reader) {
	for (int i = 0, nfaces = _header.nfaces; i < nfaces; i++) {
	    if (_faceinfo[i].flags == uint8_t(-1)) {
		// copy face data
                const Ptex::FaceInfo& info = _reader->getFaceInfo(i);
                int size = _pixelSize * info.res.size();
                if (info.isConstant()) {
                    PtexPtr<PtexFaceData> data ( _reader->getData(i) );
                    if (data) {
                        writeConstantFace(i, info, data->getData());
                    }
                } else {
                    void* data = malloc(size);
                    _reader->getData(i, data, 0);
                    writeFace(i, info, data, 0);
                    free(data);
                }
	    }
	}
    }
    else {
	// just flag missing faces as constant (black)
	for (int i = 0, nfaces = _header.nfaces; i < nfaces; i++) {
	    if (_faceinfo[i].flags == uint8_t(-1))
		_faceinfo[i].flags = FaceInfo::flag_constant;
	}
    }

    // write reductions to tmp file
    if (_genmipmaps)
	generateReductions();

    // flag faces w/ constant neighborhoods
    flagConstantNeighorhoods();

    // update header
    _header.nlevels = uint16_t(_levels.size());
    _header.nfaces = uint32_t(_faceinfo.size());

    // create new file
    FILE* newfp = fopen(_newpath.c_str(), "wb+");
    if (!newfp) {
	setError(fileError("Can't write to ptex file: ", _newpath.c_str()));
	return;
    }

    // write blank header (to fill in later)
    writeBlank(newfp, HeaderSize);
    writeBlank(newfp, ExtHeaderSize);

    // write compressed face info block
    _header.faceinfosize = writeZipBlock(newfp, &_faceinfo[0],
					 sizeof(FaceInfo)*_header.nfaces);

    // write compressed const data block
    _header.constdatasize = writeZipBlock(newfp, &_constdata[0], int(_constdata.size()));

    // write blank level info block (to fill in later)
    FilePos levelInfoPos = ftello(newfp);
    writeBlank(newfp, LevelInfoSize * _header.nlevels);

    // write level data blocks (and record level info)
    std::vector<LevelInfo> levelinfo(_header.nlevels);
    for (int li = 0; li < _header.nlevels; li++)
    {
	LevelInfo& info = levelinfo[li];
	LevelRec& level = _levels[li];
	int nfaces = int(level.fdh.size());
	info.nfaces = nfaces;
	// output compressed level data header
	info.levelheadersize = writeZipBlock(newfp, &level.fdh[0],
					     sizeof(FaceDataHeader)*nfaces);
	info.leveldatasize = info.levelheadersize;
	// copy level data from tmp file
	for (int fi = 0; fi < nfaces; fi++)
	    info.leveldatasize += copyBlock(newfp, _tmpfp, level.pos[fi],
					    level.fdh[fi].blocksize());
	_header.leveldatasize += info.leveldatasize;
    }
    rewind(_tmpfp);

    // write meta data (if any)
    if (!_metadata.empty())
	writeMetaData(newfp);

    // update extheader for edit data position
    _extheader.editdatapos = ftello(newfp);

    // rewrite level info block
    fseeko(newfp, levelInfoPos, SEEK_SET);
    _header.levelinfosize = writeBlock(newfp, &levelinfo[0], LevelInfoSize*_header.nlevels);

    // rewrite header
    fseeko(newfp, 0, SEEK_SET);
//.........这里部分代码省略.........
开发者ID:UIKit0,项目名称:oiio,代码行数:101,代码来源:PtexWriter.cpp


示例2: setError

bool Connection::processHandshake()
{
  // Parse data
  UINT8 protocolVersion = m_reader.readByte();

  if (protocolVersion == 0xff)
  {
    setError("Too many connections reported by server", 0, UME_OTHER);
    return false;
  }
  else
    if (protocolVersion != MYSQL_PROTOCOL_VERSION)
    {
      setError("Protocol version not supported(1)", 0, UME_OTHER);
      return false;
    }

    char *serverVersion = m_reader.readNTString();
    UINT32 threadId = m_reader.readLong();
    char *scrambleBuff = (char *) m_reader.readBytes(8);

    UINT8 filler1 = m_reader.readByte();
    UINT16 serverCaps = m_reader.readShort();

    if (!(serverCaps & MCP_PROTOCOL_41))
    {
      setError("Authentication < 4.1 not supported", 1, UME_OTHER);
      return false;
    }

    UINT8 serverLang = m_reader.readByte();
    UINT16 serverStatus = m_reader.readShort();
    UINT8 *filler2 = m_reader.readBytes(13);


    char *scrambleBuff2 = NULL;
    if (m_reader.getBytesLeft ())
    {
      scrambleBuff2 = (char *) m_reader.readNTString();
    }
    else
    {
      setError("Authentication < 4.1 not supported", 2, UME_OTHER);
      return false;
    }

    m_clientCaps = serverCaps;

    m_clientCaps  &= ~MCP_COMPRESS;
    m_clientCaps  &= ~MCP_NO_SCHEMA;
    m_clientCaps &= ~MCP_SSL;

    if (!(serverCaps & MCP_CONNECT_WITH_DB) && !m_database.empty())
    {
      setError("Protocol < 4.1 not supported", 3, UME_OTHER);
      return false;
    }

    if ((serverCaps & MCP_CONNECT_WITH_DB) && m_database.empty())
    {
      m_clientCaps &= ~MCP_CONNECT_WITH_DB;
    }

    m_reader.skip();

    m_writer.reset();
    m_writer.writeLong (m_clientCaps);
    m_writer.writeLong (MYSQL_PACKET_SIZE);

    if (m_charset != MCS_UNDEFINED)
    {
      m_writer.writeByte( (UINT8) (int) m_charset);
    }
    else
    {
      m_writer.writeByte(serverLang);
    }

    for (int filler = 0; filler < 23; filler ++)
      m_writer.writeByte(0x00);

    m_writer.writeNTString(m_username.c_str ());

    if (!m_password.empty())
    {
      m_writer.writeByte(20);

      UINT8 token[20];
      scramble(scrambleBuff, scrambleBuff2, token);
      m_writer.writeBytes(token, 20);
    }
    else
    {
      m_writer.writeByte(0x00);
    }

    if (!m_database.empty())
    {
      m_writer.writeNTString(m_database.c_str());
    }
//.........这里部分代码省略.........
开发者ID:DYFeng,项目名称:ultramysql,代码行数:101,代码来源:Connection.cpp


示例3: PRINTMARK

void *Connection::query(const char *_query, size_t _cbQuery)
{
  m_dbgMethodProgress ++;

  if (m_dbgMethodProgress > 1)
  {
    /*
    NOTE: We don't call setError here because it will close the socket worsening the concurrent access error making it impossible to trace */
    m_errorMessage = "Concurrent access in query method";
    m_errno = 0;
    m_errorType = UME_OTHER;
    m_dbgMethodProgress --;
    return NULL;
  }

  if (m_sockInst == NULL)
  {
    PRINTMARK();
    setError ("Not connected", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;
  }

  size_t len = _cbQuery;

  if (len > m_writer.getSize () - (MYSQL_PACKET_HEADER_SIZE + 1))
  {
    PRINTMARK();
    setError ("Query too big", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;
  }

  m_writer.reset();
  m_writer.writeByte(MC_QUERY);
  m_writer.writeBytes ( (void *) _query, len);
  m_writer.finalize(0);

  if (!sendPacket())
  {
    PRINTMARK();
    m_dbgMethodProgress --;
    return NULL;
  }

  if (!recvPacket())
  {
    PRINTMARK();
    m_dbgMethodProgress --;
    return NULL;
  }

  UINT8 result = m_reader.readByte();

  switch (result)
  {
  case 0x00:
    PRINTMARK();
    m_dbgMethodProgress --;
    return handleOKPacket();

  case 0xff:
    PRINTMARK();
    handleErrorPacket();
    m_dbgMethodProgress --;
    return NULL;

  case 0xfe:
    PRINTMARK();
    setError ("Unexpected EOF when decoding result", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;


  default:
    PRINTMARK();
    m_dbgMethodProgress --;
    return handleResultPacket((int)result);
  }

  PRINTMARK();
  m_dbgMethodProgress --;
  return NULL;
}
开发者ID:DYFeng,项目名称:ultramysql,代码行数:84,代码来源:Connection.cpp


示例4: Q_ASSERT

bool VideoPlayerBackend::start(const QUrl &url)
{
    Q_ASSERT(!m_pipeline);
    if (state() == PermanentError || m_pipeline)
        return false;

    if (!m_sink)
    {
        setError(true, QLatin1String("Internal error: improper usage"));
        return false;
    }

    /* Pipeline */
    m_pipeline = gst_pipeline_new("stream");
    if (!m_pipeline)
    {
        setError(true, tr("Failed to create video pipeline (%1)").arg(QLatin1String("stream")));
        return false;
    }

    /* Buffered HTTP source */
    setVideoBuffer(new VideoHttpBuffer(url));

    GstElement *source = m_videoBuffer->setupSrcElement(m_pipeline);
    if (!source)
    {
        setError(true, tr("Failed to create video pipeline (%1)").arg(QLatin1String("source")));
        setVideoBuffer(0);
        return false;
    }

    m_videoBuffer->startBuffering();

    /* Decoder */
    GstElement *decoder = gst_element_factory_make("decodebin2", "decoder");
    if (!decoder)
    {
        setError(true, tr("Failed to create video pipeline (%1)").arg(QLatin1String("decoder")));
        return false;
    }

    g_object_set(G_OBJECT(decoder),
                 "use-buffering", TRUE,
                 "max-size-time", 10 * GST_SECOND,
                 NULL);

    g_signal_connect(decoder, "new-decoded-pad", G_CALLBACK(staticDecodePadReady), this);

    /* Colorspace conversion (no-op if unnecessary) */
    GstElement *colorspace = gst_element_factory_make("ffmpegcolorspace", "colorspace");
    if (!colorspace)
    {
        setError(true, tr("Failed to create video pipeline (%1)").arg(QLatin1String("colorspace")));
        return false;
    }

    gst_bin_add_many(GST_BIN(m_pipeline), decoder, colorspace, m_sink, NULL);
    if (!gst_element_link(source, decoder))
    {
        setError(true, tr("Failed to create video pipeline (%1)").arg(QLatin1String("link decoder")));
        return false;
    }

    if (!gst_element_link(colorspace, m_sink))
    {
        setError(true, tr("Failed to create video pipeline (%1)").arg(QLatin1String("link sink")));
        return false;
    }

    /* This is the element that is linked to the decoder for video output; it will be linked when decodePadReady
     * gives us the video pad. */
    m_videoLink = colorspace;

    m_playbackSpeed = 1.0;

    /* We handle all messages in the sync handler, because we can't run a glib event loop.
     * Although linux does use glib's loop (and we could take advantage of that), it's better
     * to handle everything this way for windows and mac support. */
    GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(m_pipeline));
    Q_ASSERT(bus);
    gst_bus_enable_sync_message_emission(bus);
    gst_bus_set_sync_handler(bus, staticBusHandler, this);
    gst_object_unref(bus);

    /* Move the pipeline into the PLAYING state. This call may block for a very long time
     * (up to several seconds), because it will block until the pipeline has completed that move. */
    gst_element_set_state(m_pipeline, GST_STATE_READY);
    return true;
}
开发者ID:ruminsam,项目名称:bluecherry-client,代码行数:89,代码来源:VideoPlayerBackend_gst.cpp


示例5: LogFlowFuncEnter

HRESULT VFSExplorer::i_updateS3(TaskVFSExplorer *aTask)
{
    LogFlowFuncEnter();

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);

    HRESULT rc = S_OK;

    RTS3 hS3 = NULL;
    std::list<VFSExplorer::Data::DirEntry> fileList;
    try
    {
        int vrc = RTS3Create(&hS3, m->strUsername.c_str(), m->strPassword.c_str(),
                             m->strHostname.c_str(), "virtualbox-agent/" VBOX_VERSION_STRING);
        if (RT_FAILURE(vrc))
            throw setError(E_FAIL, tr ("Can't open S3 storage service (%Rrc)"), vrc);

        RTS3SetProgressCallback(hS3, VFSExplorer::TaskVFSExplorer::uploadProgress, &aTask);
        /* Do we need the list of buckets or keys? */
        if (m->strBucket.isEmpty())
        {
            PCRTS3BUCKETENTRY pBuckets = NULL;
            vrc = RTS3GetBuckets(hS3, &pBuckets);
            if (RT_FAILURE(vrc))
                throw setError(E_FAIL, tr ("Can't get buckets (%Rrc)"), vrc);

            PCRTS3BUCKETENTRY pTmpBuckets = pBuckets;
            while (pBuckets)
            {
                /* Set always read/write permissions of the current logged in user. */
                fileList.push_back(VFSExplorer::Data::DirEntry(pBuckets->pszName, VFSFileType_Directory,
                                   0, RTFS_UNIX_IRUSR | RTFS_UNIX_IWUSR));
                pBuckets = pBuckets->pNext;
            }
            RTS3BucketsDestroy(pTmpBuckets);
        }
        else
        {
            PCRTS3KEYENTRY pKeys = NULL;
            vrc = RTS3GetBucketKeys(hS3, m->strBucket.c_str(), &pKeys);
            if (RT_FAILURE(vrc))
                throw setError(E_FAIL, tr ("Can't get keys for bucket (%Rrc)"), vrc);

            PCRTS3KEYENTRY pTmpKeys = pKeys;
            while (pKeys)
            {
                Utf8Str name(pKeys->pszName);
                /* Set always read/write permissions of the current logged in user. */
                fileList.push_back(VFSExplorer::Data::DirEntry(pKeys->pszName, VFSFileType_File, pKeys->cbFile,
                                   RTFS_UNIX_IRUSR | RTFS_UNIX_IWUSR));
                pKeys = pKeys->pNext;
            }
            RTS3KeysDestroy(pTmpKeys);
        }
    }
    catch(HRESULT aRC)
    {
        rc = aRC;
    }

    if (hS3 != NULL)
        RTS3Destroy(hS3);

    /* Assign the result on success (this clears the old list) */
    if (rc == S_OK)
        m->entryList.assign(fileList.begin(), fileList.end());

    aTask->rc = rc;

    if (!aTask->progress.isNull())
        aTask->progress->i_notifyComplete(rc);

    LogFlowFunc(("rc=%Rhrc\n", rc));
    LogFlowFuncLeave();

    return VINF_SUCCESS;
}
开发者ID:mcenirm,项目名称:vbox,代码行数:80,代码来源:VFSExplorerImpl.cpp


示例6: setError

void Soprano::Error::ErrorCache::setError( const QString& errorMessage, int code ) const
{
    setError( Error( errorMessage, code ) );
}
开发者ID:KDE,项目名称:soprano,代码行数:4,代码来源:error.cpp


示例7: adep

HRESULT StorageController::setPortCount(ULONG aPortCount)
{
    /* the machine needs to be mutable */
    AutoMutableStateDependency adep(m->pParent);
    if (FAILED(adep.rc())) return adep.rc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    switch (m->bd->storageBus)
    {
        case StorageBus_SATA:
        {
            /* AHCI SATA supports a maximum of 30 ports. */
            if (aPortCount < 1 || aPortCount > 30)
                return setError(E_INVALIDARG,
                                tr("Invalid port count: %lu (must be in range [%lu, %lu])"),
                                aPortCount, 1, 30);
            break;
        }
        case StorageBus_SCSI:
        {
            /*
             * SCSI does not support setting different ports.
             * (doesn't make sense here either).
             * The maximum and minimum is 16 and unless the callee
             * tries to set a different value we return an error.
             */
            if (aPortCount != 16)
                return setError(E_INVALIDARG,
                                tr("Invalid port count: %lu (must be in range [%lu, %lu])"),
                                aPortCount, 16, 16);
            break;
        }
        case StorageBus_IDE:
        {
            /*
             * The port count is fixed to 2.
             */
            if (aPortCount != 2)
                return setError(E_INVALIDARG,
                                tr("Invalid port count: %lu (must be in range [%lu, %lu])"),
                                aPortCount, 2, 2);
            break;
        }
        case StorageBus_Floppy:
        {
            /*
             * The port count is fixed to 1.
             */
            if (aPortCount != 1)
                return setError(E_INVALIDARG,
                                tr("Invalid port count: %lu (must be in range [%lu, %lu])"),
                                aPortCount, 1, 1);
            break;
        }
        case StorageBus_SAS:
        {
            /* SAS supports a maximum of 255 ports. */
            if (aPortCount < 1 || aPortCount > 255)
                return setError(E_INVALIDARG,
                                tr("Invalid port count: %lu (must be in range [%lu, %lu])"),
                                aPortCount, 1, 255);
            break;
        }
        case StorageBus_USB:
        {
            /*
             * The port count is fixed to 8.
             */
            if (aPortCount != 8)
                return setError(E_INVALIDARG,
                                tr("Invalid port count: %lu (must be in range [%lu, %lu])"),
                                aPortCount, 8, 8);
            break;
        }
        case StorageBus_PCIe:
        {
            /*
             * PCIe (NVMe in particular) supports theoretically 2^32 - 1
             * different namespaces, limit the amount artifically here.
             */
            if (aPortCount < 1 || aPortCount > 255)
                return setError(E_INVALIDARG,
                                tr("Invalid port count: %lu (must be in range [%lu, %lu])"),
                                aPortCount, 1, 255);
            break;
        }
        default:
            AssertMsgFailed(("Invalid controller type %d\n", m->bd->storageBus));
    }

    if (m->bd->ulPortCount != aPortCount)
    {
        m->bd.backup();
        m->bd->ulPortCount = aPortCount;

        alock.release();
        AutoWriteLock mlock(m->pParent COMMA_LOCKVAL_SRC_POS);        // m->pParent is const, needs no locking
        m->pParent->i_setModified(Machine::IsModified_Storage);
        mlock.release();
//.........这里部分代码省略.........
开发者ID:mdaniel,项目名称:virtualbox-org-svn-vbox-trunk,代码行数:101,代码来源:StorageControllerImpl.cpp


示例8: qDebug

bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16 port)
{
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug("QNativeSocketEnginePrivate::nativeConnect() : %d ", socketDescriptor);
#endif

    struct sockaddr_in sockAddrIPv4;
    struct sockaddr *sockAddrPtr = 0;
    QT_SOCKLEN_T sockAddrSize = 0;


    struct sockaddr_in6 sockAddrIPv6;

    if (addr.protocol() == QAbstractSocket::IPv6Protocol) {
        memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
        sockAddrIPv6.sin6_family = AF_INET6;
        sockAddrIPv6.sin6_port = htons(port);

        QString scopeid = addr.scopeId();
        bool ok;
        sockAddrIPv6.sin6_scope_id = scopeid.toInt(&ok);
#ifndef QT_NO_IPV6IFNAME
        if (!ok)
            sockAddrIPv6.sin6_scope_id = ::if_nametoindex(scopeid.toLatin1());
#endif
        Q_IPV6ADDR ip6 = addr.toIPv6Address();
        memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &ip6, sizeof(ip6));

        sockAddrSize = sizeof(sockAddrIPv6);
        sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
    } else


    if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
        memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
        sockAddrIPv4.sin_family = AF_INET;
        sockAddrIPv4.sin_port = htons(port);
        sockAddrIPv4.sin_addr.s_addr = htonl(addr.toIPv4Address());

        sockAddrSize = sizeof(sockAddrIPv4);
        sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
    } else {
        // unreachable
    }

    int connectResult = qt_safe_connect(socketDescriptor, sockAddrPtr, sockAddrSize);
    if (connectResult == -1) {
        switch (errno) {
        case EISCONN:
            socketState = QAbstractSocket::ConnectedState;
            break;
        case ECONNREFUSED:
        case EINVAL:
            setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
            socketState = QAbstractSocket::UnconnectedState;
            break;
        case ETIMEDOUT:
            setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
            break;
        case EHOSTUNREACH:
            setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
            socketState = QAbstractSocket::UnconnectedState;
            break;
        case ENETUNREACH:
            setError(QAbstractSocket::NetworkError, NetworkUnreachableErrorString);
            socketState = QAbstractSocket::UnconnectedState;
            break;
        case EADDRINUSE:
            setError(QAbstractSocket::NetworkError, AddressInuseErrorString);
            break;
        case EINPROGRESS:
        case EALREADY:
            setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
            socketState = QAbstractSocket::ConnectingState;
            break;
        case EAGAIN:
            setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
            setError(QAbstractSocket::SocketResourceError, ResourceErrorString);
            break;
        case EACCES:
        case EPERM:
            setError(QAbstractSocket::SocketAccessError, AccessErrorString);
            socketState = QAbstractSocket::UnconnectedState;
            break;
        case EAFNOSUPPORT:
        case EBADF:
        case EFAULT:
        case ENOTSOCK:
            socketState = QAbstractSocket::UnconnectedState;
        default:
            break;
        }

        if (socketState != QAbstractSocket::ConnectedState) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
            qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == false (%s)",
                   addr.toString().toLatin1().constData(), port,
                   socketState == QAbstractSocket::ConnectingState
                   ? "Connection in progress" : socketErrorString.toLatin1().constData());
#endif
//.........这里部分代码省略.........
开发者ID:wpbest,项目名称:copperspice,代码行数:101,代码来源:qnativesocketengine_unix.cpp


示例9: sizeof

bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &address, quint16 port)
{
    struct sockaddr_in sockAddrIPv4;
    struct sockaddr *sockAddrPtr = 0;
    QT_SOCKLEN_T sockAddrSize = 0;


    struct sockaddr_in6 sockAddrIPv6;

    if (address.protocol() == QAbstractSocket::IPv6Protocol || address.protocol() == QAbstractSocket::AnyIPProtocol) {
#ifdef IPV6_V6ONLY
        int ipv6only = 0;
        if (address.protocol() == QAbstractSocket::IPv6Protocol)
            ipv6only = 1;
        //default value of this socket option varies depending on unix variant (or system configuration on BSD), so always set it explicitly
        ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );
#endif
        memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
        sockAddrIPv6.sin6_family = AF_INET6;
        sockAddrIPv6.sin6_port = htons(port);
#ifndef QT_NO_IPV6IFNAME
        sockAddrIPv6.sin6_scope_id = ::if_nametoindex(address.scopeId().toLatin1().data());
#else
        sockAddrIPv6.sin6_scope_id = address.scopeId().toInt();
#endif
        Q_IPV6ADDR tmp = address.toIPv6Address();
        memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
        sockAddrSize = sizeof(sockAddrIPv6);
        sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
    } else

        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
            sockAddrIPv4.sin_family = AF_INET;
            sockAddrIPv4.sin_port = htons(port);
            sockAddrIPv4.sin_addr.s_addr = htonl(address.toIPv4Address());
            sockAddrSize = sizeof(sockAddrIPv4);
            sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
        } else {
            // unreachable
        }

    int bindResult = QT_SOCKET_BIND(socketDescriptor, sockAddrPtr, sockAddrSize);

    if (bindResult < 0) {
        switch(errno) {
        case EADDRINUSE:
            setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);
            break;
        case EACCES:
            setError(QAbstractSocket::SocketAccessError, AddressProtectedErrorString);
            break;
        case EINVAL:
            setError(QAbstractSocket::UnsupportedSocketOperationError, OperationUnsupportedErrorString);
            break;
        case EADDRNOTAVAIL:
            setError(QAbstractSocket::SocketAddressNotAvailableError, AddressNotAvailableErrorString);
            break;
        default:
            break;
        }

#if defined (QNATIVESOCKETENGINE_DEBUG)
        qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)",
               address.toString().toLatin1().constData(), port, socketErrorString.toLatin1().constData());
#endif

        return false;
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == true",
           address.toString().toLatin1().constData(), port);
#endif
    socketState = QAbstractSocket::BoundState;
    return true;
}
开发者ID:wpbest,项目名称:copperspice,代码行数:77,代码来源:qnativesocketengine_unix.cpp


示例10: Thread

TCPSession::TCPSession(TCPV6Socket &s, int pri, size_t stack) :
Thread(pri, stack), TCPStream(s)
{
    setCompletion(true);
    setError(false);
}
开发者ID:tmatth,项目名称:ucommon,代码行数:6,代码来源:tcp.cpp


示例11: streambuf

TCPStream::TCPStream(TCPSocket &server, bool throwflag, timeout_t to) :
    streambuf(), Socket(accept(server.getSocket(), NULL, NULL)),
#ifdef  OLD_IOSTREAM
    iostream()
#else
    iostream((streambuf *)this)
#endif
    ,bufsize(0)
    ,gbuf(NULL)
    ,pbuf(NULL) {
    tpport_t port;
    family = IPV4;

#ifdef  OLD_IOSTREAM
    init((streambuf *)this);
#endif

    timeout = to;
    setError(throwflag);
    IPV4Host host = getPeer(&port);
    if(!server.onAccept(host, port)) {
        endSocket();
        error(errConnectRejected);
        iostream::clear(ios::failbit | rdstate());
        return;
    }

    segmentBuffering(server.getSegmentSize());
    Socket::state = CONNECTED;
}

#ifdef  CCXX_IPV6
TCPStream::TCPStream(TCPV6Socket &server, bool throwflag, timeout_t to) :
    streambuf(), Socket(accept(server.getSocket(), NULL, NULL)),
#ifdef  OLD_IOSTREAM
    iostream()
#else
    iostream((streambuf *)this)
#endif
    ,bufsize(0)
    ,gbuf(NULL)
    ,pbuf(NULL) {
    tpport_t port;

    family = IPV6;

#ifdef  OLD_IOSTREAM
    init((streambuf *)this);
#endif

    timeout = to;
    setError(throwflag);
    IPV6Host host = getIPV6Peer(&port);
    if(!server.onAccept(host, port)) {
        endSocket();
        error(errConnectRejected);
        iostream::clear(ios::failbit | rdstate());
        return;
    }

    segmentBuffering(server.getSegmentSize());
    Socket::state = CONNECTED;
}
#endif

TCPStream::TCPStream(const IPV4Host &host, tpport_t port, unsigned size, bool throwflag, timeout_t to) :
    streambuf(), Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP),
#ifdef  OLD_IOSTREAM
    iostream(),
#else
    iostream((streambuf *)this),
#endif
    bufsize(0),gbuf(NULL),pbuf(NULL) {
#ifdef  OLD_IOSTREAM
    init((streambuf *)this);
#endif
    family = IPV4;
    timeout = to;
    setError(throwflag);
    connect(host, port, size);
}

#ifdef  CCXX_IPV6
TCPStream::TCPStream(const IPV6Host &host, tpport_t port, unsigned size, bool throwflag, timeout_t to) :
    streambuf(), Socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP),
#ifdef OLD_IOSTREAM
    iostream(),
#else
    iostream((streambuf *)this),
#endif
    bufsize(0),gbuf(NULL),pbuf(NULL) {
    family = IPV6;

#ifdef  OLD_IOSTREAM
    init((streambuf *)this);
#endif
    timeout = to;
    setError(throwflag);
    connect(host, port, size);
}
//.........这里部分代码省略.........
开发者ID:tmatth,项目名称:ucommon,代码行数:101,代码来源:tcp.cpp


示例12: CheckComArgOutPointerValid

/**
 * Start teleporter to the specified target.
 *
 * @returns COM status code.
 *
 * @param   aHostname       The name of the target host.
 * @param   aPort           The TCP port number.
 * @param   aPassword       The password.
 * @param   aMaxDowntime    Max allowed "downtime" in milliseconds.
 * @param   aProgress       Where to return the progress object.
 */
STDMETHODIMP
Console::Teleport(IN_BSTR aHostname, ULONG aPort, IN_BSTR aPassword, ULONG aMaxDowntime, IProgress **aProgress)
{
    /*
     * Validate parameters, check+hold object status, write lock the object
     * and validate the state.
     */
    CheckComArgOutPointerValid(aProgress);
    CheckComArgStrNotEmptyOrNull(aHostname);
    CheckComArgStrNotEmptyOrNull(aPassword);
    CheckComArgExprMsg(aPort, aPort > 0 && aPort <= 65535, ("is %u", aPort));
    CheckComArgExprMsg(aMaxDowntime, aMaxDowntime > 0, ("is %u", aMaxDowntime));

    Utf8Str strPassword(aPassword);
    if (!strPassword.isEmpty())
    {
        if (VBoxIsPasswordHashed(&strPassword))
            return setError(E_INVALIDARG, tr("The specified password resembles a hashed password, expected plain text"));
        VBoxHashPassword(&strPassword);
    }

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    AutoWriteLock autoLock(this COMMA_LOCKVAL_SRC_POS);
    LogFlowThisFunc(("mMachineState=%d\n", mMachineState));

    switch (mMachineState)
    {
    case MachineState_Running:
    case MachineState_Paused:
        break;

    default:
        return setError(VBOX_E_INVALID_VM_STATE,
                        tr("Invalid machine state: %s (must be Running or Paused)"),
                        Global::stringifyMachineState(mMachineState));
    }


    /*
     * Create a progress object, spawn a worker thread and change the state.
     * Note! The thread won't start working until we release the lock.
     */
    LogFlowThisFunc(("Initiating TELEPORT request...\n"));

    ComObjPtr<Progress> ptrProgress;
    HRESULT hrc = ptrProgress.createObject();
    if (SUCCEEDED(hrc))
        hrc = ptrProgress->init(static_cast<IConsole *>(this),
                                Bstr(tr("Teleporter")).raw(),
                                TRUE /*aCancelable*/);
    if (FAILED(hrc))
        return hrc;

    TeleporterStateSrc *pState = new TeleporterStateSrc(this, mpUVM, ptrProgress, mMachineState);
    pState->mstrPassword    = strPassword;
    pState->mstrHostname    = aHostname;
    pState->muPort          = aPort;
    pState->mcMsMaxDowntime = aMaxDowntime;

    void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(pState));
    ptrProgress->setCancelCallback(teleporterProgressCancelCallback, pvUser);

    int vrc = RTThreadCreate(NULL, Console::teleporterSrcThreadWrapper, (void *)pState, 0 /*cbStack*/,
                             RTTHREADTYPE_EMULATION, 0 /*fFlags*/, "Teleport");
    if (RT_SUCCESS(vrc))
    {
        if (mMachineState == MachineState_Running)
            hrc = setMachineState(MachineState_Teleporting);
        else
            hrc = setMachineState(MachineState_TeleportingPausedVM);
        if (SUCCEEDED(hrc))
        {
            ptrProgress.queryInterfaceTo(aProgress);
            mptrCancelableProgress = ptrProgress;
        }
        else
            ptrProgress->Cancel();
    }
    else
    {
        ptrProgress->setCancelCallback(NULL, NULL);
        delete pState;
        hrc = setError(E_FAIL, tr("RTThreadCreate -> %Rrc"), vrc);
    }

    return hrc;
}
开发者ID:marktsai0316,项目名称:VirtualMonitor,代码行数:100,代码来源:ConsoleImplTeleporter.cpp


示例13: autoCaller

/**
 * Do the teleporter.
 *
 * @returns VBox status code.
 * @param   pState              The teleporter state.
 */
HRESULT
Console::teleporterSrc(TeleporterStateSrc *pState)
{
    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    /*
     * Wait for Console::Teleport to change the state.
     */
    {
        AutoWriteLock autoLock(this COMMA_LOCKVAL_SRC_POS);
    }

    BOOL fCanceled = TRUE;
    HRESULT hrc = pState->mptrProgress->COMGETTER(Canceled)(&fCanceled);
    if (FAILED(hrc))
        return hrc;
    if (fCanceled)
        return setError(E_FAIL, tr("canceled"));

    /*
     * Try connect to the destination machine, disable Nagle.
     * (Note. The caller cleans up mhSocket, so we can return without worries.)
     */
    int vrc = RTTcpClientConnect(pState->mstrHostname.c_str(), pState->muPort, &pState->mhSocket);
    if (RT_FAILURE(vrc))
        return setError(E_FAIL, tr("Failed to connect to port %u on '%s': %Rrc"),
                        pState->muPort, pState->mstrHostname.c_str(), vrc);
    vrc = RTTcpSetSendCoalescing(pState->mhSocket, false /*fEnable*/);
    AssertRC(vrc);

    /* Read and check the welcome message. */
    char szLine[RT_MAX(128, sizeof(g_szWelcome))];
    RT_ZERO(szLine);
    vrc = RTTcpRead(pState->mhSocket, szLine, sizeof(g_szWelcome) - 1, NULL);
    if (RT_FAILURE(vrc))
        return setError(E_FAIL, tr("Failed to read welcome message: %Rrc"), vrc);
    if (strcmp(szLine, g_szWelcome))
        return setError(E_FAIL, tr("Unexpected welcome %.*Rhxs"), sizeof(g_szWelcome) - 1, szLine);

    /* password */
    pState->mstrPassword.append('\n');
    vrc = RTTcpWrite(pState->mhSocket, pState->mstrPassword.c_str(), pState->mstrPassword.length());
    if (RT_FAILURE(vrc))
        return setError(E_FAIL, tr("Failed to send password: %Rrc"), vrc);

    /* ACK */
    hrc = teleporterSrcReadACK(pState, "password", tr("Invalid password"));
    if (FAILED(hrc))
        return hrc;

    /*
     * Start loading the state.
     *
     * Note! The saved state includes vital configuration data which will be
     *       verified against the VM config on the other end.  This is all done
     *       in the first pass, so we should fail pretty promptly on misconfig.
     */
    hrc = teleporterSrcSubmitCommand(pState, "load");
    if (FAILED(hrc))
        return hrc;

    RTSocketRetain(pState->mhSocket);
    void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(pState));
    vrc = VMR3Teleport(VMR3GetVM(pState->mpUVM),
                       pState->mcMsMaxDowntime,
                       &g_teleporterTcpOps,         pvUser,
                       teleporterProgressCallback,  pvUser,
                       &pState->mfSuspendedByUs);
    RTSocketRelease(pState->mhSocket);
    if (RT_FAILURE(vrc))
    {
        if (   vrc == VERR_SSM_CANCELLED
                && RT_SUCCESS(RTTcpSelectOne(pState->mhSocket, 1)))
        {
            hrc = teleporterSrcReadACK(pState, "load-complete");
            if (FAILED(hrc))
                return hrc;
        }
        return setError(E_FAIL, tr("VMR3Teleport -> %Rrc"), vrc);
    }

    hrc = teleporterSrcReadACK(pState, "load-complete");
    if (FAILED(hrc))
        return hrc;

    /*
     * We're at the point of no return.
     */
    if (!pState->mptrProgress->notifyPointOfNoReturn())
    {
        teleporterSrcSubmitCommand(pState, "cancel", false /*fWaitForAck*/);
        return E_FAIL;
    }
//.........这里部分代码省略.........
开发者ID:marktsai0316,项目名称:VirtualMonitor,代码行数:101,代码来源:ConsoleImplTeleporter.cpp


示例14: LogThisFunc

/**
 * Creates a TCP server that listens for the source machine and passes control
 * over to Console::teleporterTrgServeConnection().
 *
 * @returns VBox status code.
 * @param   pUVM                The user-mode VM handle
 * @param   pMachine            The IMachine for the virtual machine.
 * @param   pErrorMsg           Pointer to the error string for VMSetError.
 * @param   fStartPaused        Whether to start it in the Paused (true) or
 *                              Running (false) state,
 * @param   pProgress           Pointer to the progress object.
 * @param   pfPowerOffOnFailure Whether the caller should power off
 *                              the VM on failure.
 *
 * @remarks The caller expects error information to be set on failure.
 * @todo    Check that all the possible failure paths sets error info...
 */
HRESULT
Console::teleporterTrg(PUVM pUVM, IMachine *pMachine, Utf8Str *pErrorMsg, bool fStartPaused,
                       Progress *pProgress, bool *pfPowerOffOnFailure)
{
    LogThisFunc(("pUVM=%p pMachine=%p fStartPaused=%RTbool pProgress=%p\n", pUVM, pMachine, fStartPaused, pProgress));

    *pfPowerOffOnFailure = true;

    /*
     * Get the config.
     */
    ULONG uPort;
    HRESULT hrc = pMachine->COMGETTER(TeleporterPort)(&uPort);
    if (FAILED(hrc))
        return hrc;
    ULONG const uPortOrg = uPort;

    Bstr bstrAddress;
    hrc = pMachine->COMGETTER(TeleporterAddress)(bstrAddress.asOutParam());
    if (FAILED(hrc))
        return hrc;
    Utf8Str strAddress(bstrAddress);
    const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();

    Bstr bstrPassword;
    hrc = pMachine->COMGETTER(TeleporterPassword)(bstrPassword.asOutParam());
    if (FAILED(hrc))
        return hrc;
    Utf8Str strPassword(bstrPassword);
    strPassword.append('\n');           /* To simplify password checking. */

    /*
     * Create the TCP server.
     */
    int vrc;
    PRTTCPSERVER hServer;
    if (uPort)
        vrc = RTTcpServerCreateEx(pszAddress, uPort, &hServer);
    else
    {
        for (int cTries = 10240; cTries > 0; cTries--)
        {
            uPort = RTRandU32Ex(cTries >= 8192 ? 49152 : 1024, 65534);
            vrc = RTTcpServerCreateEx(pszAddress, uPort, &hServer);
            if (vrc != VERR_NET_ADDRESS_IN_USE)
                break;
        }
        if (RT_SUCCESS(vrc))
        {
            hrc = pMachine->COMSETTER(TeleporterPort)(uPort);
            if (FAILED(hrc))
            {
                RTTcpServerDestroy(hServer);
                return hrc;
            }
        }
    }
    if (RT_FAILURE(vrc))
        return setError(E_FAIL, tr("RTTcpServerCreateEx failed with status %Rrc"), vrc);

    /*
     * Create a one-shot timer for timing out after 5 mins.
     */
    RTTIMERLR hTimerLR;
    vrc = RTTimerLRCreateEx(&hTimerLR, 0 /*ns*/, RTTIMER_FLAGS_CPU_ANY, teleporterDstTimeout, hServer);
    if (RT_SUCCESS(vrc))
    {
        vrc = RTTimerLRStart(hTimerLR, 5*60*UINT64_C(1000000000) /*ns*/);
        if (RT_SUCCESS(vrc))
        {
            /*
             * Do the job, when it returns we're done.
             */
            TeleporterStateTrg theState(this, pUVM, pProgress, pMachine, mControl, &hTimerLR, fStartPaused);
            theState.mstrPassword      = strPassword;
            theState.mhServer          = hServer;

            void *pvUser = static_cast<void *>(static_cast<TeleporterState *>(&theState));
            if (pProgress->setCancelCallback(teleporterProgressCancelCallback, pvUser))
            {
                LogRel(("Teleporter: Waiting for incoming VM...\n"));
                hrc = pProgress->SetNextOperation(Bstr(tr("Waiting for incoming VM")).raw(), 1);
                if (SUCCEEDED(hrc))
//.........这里部分代码省略.........
开发者ID:marktsai0316,项目名称:VirtualMonitor,代码行数:101,代码来源:ConsoleImplTeleporter.cpp


示例15: parse

	/// \brief Call the first/next iteration of parsing the header
	/// \return true on success, false if more data is needed (putInput(const char*,std::size_t)) or if an error occurred. Check lasterror() for an error
	bool parse()
	{
		unsigned char ch = nextChar();
		for (;ch != 0; ch = nextChar())
		{
			switch (m_state)
			{
				case Init:
					if (ch == '<')
					{
						m_state = ParseXmlOpen;
					}
					else if (ch <= 32)
					{
						continue;
					}
					else
					{
						setError( "expected open tag angle bracket '>'");
						return false;
					}
					break;

				case ParseXmlOpen:
					if (ch == '?')
					{
						m_state = ParseXmlHdr;
					}
					else if (ch <= 32)
					{
						break;
					}
					else if (((ch|32) >= 'a' && (ch|32) <= 'z') || ch == '_')
					{
						return true;
					}
					else
					{
						setError( "expected xml header question mark '?' after open tag angle bracket '<'");
						return false;
					}
					break;

				case ParseXmlHdr:
					if (ch <= 32 || ch == '?')
					{
						if (m_item != "xml")
						{
							setError( "expected '<?xml' as xml header start");
							return false;
						}
						m_item.clear();
						if (ch == '?') return true; /*...."<?xml?>"*/

						m_state = FindAttributeName;
					}
					else if (((ch|32) >= 'a' && (ch|32) <= 'z') || ch == '_')
					{
						m_item.push_back(ch);
						continue;
					}
					else if (ch == '>')
					{
						setError( "unexpected close angle bracket '>' in xml header after '<?xml'");
						return false;
					}
					else
					{
						setError( "expected '<?xml' as xml header start (invalid character)");
						return false;
					}
					break;

				case FindAttributeName:
					if (ch <= 32)
					{
						continue;
					}
					else if (ch == '>' || ch == '?')
					{
						if (ch == '>')
						{
							setError( "unexpected close angle bracket '>' in xml header (missing '?')");
							return false;
						}
						return true;
					}
					else if (((ch|32) >= 'a' && (ch|32) <= 'z') || ch == '_')
					{
						m_item.push_back(ch);
						m_state = ParseAttributeName;
					}
					else
					{
						setError( "invalid character in xml header attribute name");
						return false;
					}
					break;
//.........这里部分代码省略.........
开发者ID:patrickfrey,项目名称:textwolf,代码行数:101,代码来源:xmlhdrparser.hpp


示例16: setError

void JsonRpcResponse::setError(const Error& error)
{   
   setError(error, json::Value());
}
开发者ID:Wisling,项目名称:rstudio,代码行数:4,代码来源:JsonRpc.cpp


示例17: setError

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ setErrorCode函数代码示例发布时间:2022-05-30
下一篇:
C++ setEntry函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap