예제 #1
0
void SIPAccount::setAccountDetails (std::map<std::string, std::string> details)
{
    // Account setting common to SIP and IAX
    setAlias (details[CONFIG_ACCOUNT_ALIAS]);
    setType (details[CONFIG_ACCOUNT_TYPE]);
    setUsername (details[USERNAME]);
    setHostname (details[HOSTNAME]);
    setEnabled ( (details[CONFIG_ACCOUNT_ENABLE] == "true"));
    setRingtonePath (details[CONFIG_RINGTONE_PATH]);
    setRingtoneEnabled ( (details[CONFIG_RINGTONE_ENABLED] == "true"));
    setMailBox (details[CONFIG_ACCOUNT_MAILBOX]);

    // SIP specific account settings

    // general sip settings
    setDisplayName (details[DISPLAY_NAME]);
    setServiceRoute (details[ROUTESET]);
    setLocalInterface (details[LOCAL_INTERFACE]);
    setPublishedSameasLocal (details[PUBLISHED_SAMEAS_LOCAL] == "true");
    setPublishedAddress (details[PUBLISHED_ADDRESS]);
    setLocalPort (atoi (details[LOCAL_PORT].c_str()));
    setPublishedPort (atoi (details[PUBLISHED_PORT].c_str()));
    setStunServer (details[STUN_SERVER]);
    setStunEnabled (details[STUN_ENABLE] == "true");
    setDtmfType ( (details[ACCOUNT_DTMF_TYPE] == "overrtp") ? OVERRTP : SIPINFO);

    setResolveOnce (details[CONFIG_ACCOUNT_RESOLVE_ONCE] == "true");
    setRegistrationExpire (details[CONFIG_ACCOUNT_REGISTRATION_EXPIRE]);

    setUseragent (details[USERAGENT]);

    // srtp settings
    setSrtpEnable (details[SRTP_ENABLE] == "true");
    setSrtpFallback (details[SRTP_RTP_FALLBACK] == "true");
    setZrtpDisplaySas (details[ZRTP_DISPLAY_SAS] == "true");
    setZrtpDiaplaySasOnce (details[ZRTP_DISPLAY_SAS_ONCE] == "true");
    setZrtpNotSuppWarning (details[ZRTP_NOT_SUPP_WARNING] == "true");
    setZrtpHelloHash (details[ZRTP_HELLO_HASH] == "true");
    setSrtpKeyExchange (details[SRTP_KEY_EXCHANGE]);

    // TLS settings
    // The TLS listener is unique and globally defined through IP2IP_PROFILE
    if (_accountID == IP2IP_PROFILE)
    	setTlsListenerPort (atoi (details[TLS_LISTENER_PORT].c_str()));

    setTlsEnable (details[TLS_ENABLE]);
    setTlsCaListFile (details[TLS_CA_LIST_FILE]);
    setTlsCertificateFile (details[TLS_CERTIFICATE_FILE]);
    setTlsPrivateKeyFile (details[TLS_PRIVATE_KEY_FILE]);
    setTlsPassword (details[TLS_PASSWORD]);
    setTlsMethod (details[TLS_METHOD]);
    setTlsCiphers (details[TLS_CIPHERS]);
    setTlsServerName (details[TLS_SERVER_NAME]);
    setTlsVerifyServer (details[TLS_VERIFY_SERVER] == "true");
    setTlsVerifyClient (details[TLS_VERIFY_CLIENT] == "true");
    setTlsRequireClientCertificate (details[TLS_REQUIRE_CLIENT_CERTIFICATE] == "true");
    setTlsNegotiationTimeoutSec (details[TLS_NEGOTIATION_TIMEOUT_SEC]);
    setTlsNegotiationTimeoutMsec (details[TLS_NEGOTIATION_TIMEOUT_MSEC]);
}
FTPActiveTextDataOut::FTPActiveTextDataOut(QHostAddress aHostAdress, int aHostPort, QHostAddress aLocalAdress, int aLocalPort, QObject *parent)
    :QTcpSocket(parent)
{
    setLocalPort(aLocalPort);
    setLocalAddress(aLocalAdress);
    connect(this,SIGNAL(disconnected()),this,SLOT(connectionClosedSlot()));
    connectToHost(aHostAdress,aHostPort,QIODevice::ReadWrite);
}
void PeerWireClient::socketStateChanged(QAbstractSocket::SocketState state)
{
    setLocalAddress(socket.localAddress());
    setLocalPort(socket.localPort());
    setPeerName(socket.peerName());
    setPeerAddress(socket.peerAddress());
    setPeerPort(socket.peerPort());
    setSocketState(state);
}
예제 #4
0
void CNetworkConnection::socketStateChanged(QAbstractSocket::SocketState state)
{
    setLocalAddress(m_pSocket->localAddress());
    setLocalPort(m_pSocket->localPort());
    setPeerName(m_pSocket->peerName());
    setPeerAddress(m_pSocket->peerAddress());
    setPeerPort(m_pSocket->peerPort());
    setSocketState(state);
}
예제 #5
0
// localPort: Local (source) port number
bool NetHandler::setSlotLocalPort(const Number* const msg)
{
    bool ok = false;
    if (msg != 0) {
        int ii = msg->getInt();
        if (ii >= 0x0 && ii <= 0xffff) {
            ok = setLocalPort( (uint16_t) ii );
        }
    }
    return ok;
}
예제 #6
0
// localPort: Local (source) port number
bool PosixHandler::setSlotLocalPort(const Number* const msg)
{
    bool ok = false;
    if (msg != nullptr) {
        int ii = msg->getInt();
        if (ii >= 0x0 && ii <= 0xffff) {
            ok = setLocalPort( static_cast<uint16_t>(ii) );
        }
    }
    return ok;
}
예제 #7
0
DataTunnel::DataTunnel()
{
	this->agentFd=INVALID_SOCKET;
	this->serverConnected=false;
	this->runFlag=false;
	this->g_hMutex_send_network= INVALID_HANDLE_VALUE;  
	this->g_hMutex_audio_network=INVALID_HANDLE_VALUE;
	this->g_hMutex_video_network=INVALID_HANDLE_VALUE;
	this->nalPacketCursor=0;
	this->videoPacketCursor=0;
	setLocalPort(DEFAULT_LOCALPORT);
	this->setEndpointAddr(DEFAULT_REMOTEADDRESS,DEFAULT_REMOTEPORT);
}
예제 #8
0
파일: socket.cpp 프로젝트: alyst/zorba
TCPServerSocket::TCPServerSocket(unsigned short localPort, int queueLen): Socket(SOCK_STREAM, IPPROTO_TCP) {
  setLocalPort(localPort);
  setListen(queueLen);
}
예제 #9
0
void AtDrv::startClient(uint8_t sock, const char *host, uint16_t port, uint8_t protMode)
{
	// if we enable CHECK_TCP_STATE feature, always call reConnect(), or we won't get right
	// tcp port status, since we disable tcp auto reconnect.
#ifndef CHECK_TCP_STATE
	bool needReConn = false;
#else
	bool needReConn = true;
#endif
	int curMode;
	char curHostBuf[MAX_HOST_NAME_BUF_SIZE];
	uint8_t curProtocol;
	uint16_t curPort;
	uint16_t curLocalPort;
	uint32_t curTimeout;
	bool curTcpAuto;

	// clear uart buffer first
	stopClient(sock);

	if(!isAtMode()) {
		if(!switchToAtMode()) {
			INFO1("Can't switch to at mode");
			goto end;
		}
	}
	
	if(!getMode(sock, &curMode) || curMode != MODE_CLIENT) {
		needReConn = true;
		INFO1("curMode != MODE_CLIENT");
		if(!setMode(sock, MODE_CLIENT)) {
			INFO1("Can't set mode");
			goto end;			
		}
	}

	if(!getRemoteHost(sock, curHostBuf) || (strcmp(curHostBuf,  host) != 0)) {
		needReConn = true;
		INFO1("curHostBuf != host");
		if(!setRemoteHost(sock, host)) {
			INFO1("Can't set host");
			goto end;	
		}
	}
	
	if(!getProtocol(sock, &curProtocol) || curProtocol != protMode) {
		needReConn = true;
		INFO1("curProtocol != protMode");
		if(!setProtocol(sock, protMode)) {
			INFO1("Can't set protocol");
			goto end;	
		}
	}
	
	if(!getRemotePort(sock, &curPort) || curPort != port) {
		needReConn = true;
		INFO1("curPort != port");
		if(!setPort(sock, port)) {
			INFO1("Can't set port");
			goto end;	
		}
	}
	
	if(!getTcpAuto(sock, &curTcpAuto) || curTcpAuto != false) {
		needReConn = true;
		INFO1("curTcpAuto != false");	
		if(!setTcpAuto(sock, false)) {
			INFO1("Can't set tcp auto");
			goto end;	
		}
	}	
	
	if(!getLocalPort(sock, &curLocalPort) || curLocalPort != localSockPort[sock]) {
		needReConn = true;
		INFO1("curLocalPort != port");
		if(!setLocalPort(sock, localSockPort[sock])) {
			INFO1("Can't set port");
			goto end;	
		}
	}	
	
	if(needReConn) {
		if(!reConnect()) {
			INFO1("Can't reconnect");
			goto end;	
		}
	}	

	sockPort[sock] = localSockPort[sock];
	sockConnected[sock] = true;

end:
	return;
}
예제 #10
0
void AtDrv::startClient(uint8_t sock, uint32_t ipAddress, uint16_t port, uint8_t protMode)
{
	// if we enable CHECK_TCP_STATE feature, always call reConnect(), or we won't get right
	// tcp port status, since we disable tcp auto reconnect.
#ifndef CHECK_TCP_STATE
	bool needReConn = false;
#else
	bool needReConn = true;
#endif
	int curMode;
	uint32_t curIp;
	uint8_t curProtocol;
	uint16_t curPort;
	uint16_t curLocalPort;
	uint32_t curTimeout;
	bool curTcpAuto;

	// clear uart buffer first
	stopClient(sock);
	
	if(!isAtMode()) {
		if(!switchToAtMode()) {
			INFO1("Can't switch to at mode");
			goto end;
		}
	}
	
	if(!getMode(sock, &curMode) || curMode != MODE_CLIENT) {
		needReConn = true;
		INFO1("curMode != MODE_CLIENT");
		if(!setMode(sock, MODE_CLIENT)) {
			INFO1("Can't set mode");
			goto end;			
		}
	}
	
	if(!getRemoteIp(sock, (uint8_t *)&curIp) || curIp != ipAddress) {
		needReConn = true;
		INFO1("curIp != ipAddress");
		if(!setRemoteIp(sock, ipAddress)) {
			INFO1("Can't set ip");
			goto end;	
		}
	}
	
	if(!getProtocol(sock, &curProtocol) || curProtocol != protMode) {
		needReConn = true;
		INFO1("curProtocol != protMode");
		if(!setProtocol(sock, protMode)) {
			INFO1("Can't set protocol");
			goto end;	
		}
	}
	
	if(!getRemotePort(sock, &curPort) || curPort != port) {
		needReConn = true;
		INFO1("curPort != port");
		if(!setPort(sock, port)) {
			INFO1("Can't set port");
			goto end;	
		}
	}

	if(!getTcpAuto(sock, &curTcpAuto) || curTcpAuto != false) {
		needReConn = true;
		INFO1("curTcpAuto != false");	
		if(!setTcpAuto(sock, false)) {
			INFO1("Can't set tcp auto");
			goto end;	
		}
	}
	
	if(!getLocalPort(sock, &curLocalPort) || curLocalPort != localSockPort[sock]) {
		needReConn = true;
		INFO1("curLocalPort != port");
		if(!setLocalPort(sock, localSockPort[sock])) {
			INFO1("Can't set port");
			goto end;	
		}
	}
	
	if(needReConn) {
		if(!reConnect()) {
			INFO1("Can't reconnect");
			goto end;	
		}
	}

	sockPort[sock] = localSockPort[sock];
	sockConnected[sock] = true;

end:
	return;
}
UDPSocket::UDPSocket(unsigned short localPort)  throw(SocketException) :
    CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP) {
  setLocalPort(localPort);
  setBroadcast();
}
예제 #12
0
void QHttpSocketEngine::slotSocketReadNotification()
{
    Q_D(QHttpSocketEngine);
    if (d->state != Connected && d->socket->bytesAvailable() == 0)
        return;

    if (d->state == Connected) {
        // Forward as a read notification.
        if (d->readNotificationEnabled)
            emitReadNotification();
        return;
    }

    if (d->state == ConnectSent) {
        d->reply->d_func()->state = QHttpNetworkReplyPrivate::NothingDoneState;
        d->state = ReadResponseHeader;
    }

    if (d->state == ReadResponseHeader) {
        bool ok = readHttpHeader();
        if (!ok) {
            // protocol error, this isn't HTTP
            d->socket->close();
            setState(QAbstractSocket::UnconnectedState);
            setError(QAbstractSocket::ProxyProtocolError, tr("Did not receive HTTP response from proxy"));
            emitConnectionNotification();
            return;
        }
        if (d->state == ReadResponseHeader)
            return; // readHttpHeader() was not done yet, need to wait for more header data
    }

    if (d->state == ReadResponseContent) {
        char dummybuffer[4096];
        while (d->pendingResponseData) {
            int read = d->socket->read(dummybuffer, qMin(sizeof(dummybuffer), (size_t)d->pendingResponseData));
            if (read == 0)
                return;
            if (read == -1) {
                d->socket->disconnectFromHost();
                emitWriteNotification();
                return;
            }
            d->pendingResponseData -= read;
        }
        if (d->pendingResponseData > 0)
            return;
        if (d->reply->d_func()->statusCode == 407)
            d->state = SendAuthentication;
    }

    int statusCode = d->reply->statusCode();
    QAuthenticatorPrivate *priv = 0;
    if (statusCode == 200) {
        d->state = Connected;
        setLocalAddress(d->socket->localAddress());
        setLocalPort(d->socket->localPort());
        setState(QAbstractSocket::ConnectedState);
        d->authenticator.detach();
        priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
        priv->hasFailed = false;
    } else if (statusCode == 407) {
        if (d->authenticator.isNull())
            d->authenticator.detach();
        priv = QAuthenticatorPrivate::getPrivate(d->authenticator);

        if (d->credentialsSent && priv->phase != QAuthenticatorPrivate::Phase2) {
            // Remember that (e.g.) NTLM is two-phase, so only reset when the authentication is not currently in progress.
            //407 response again means the provided username/password were invalid.
            d->authenticator = QAuthenticator(); //this is needed otherwise parseHttpResponse won't set the state, and then signal isn't emitted.
            d->authenticator.detach();
            priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
            priv->hasFailed = true;
        }

        priv->parseHttpResponse(d->reply->header(), true);

        if (priv->phase == QAuthenticatorPrivate::Invalid) {
            // problem parsing the reply
            d->socket->close();
            setState(QAbstractSocket::UnconnectedState);
            setError(QAbstractSocket::ProxyProtocolError, tr("Error parsing authentication request from proxy"));
            emitConnectionNotification();
            return;
        }

        bool willClose;
        QByteArray proxyConnectionHeader = d->reply->headerField("Proxy-Connection");
        // Although most proxies use the unofficial Proxy-Connection header, the Connection header
        // from http spec is also allowed.
        if (proxyConnectionHeader.isEmpty())
            proxyConnectionHeader = d->reply->headerField("Connection");
        proxyConnectionHeader = proxyConnectionHeader.toLower();
        if (proxyConnectionHeader == "close") {
            willClose = true;
        } else if (proxyConnectionHeader == "keep-alive") {
            willClose = false;
        } else {
            // no Proxy-Connection header, so use the default
            // HTTP 1.1's default behaviour is to keep persistent connections
            // HTTP 1.0 or earlier, so we expect the server to close
            willClose = (d->reply->majorVersion() * 0x100 + d->reply->minorVersion()) <= 0x0100;
        }

        if (willClose) {
            // the server will disconnect, so let's avoid receiving an error
            // especially since the signal below may trigger a new event loop
            d->socket->disconnectFromHost();
            d->socket->readAll();
            //We're done with the reply and need to reset it for the next connection
            delete d->reply;
            d->reply = new QHttpNetworkReply;
        }

        if (priv->phase == QAuthenticatorPrivate::Done)
            emit proxyAuthenticationRequired(d->proxy, &d->authenticator);
        // priv->phase will get reset to QAuthenticatorPrivate::Start if the authenticator got modified in the signal above.
        if (priv->phase == QAuthenticatorPrivate::Done) {
            setError(QAbstractSocket::ProxyAuthenticationRequiredError, tr("Authentication required"));
            d->socket->disconnectFromHost();
        } else {
            // close the connection if it isn't already and reconnect using the chosen authentication method
            d->state = SendAuthentication;
            if (willClose) {
                d->socket->connectToHost(d->proxy.hostName(), d->proxy.port());
            } else {
                // send the HTTP CONNECT again
                slotSocketConnected();
            }
            return;
        }
    } else {
        d->socket->close();
        setState(QAbstractSocket::UnconnectedState);
        if (statusCode == 403 || statusCode == 405) {
            // 403 Forbidden
            // 405 Method Not Allowed
            setError(QAbstractSocket::SocketAccessError, tr("Proxy denied connection"));
        } else if (statusCode == 404) {
            // 404 Not Found: host lookup error
            setError(QAbstractSocket::HostNotFoundError, QAbstractSocket::tr("Host not found"));
        } else if (statusCode == 503) {
            // 503 Service Unavailable: Connection Refused
            setError(QAbstractSocket::ConnectionRefusedError, QAbstractSocket::tr("Connection refused"));
        } else {
            // Some other reply
            //qWarning("UNEXPECTED RESPONSE: [%s]", responseHeader.toString().toLatin1().data());
            setError(QAbstractSocket::ProxyProtocolError, tr("Error communicating with HTTP proxy"));
        }
    }

    // The handshake is done; notify that we're connected (or failed to connect)
    emitConnectionNotification();
}
예제 #13
0
void DhQAbstractSocket::DvhsetLocalPort(quint16 x1) {
  return setLocalPort(x1);
}
예제 #14
0
int Cconfigurator::loadConfig(QByteArray path, QByteArray filename)
{
	int size;
	QSettings conf(path + filename, QSettings::IniFormat);

	conf.beginGroup("General");
    setBaseFile( conf.value("mapFile", "database/mume.pmf").toByteArray() );
	setWindowRect( conf.value("windowRect").toRect() );
	setAlwaysOnTop( conf.value("alwaysOnTop", true ).toBool() );
	setStartupMode( conf.value("startupMode", 1).toInt() );
    setLogFileEnabled( conf.value("isLogFileEnabled", false).toBool() );
	conf.endGroup();

	conf.beginGroup("Networking");
	setLocalPort( conf.value("localPort", 4242).toInt() );
	setRemoteHost( conf.value("remoteHost", "193.134.218.111").toByteArray() );
	setRemotePort( conf.value("remotePort", 443).toInt() );
	conf.endGroup();

	conf.beginGroup("OpenGL");
	setTextureVisibility( conf.value("texturesVisibility", 500).toInt() );
	setDetailsVisibility( conf.value("detailsVisibility", 300).toInt() );
	setVisibleLayers( conf.value("visibleLayers", 5).toInt() );
	setShowNotesRenderer( conf.value("showNotes", true).toBool() );
	setShowRegionsInfo( conf.value("showRegions", false). toBool() );
	setDisplayRegionsRenderer( conf.value("displayRegions", false).toBool() );
	setMultisampling( conf.value("multisampling", true).toBool() );
	setSelectOAnyLayer( conf.value("selectOnAnyLayer", true).toBool() );
    setRendererAngles(conf.value("angleX", 0).toFloat(), conf.value("angleY", 0).toFloat(), conf.value("angleZ", 0).toFloat());
    setRendererPosition(conf.value("userX", 0).toFloat(), conf.value("userY", 0).toFloat(), conf.value("userZ", 0).toFloat());
    setNoteColor( conf.value("noteColor", "#F28003").toByteArray() );
    setDrawPrespam(  conf.value("drawPrespam", true).toBool() );

	conf.endGroup();

	conf.beginGroup("Engine");
	setExitsCheck( conf.value("checkExits", false).toBool() );
	setTerrainCheck( conf.value("checkTerrain", true).toBool() );
	setBriefMode( conf.value("briefmode", true ).toBool() );
	setAutomerge( conf.value("autoMerge", true ).toBool() );
	setAngrylinker( conf.value("angryLinker", true ).toBool() );
	setDuallinker( conf.value("dualLinker", false ).toBool() );
	setAutorefresh( conf.value("autoRefresh", true ).toBool() );
	setNameQuote( conf.value("roomNameQuote", 10 ).toInt() );
	setDescQuote( conf.value("descQuote", 10 ).toInt() );
	setRegionsAutoReplace( conf.value("regionsAutoReplace", false ).toBool() );
	setRegionsAutoSet( conf.value("regionsAutoSet", false ).toBool() );
	setMactionUsesPrespam( conf.value("mactionUsesPrespam", true).toBool() );
	setPrespamTTL( conf.value("prespamTTL", 5000).toInt() );

	conf.endGroup();

    conf.beginGroup("Patterns");
    setExitsPattern( conf.value("exitsPattern", "Exits: ").toByteArray() );
    spells_pattern = conf.value("spellsEffectPattern", "Affected by:").toByteArray();
    setScorePattern( conf.value("scorePattern", "[0-9]*/* hits, */* mana, and */* moves.").toByteArray()  );
    setShortScorePattern( conf.value("scorePatternShort", "[0-9]*/* hits and */* moves.").toByteArray() );
	conf.endGroup();


	conf.beginGroup("GroupManager");
	setGroupManagerHost( conf.value("remoteHost", "localhost").toByteArray() );
	setGroupManagerRemotePort( conf.value("remotePort", 4243 ).toInt() );
	setGroupManagerLocalPort( conf.value("localServerPort", 4243 ).toInt() );
	setGroupManagerCharName( conf.value("charName", "Charname" ).toByteArray() );
	setGroupManagerColor( QColor( conf.value("charColor", "#F28003").toString() ) );
	setGroupManagerShowSelf( conf.value("showSelf", false ).toBool() );
	setGroupManagerNotifyArmour( conf.value("notifyArm", true ).toBool() );
	setGroupManagerNotifySanc( conf.value("notifySanc", true ).toBool() );
	setGroupManagerNotifyBash( conf.value("notifyBash", true ).toBool() );
	setGroupManagerShowManager( conf.value("showGroupManager", true ).toBool() );
	setGroupManagerRect( conf.value("windowRect").toRect() );
	conf.endGroup();


	size = conf.beginReadArray("Spells");
	for (int i = 0; i < size; ++i) {
	  conf.setArrayIndex(i);
	  TSpell spell;

      spell.up = false;
      spell.silently_up = false;
	  spell.addon = conf.value("addon", 0).toBool();
	  spell.name = conf.value("name").toByteArray();
	  spell.up_mes = conf.value("upMessage").toByteArray();
	  spell.refresh_mes = conf.value("refreshMessage").toByteArray();
	  spell.down_mes = conf.value("downMessage").toByteArray();

      addSpell(spell);
	}
	conf.endArray();


	conf.beginGroup("Movement tracking");
	size = conf.beginReadArray("Cancel Patterns");
	for (int i = 0; i < size; ++i) {
	  conf.setArrayIndex(i);
	  moveCancelPatterns.append( conf.value("pattern").toByteArray() );
	}
	conf.endArray();
	size = conf.beginReadArray("Force Patterns");
	for (int i = 0; i < size; ++i) {
	  conf.setArrayIndex(i);
	  moveForcePatterns.append( conf.value("pattern").toByteArray() );
	}
	conf.endArray();
	conf.endGroup();

	size = conf.beginReadArray("Debug Settings");
	for (int i = 0; i < size; ++i) {
	  conf.setArrayIndex(i);

      QString s = conf.value("name").toString();

	  unsigned int z = 0;
      while (debug_data[z].name != NULL) {
          if (debug_data[z].name == s)
              break;
          z++;
      }
      if (debug_data[z].name == NULL) {
          print_debug(DEBUG_CONFIG, "Warning, %s is a wrong debug descriptor/name!", qPrintable(s));
          continue;
      }

      debug_data[i].state = conf.value("state", 0 ).toInt();
	}
	conf.endArray();

	configFile = filename;
	configPath = path;

	setConfigModified(false);
	return true;
}
예제 #15
0
void DataSocket::bindPort(quint16 port)
{
    setLocalPort(port);
    bind(QHostAddress::Any, port);
}
void QHttpSocketEngine::slotSocketReadNotification()
{
    Q_D(QHttpSocketEngine);
    if (d->state != Connected && d->socket->bytesAvailable() == 0)
        return;

    if (d->state == Connected) {
        // Forward as a read notification.
        if (d->readNotificationEnabled)
            emitReadNotification();
        return;
    }

  readResponseContent:
    if (d->state == ReadResponseContent) {
        char dummybuffer[4096];
        while (d->pendingResponseData) {
            int read = d->socket->read(dummybuffer, qMin(sizeof(dummybuffer), (size_t)d->pendingResponseData));
            if (read >= 0)
                dummybuffer[read] = 0;

            if (read == 0)
                return;
            if (read == -1) {
                d->socket->disconnectFromHost();
                emitWriteNotification();
                return;
            }
            d->pendingResponseData -= read;
        }
        if (d->pendingResponseData > 0)
            return;
        d->state = SendAuthentication;
        slotSocketConnected();
        return;
    }

    // Still in handshake mode. Wait until we've got a full response.
    bool done = false;
    do {
        d->readBuffer += d->socket->readLine();
    } while (!(done = d->readBuffer.endsWith("\r\n\r\n")) && d->socket->canReadLine());

    if (!done) {
        // Wait for more.
        return;
    }

    if (!d->readBuffer.startsWith("HTTP/1.")) {
        // protocol error, this isn't HTTP
        d->readBuffer.clear();
        d->socket->close();
        setState(QAbstractSocket::UnconnectedState);
        setError(QAbstractSocket::ProxyProtocolError, tr("Did not receive HTTP response from proxy"));
        emitConnectionNotification();
        return;
    }

    QHttpResponseHeader responseHeader(QString::fromLatin1(d->readBuffer));
    d->readBuffer.clear(); // we parsed the proxy protocol response. from now on direct socket reading will be done

    int statusCode = responseHeader.statusCode();
    QAuthenticatorPrivate *priv = 0;
    if (statusCode == 200) {
        d->state = Connected;
        setLocalAddress(d->socket->localAddress());
        setLocalPort(d->socket->localPort());
        setState(QAbstractSocket::ConnectedState);
        d->authenticator.detach();
        priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
        priv->hasFailed = false;
    } else if (statusCode == 407) {
        if (d->credentialsSent) {
            //407 response again means the provided username/password were invalid.
            d->authenticator = QAuthenticator(); //this is needed otherwise parseHttpResponse won't set the state, and then signal isn't emitted.
            d->authenticator.detach();
            priv = QAuthenticatorPrivate::getPrivate(d->authenticator);
            priv->hasFailed = true;
        }
        else if (d->authenticator.isNull())
            d->authenticator.detach();
        priv = QAuthenticatorPrivate::getPrivate(d->authenticator);

        priv->parseHttpResponse(responseHeader, true);

        if (priv->phase == QAuthenticatorPrivate::Invalid) {
            // problem parsing the reply
            d->socket->close();
            setState(QAbstractSocket::UnconnectedState);
            setError(QAbstractSocket::ProxyProtocolError, tr("Error parsing authentication request from proxy"));
            emitConnectionNotification();
            return;
        }

        bool willClose;
        QString proxyConnectionHeader = responseHeader.value(QLatin1String("Proxy-Connection"));
        // Although most proxies use the unofficial Proxy-Connection header, the Connection header
        // from http spec is also allowed.
        if (proxyConnectionHeader.isEmpty())
            proxyConnectionHeader = responseHeader.value(QLatin1String("Connection"));
        proxyConnectionHeader = proxyConnectionHeader.toLower();
        if (proxyConnectionHeader == QLatin1String("close")) {
            willClose = true;
        } else if (proxyConnectionHeader == QLatin1String("keep-alive")) {
            willClose = false;
        } else {
            // no Proxy-Connection header, so use the default
            // HTTP 1.1's default behaviour is to keep persistent connections
            // HTTP 1.0 or earlier, so we expect the server to close
            willClose = (responseHeader.majorVersion() * 0x100 + responseHeader.minorVersion()) <= 0x0100;
        }

        if (willClose) {
            // the server will disconnect, so let's avoid receiving an error
            // especially since the signal below may trigger a new event loop
            d->socket->disconnectFromHost();
            d->socket->readAll();
        }

        if (priv->phase == QAuthenticatorPrivate::Done)
            emit proxyAuthenticationRequired(d->proxy, &d->authenticator);
        // priv->phase will get reset to QAuthenticatorPrivate::Start if the authenticator got modified in the signal above.
        if (priv->phase == QAuthenticatorPrivate::Done) {
            setError(QAbstractSocket::ProxyAuthenticationRequiredError, tr("Authentication required"));
            d->socket->disconnectFromHost();
        } else {
            // close the connection if it isn't already and reconnect using the chosen authentication method
            d->state = SendAuthentication;
            if (willClose) {
                d->socket->connectToHost(d->proxy.hostName(), d->proxy.port());
            } else {
                bool ok;
                int contentLength = responseHeader.value(QLatin1String("Content-Length")).toInt(&ok);
                if (ok && contentLength > 0) {
                    d->state = ReadResponseContent;
                    d->pendingResponseData = contentLength;
                    goto readResponseContent;
                } else {
                    d->state = SendAuthentication;
                    slotSocketConnected();
                }
            }
            return;
        }
    } else {
        d->socket->close();
        setState(QAbstractSocket::UnconnectedState);
        if (statusCode == 403 || statusCode == 405) {
            // 403 Forbidden
            // 405 Method Not Allowed
            setError(QAbstractSocket::SocketAccessError, tr("Proxy denied connection"));
        } else if (statusCode == 404) {
            // 404 Not Found: host lookup error
            setError(QAbstractSocket::HostNotFoundError, QAbstractSocket::tr("Host not found"));
        } else if (statusCode == 503) {
            // 503 Service Unavailable: Connection Refused
            setError(QAbstractSocket::ConnectionRefusedError, QAbstractSocket::tr("Connection refused"));
        } else {
            // Some other reply
            //qWarning("UNEXPECTED RESPONSE: [%s]", responseHeader.toString().toLatin1().data());
            setError(QAbstractSocket::ProxyProtocolError, tr("Error communicating with HTTP proxy"));
        }
    }

    // The handshake is done; notify that we're connected (or failed to connect)
    emitConnectionNotification();
}
예제 #17
0
TCPServerSocket::TCPServerSocket(unsigned short localPort, int queueLen) 
    throw(ClassException<Socket>) : Socket(SOCK_STREAM, IPPROTO_TCP) {
  setLocalPort(localPort);
  setListen(queueLen);
}