/** Binds the socket to the specified port. Call bind() for an unreliable socket if the host acts as a server and waits for * messages. If the host acts as a client, call sendTo(), there is no need to bind the socket. */ void CUdpSock::bind( uint16 port ) { CInetAddress addr; // any IP address addr.setPort( port ); bind( addr ); setLocalAddress(); // will not set the address if the host is multihomed, use bind(CInetAddress) instead }
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); }
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); }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), logic(this), connectDialog(new ZeroconfConnectDialog(this)), ipConnectDialog(new IPConnectDialog(this)) { ui->setupUi(this); ui->centralwidget->setClientLogic(&logic); /* connect(connectDialog, SIGNAL(connectedTo(QHostAddress,quint16)), this, SLOT(newServerConnection(QHostAddress,quint16))); */ connect(ipConnectDialog, SIGNAL(setLocalAddress(QHostAddress)), &logic, SLOT(setLocalAddress(QHostAddress))); connect(ipConnectDialog, SIGNAL(connectedTo(QHostAddress,quint16)), this, SLOT(newServerConnection(QHostAddress,quint16))); connect(ui->centralwidget, SIGNAL(take(QString)), this, SLOT(takeNode(QString))); connect(ui->centralwidget, SIGNAL(give(QString)), this, SLOT(giveNode(QString))); connect(&logic, SIGNAL(serverPoolChanged()), ui->centralwidget, SLOT(updateServerPool())); connect(&logic, SIGNAL(localPoolChanged()), ui->centralwidget, SLOT(updateLocalPool())); connect(&logic, SIGNAL(sendLog(QString)), ui->centralwidget, SLOT(addLog(QString))); }
int Socket::passivate(unsigned short port){ string backlogStr = configuration->get("backlog"); int backlog = atoi(backlogStr.c_str()); this->port = port; setLocalAddress(port); if ((socketFd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ notifyErrorOn("get file descriptor"); return -1; } if (bind(socketFd, (struct sockaddr *) &localAddress, sizeof (localAddress)) < 0){ notifyErrorOn("bind"); return -1; } if (listen(socketFd, backlog) < 0){ notifyErrorOn("listen"); return -1; } return 0; }
int FSocketDomain::bind(struct addrinfo *addr) { int ret = 0; do { ret = createSocket(addr->ai_protocol); if (ret != 0) break; int optval = 1; ret = ::setsockopt(this->m_socketfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (ret != 0) { ELOGM_PRINTLN_ERR("setsockopt error", FUtil::getErrCode(), FUtil::getErrStr()); break; } ret = -1; while (addr != NULL) { ret = ::bind(this->m_socketfd, addr->ai_addr, addr->ai_addrlen); if (ret != 0) { ELOGM_PRINTLN_ERR("bind error", FUtil::getErrCode(), FUtil::getErrStr()); addr = addr->ai_next; continue; } break; } if (ret != 0) break; setLocalAddress(addr->ai_addr); } while (false); return ret == 0 ? 0 : -1; }
/* * Sends a message */ void CUdpSock::sendTo( const uint8 *buffer, uint len, const CInetAddress& addr ) { // Send if ( ::sendto( _Sock, (const char*)buffer, len, 0, (sockaddr*)(addr.sockAddr()), sizeof(sockaddr) ) != (sint32)len ) { throw ESocket( "Unable to send datagram" ); } _BytesSent += len; if ( _Logging ) { LNETL0_DEBUG( "LNETL0: Socket %d sent %d bytes to %s", _Sock, len, addr.asString().c_str() ); } // If socket is unbound, retrieve local address if ( ! _Bound ) { setLocalAddress(); _Bound = true; } #ifdef NL_OS_WINDOWS // temporary by ace to know size of SO_MAX_MSG_SIZE static bool first = true; if (first) { uint MMS, SB; int size = sizeof (MMS); getsockopt (_Sock, SOL_SOCKET, SO_SNDBUF, (char *)&SB, &size); getsockopt (_Sock, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&MMS, &size); LNETL0_INFO ("LNETL0: The udp SO_MAX_MSG_SIZE=%u, SO_SNDBUF=%u", MMS, SB); first = false; } #endif }
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(); }
static int brl_construct (BrailleDisplay *brl, char **parameters, const char *device) { if (!allocateCommandDescriptors()) return 0; inputLength = 0; inputStart = 0; inputEnd = 0; outputLength = 0; if (isQualifiedDevice(&device, "client")) { static const ModeEntry clientModeEntry = { #ifdef AF_LOCAL requestLocalConnection, #endif /* AF_LOCAL */ #ifdef __MINGW32__ requestNamedPipeConnection, #endif /* __MINGW32__ */ requestInetConnection }; mode = &clientModeEntry; } else if (isQualifiedDevice(&device, "server")) { static const ModeEntry serverModeEntry = { #ifdef AF_LOCAL acceptLocalConnection, #endif /* AF_LOCAL */ #ifdef __MINGW32__ acceptNamedPipeConnection, #endif /* __MINGW32__ */ acceptInetConnection }; mode = &serverModeEntry; } else { unsupportedDevice(device); goto failed; } if (!*device) device = VR_DEFAULT_SOCKET; #ifdef AF_LOCAL if (device[0] == '/') { struct sockaddr_un address; if (setLocalAddress(device, &address)) { fileDescriptor = mode->getLocalConnection(&address); } } else #endif /* AF_LOCAL */ #ifdef __MINGW32__ if (device[0] == '\\') { fileDescriptor = mode->getNamedPipeConnection(device); } else { static WSADATA wsadata; if (WSAStartup(MAKEWORD(1, 1), &wsadata)) { logWindowsSystemError("socket library start"); goto failed; } } #endif /* __MINGW32__ */ { struct sockaddr_in address; if (setInetAddress(device, &address)) { fileDescriptor = mode->getInetConnection(&address); } } if (fileDescriptor != -1) { char *line = NULL; while (1) { if (line) free(line); if ((line = readCommandLine())) { const char *word; logMessage(LOG_DEBUG, "command received: %s", line); if ((word = strtok(line, inputDelimiters))) { if (testWord(word, "cells")) { if (dimensionsChanged(brl)) { free(line); return 1; } } else if (testWord(word, "quit")) { break; } else { logMessage(LOG_WARNING, "unexpected command: %s", word); } } } else { asyncWait(1000); } } if (line) free(line); close(fileDescriptor); fileDescriptor = -1; } failed: deallocateCommandDescriptors(); return 0; }
/** * Offer an Unix socket over this stream tube. * * This method offers an Unix socket over this stream tube. The socket address is given as a * a QString, which should contain the path to the socket. Abstract Unix sockets are also supported, * and are given as addresses prefixed with a \c NUL byte. * * If your application uses QLocalServer as the local Unix server implementation, you can use the * offerUnixSocket(const QLocalServer *, const QVariantMap &, bool) overload instead to more easily * pass the server's listen address. * * Note that only connection managers for which supportsUnixSocketsOnLocalhost() or * supportsAbstractUnixSocketsOnLocalhost() is \c true support exporting Unix sockets. * * If supportsUnixSocketsWithCredentials() or supportsAbstractUnixSocketsWithCredentials(), as * appropriate, returns \c true, the \c requireCredentials parameter can be set to \c true to make * the connection manager pass an SCM_CREDS or SCM_CREDENTIALS message as supported by the platform * when making a new connection. This enables preventing other local users from connecting to the * service, but might not be possible to use with all protocols as the message is in-band in the * data stream. * * Arbitrary parameters can be associated with the offer to bootstrap legacy protocols; these will * in particular be available as IncomingStreamTubeChannel::parameters() for a tube receiver * implemented using TelepathyQt in the other end. * * This method requires OutgoingStreamTubeChannel::FeatureCore to be ready. * * \param socketAddress A valid path to an existing Unix socket or abstract Unix socket. * \param parameters A dictionary of arbitrary parameters to send with the tube offer. * \param requireCredentials Whether the server requires a SCM_CREDS or SCM_CREDENTIALS message * upon connection. * \return A PendingOperation which will emit PendingOperation::finished * when the stream tube is ready to be used * (hence in the #TubeStateOpen state). */ PendingOperation *OutgoingStreamTubeChannel::offerUnixSocket( const QString &socketAddress, const QVariantMap ¶meters, bool requireCredentials) { SocketAccessControl accessControl = requireCredentials ? SocketAccessControlCredentials : SocketAccessControlLocalhost; if (!isReady(OutgoingStreamTubeChannel::FeatureCore)) { warning() << "OutgoingStreamTubeChannel::FeatureCore must be ready before " "calling offerTube"; return new PendingFailure(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Channel not ready"), OutgoingStreamTubeChannelPtr(this)); } // The tube must be not offered if (state() != TubeChannelStateNotOffered) { warning() << "You can not expose more than a socket for each Stream Tube"; return new PendingFailure(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Channel busy"), OutgoingStreamTubeChannelPtr(this)); } // In this specific overload, we're handling an Unix/AbstractUnix socket if (socketAddress.startsWith(QLatin1Char('\0'))) { // Abstract Unix socket case // Check if the combination type/access control is supported if ((accessControl == SocketAccessControlLocalhost && !supportsAbstractUnixSocketsOnLocalhost()) || (accessControl == SocketAccessControlCredentials && !supportsAbstractUnixSocketsWithCredentials()) ) { warning() << "You requested an address type/access control combination " "not supported by this channel"; return new PendingFailure(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("The requested address type/access control " "combination is not supported"), OutgoingStreamTubeChannelPtr(this)); } setAddressType(SocketAddressTypeAbstractUnix); setAccessControl(accessControl); setLocalAddress(socketAddress); PendingVoid *pv = new PendingVoid( interface<Client::ChannelTypeStreamTubeInterface>()->Offer( SocketAddressTypeAbstractUnix, QDBusVariant(QVariant(socketAddress.toLatin1())), accessControl, parameters), OutgoingStreamTubeChannelPtr(this)); PendingOpenTube *op = new PendingOpenTube(pv, parameters, OutgoingStreamTubeChannelPtr(this)); return op; } else { // Unix socket case // Check if the combination type/access control is supported if ((accessControl == SocketAccessControlLocalhost && !supportsUnixSocketsOnLocalhost()) || (accessControl == SocketAccessControlCredentials && !supportsUnixSocketsWithCredentials()) || (accessControl != SocketAccessControlLocalhost && accessControl != SocketAccessControlCredentials) ) { warning() << "You requested an address type/access control combination " "not supported by this channel"; return new PendingFailure(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("The requested address type/access control " "combination is not supported"), OutgoingStreamTubeChannelPtr(this)); } setAddressType(SocketAddressTypeUnix); setAccessControl(accessControl); setLocalAddress(socketAddress); PendingVoid *pv = new PendingVoid( interface<Client::ChannelTypeStreamTubeInterface>()->Offer( SocketAddressTypeUnix, QDBusVariant(QVariant(socketAddress.toLatin1())), accessControl, parameters), OutgoingStreamTubeChannelPtr(this)); PendingOpenTube *op = new PendingOpenTube(pv, parameters, OutgoingStreamTubeChannelPtr(this)); return op; } }
void DhQAbstractSocket::DvhsetLocalAddress(const QHostAddress& x1) { return setLocalAddress(x1); }
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(); }