int connectForGet(const char *ipaddr) { int servfd; struct sockaddr_in servaddr; #ifdef OS_WIN WSADATA wsadata; WSAStartup(MAKEWORD(2,2), &wsadata); #endif servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORTNO); memset(&servaddr.sin_zero, '\0', 8); servaddr.sin_addr.s_addr = inet_addr(ipaddr); bumerang_info("Trying to connection"); if ((servfd = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR) connectError("socket"); if (connect(servfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == SOCKET_ERROR) connectError("connect"); bumerang_info("Connection successfull"); bumerang_info("Waiting the file"); return servfd; }
int connectForSend(void) { int servfd; int clientfd; int yes = 1; struct sockaddr_in servaddr, clientaddr; char ipaddr[100]; #ifdef OS_WIN WSADATA wsadata; int addr_len; WSAStartup(MAKEWORD(2,2), &wsadata); #else socklen_t addr_len; #endif bumerang_info("Trying to connection"); #ifdef OS_WIN getIpAddressForNT(ipaddr); #else getIpAddressForPosix(ipaddr); #endif servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORTNO); memset(&servaddr.sin_zero, '\0', 8); servaddr.sin_addr.s_addr = inet_addr(ipaddr); if ((servfd = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR) connectError("socket"); if (setsockopt(servfd, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof (int)) == SOCKET_ERROR) connectError("setsockopt"); if (bind(servfd, (struct sockaddr *) &servaddr, sizeof (servaddr)) == SOCKET_ERROR) connectError("bind"); if (listen(servfd, BACKLOG) == SOCKET_ERROR) connectError("listen"); bumerang_info("Connection successfull"); bumerang_info("Waiting the client"); addr_len = sizeof (clientaddr); if ((clientfd = accept(servfd, (struct sockaddr *) &clientaddr, &addr_len)) == SOCKET_ERROR) connectError("accept"); return clientfd; }
void TCPStream::connect(const char *target, unsigned mss) { char namebuf[128]; char *cp; struct servent *svc; tpport_t port; snprintf(namebuf, sizeof(namebuf), "%s", target); cp = strrchr(namebuf, '/'); if(!cp) cp = strrchr(namebuf, ':'); if(!cp) { endStream(); connectError(); return; } *(cp++) = 0; if(isdigit(*cp)) port = atoi(cp); else { mutex.enter(); svc = getservbyname(cp, "tcp"); if(svc) port = ntohs(svc->s_port); mutex.leave(); if(!svc) { endStream(); connectError(); return; } } switch(family) { case IPV4: connect(IPV4Host(namebuf), port, mss); break; #ifdef CCXX_IPV6 case IPV6: connect(IPV6Host(namebuf), port, mss); break; #endif default: endStream(); connectError(); } }
Socket::Error SocketPort::connect(const IPV4Address &ia, tpport_t port) { struct sockaddr_in addr; Error rtn = errSuccess; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr = getaddress(ia); addr.sin_port = htons(port); #ifndef WIN32 long opts = fcntl(so, F_GETFL); fcntl(so, F_SETFL, opts | O_NDELAY); #else u_long opts = 1; ioctlsocket(so,FIONBIO,&opts); #endif // Win32 will crash if you try to connect to INADDR_ANY. if ( INADDR_ANY == addr.sin_addr.s_addr ) addr.sin_addr.s_addr = INADDR_LOOPBACK; if(::connect(so, (struct sockaddr *)&addr, (socklen_t)sizeof(addr))) rtn = connectError(); #ifndef WIN32 fcntl(so, F_SETFL, opts); #else opts = 0; ioctlsocket(so,FIONBIO,&opts); #endif return rtn; }
//I'm the existing device, a new device is kindly introducing itself. //I will create a TcpSocket and try to connect. This can result in either connected() or connectError(). void LanLinkProvider::newUdpConnection() { while (mUdpServer->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(mUdpServer->pendingDatagramSize()); QHostAddress sender; mUdpServer->readDatagram(datagram.data(), datagram.size(), &sender); NetworkPackage* receivedPackage = new NetworkPackage(""); bool success = NetworkPackage::unserialize(datagram, receivedPackage); if (!success || receivedPackage->type() != PACKAGE_TYPE_IDENTITY) { delete receivedPackage; continue; } if (receivedPackage->get<QString>("deviceId") == KdeConnectConfig::instance()->deviceId()) { //qCDebug(KDECONNECT_CORE) << "Ignoring my own broadcast"; delete receivedPackage; continue; } int tcpPort = receivedPackage->get<int>("tcpPort", port); //qCDebug(KDECONNECT_CORE) << "Received Udp identity package from" << sender << " asking for a tcp connection on port " << tcpPort; QTcpSocket* socket = new QTcpSocket(this); receivedIdentityPackages[socket].np = receivedPackage; receivedIdentityPackages[socket].sender = sender; connect(socket, SIGNAL(connected()), this, SLOT(connected())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectError())); socket->connectToHost(sender, tcpPort); } }
void TcpThread::run() { /** * 内存泄漏检查 */ //_CrtDumpMemoryLeaks(); // TotalBytes = 0; bytesReceived = 0; fileNameSize = 0; blockSize = 0; loadSize = 4*1024; bytesToWrite = 0; bytesWritten = 0; blFileOpen = false; blerror = false; upload_AND_download_Path = "G:\\TEEData\\"; m_searchPath = "G:\\TEEData_Build\\"; tcpServerConnection = new QTcpSocket; if (!tcpServerConnection->setSocketDescriptor(socketDescriptor)) { emit error(tcpServerConnection->error()); return; } connect(tcpServerConnection, SIGNAL(readyRead()), this, SLOT(receiveData()),Qt::DirectConnection); connect(tcpServerConnection, SIGNAL(error(QAbstractSocket::SocketError)), this,SLOT(displayError(QAbstractSocket::SocketError)), Qt::DirectConnection); connect(tcpServerConnection, SIGNAL(connectionClosed()), this, SLOT(connectError()), Qt::DirectConnection); exec(); }
//We received a UDP package and answered by connecting to them by TCP. This gets called on a succesful connection. void LanLinkProvider::connected() { qCDebug(KDECONNECT_CORE) << "Socket connected"; QSslSocket* socket = qobject_cast<QSslSocket*>(sender()); if (!socket) return; disconnect(socket, &QAbstractSocket::connected, this, &LanLinkProvider::connected); disconnect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectError())); configureSocket(socket); // If socket disconnects due to any reason after connection, link on ssl faliure connect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater); NetworkPackage* receivedPackage = receivedIdentityPackages[socket].np; const QString& deviceId = receivedPackage->get<QString>(QStringLiteral("deviceId")); //qCDebug(KDECONNECT_CORE) << "Connected" << socket->isWritable(); // If network is on ssl, do not believe when they are connected, believe when handshake is completed NetworkPackage np2(QLatin1String("")); NetworkPackage::createIdentityPackage(&np2); socket->write(np2.serialize()); bool success = socket->waitForBytesWritten(); if (success) { qCDebug(KDECONNECT_CORE) << "TCP connection done (i'm the existing device)"; // if ssl supported if (receivedPackage->get<int>(QStringLiteral("protocolVersion")) >= MIN_VERSION_WITH_SSL_SUPPORT) { bool isDeviceTrusted = KdeConnectConfig::instance()->trustedDevices().contains(deviceId); configureSslSocket(socket, deviceId, isDeviceTrusted); qCDebug(KDECONNECT_CORE) << "Starting server ssl (I'm the client TCP socket)"; connect(socket, &QSslSocket::encrypted, this, &LanLinkProvider::encrypted); if (isDeviceTrusted) { connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrors(QList<QSslError>))); } socket->startServerEncryption(); return; // Return statement prevents from deleting received package, needed in slot "encrypted" } else { qWarning() << receivedPackage->get<QString>(QStringLiteral("deviceName")) << "uses an old protocol version, this won't work"; //addLink(deviceId, socket, receivedPackage, LanDeviceLink::Remotely); } } else { //I think this will never happen, but if it happens the deviceLink //(or the socket that is now inside it) might not be valid. Delete them. qCDebug(KDECONNECT_CORE) << "Fallback (2), try reverse connection (send udp packet)"; mUdpSocket.writeDatagram(np2.serialize(), receivedIdentityPackages[socket].sender, PORT); } delete receivedIdentityPackages.take(socket).np; //We don't delete the socket because now it's owned by the LanDeviceLink }
Socket::Error SocketPort::connect(const IPV6Address &ia, tpport_t port) { struct sockaddr_in6 addr; Error rtn = errSuccess; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr = getaddress(ia); addr.sin6_port = htons(port); #ifndef WIN32 long opts = fcntl(so, F_GETFL); fcntl(so, F_SETFL, opts | O_NDELAY); #else u_long opts = 1; ioctlsocket(so,FIONBIO,&opts); #endif // Win32 will crash if you try to connect to INADDR_ANY. if(!memcmp(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any))) memcpy(&addr.sin6_addr, &in6addr_loopback, sizeof(in6addr_loopback)); if(::connect(so, (struct sockaddr *)&addr, (socklen_t)sizeof(addr))) rtn = connectError(); #ifndef WIN32 fcntl(so, F_SETFL, opts); #else opts = 0; ioctlsocket(so,FIONBIO,&opts); #endif return rtn; }
Socket::Error UDPTransmit::connect(const ucommon::Socket::address &host) { peer = host; if(peer.isAny()) peer.setLoopback(); if(::connect(so, peer, peer.getLength())) return connectError(); return errSuccess; }
void NonNativeIrcEngine::connectToHost(QString host, int port) { sock->connectToHost(host, port); if (!sock->waitForConnected(10000)) { QMessageBox::critical(NULL, "Erreur de connexion", "Impossible de se connecter."); emit connectError(); } else connected = true; }
void MeeTv::_initHtsp() { m_htsp = MeeTvHtsp::instance(); m_dvrEntriesModel = new MeeTvDvrEntryModel(m_htsp->dvrEntries()); m_eventModel = new MeeTvEventModel(m_htsp->events()); m_tagModel = new MeeTvTagModel(m_htsp->tags()); connect(&m_idleTimer, SIGNAL(timeout()), m_htsp, SLOT(disconnectIdle())); connect(m_htsp, SIGNAL(connectError()), this, SLOT(_connectError())); }
Socket::Error UDPReceive::connect(const ucommon::Socket::address &ia) { ucommon::Socket::address host = ia; setPeer(host); // Win32 will crash if you try to connect to INADDR_ANY. if(host.isAny()) host.setLoopback(); if(::connect(so, host, host.getLength())) return connectError(); return errSuccess; }
Socket::Error UDPReceive::connect(const IPV6Host &ia, tpport_t port) { int len = sizeof(peer.ipv6); peer.ipv6.sin6_family = AF_INET6; peer.ipv6.sin6_addr = getaddress(ia); peer.ipv6.sin6_port = htons(port); // Win32 will crash if you try to connect to INADDR_ANY. if(!memcmp(&peer.ipv6.sin6_addr, &in6addr_any, sizeof(in6addr_any))) memcpy(&peer.ipv6.sin6_addr, &in6addr_loopback, sizeof(in6addr_loopback)); if(::connect(so, (sockaddr *)&peer.ipv6, len)) return connectError(); return errSuccess; }
Socket::Error UDPTransmit::cConnect(const IPV4Address &ia, tpport_t port) { int len = sizeof(peer.ipv4); peer.ipv4.sin_family = AF_INET; peer.ipv4.sin_addr = getaddress(ia); peer.ipv4.sin_port = htons(port); // Win32 will crash if you try to connect to INADDR_ANY. if ( INADDR_ANY == peer.ipv4.sin_addr.s_addr ) peer.ipv4.sin_addr.s_addr = INADDR_LOOPBACK; if(::connect(so, (sockaddr *)&peer.ipv4, len)) return connectError(); return errSuccess; }
int Client::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QThread::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: dataReceived((*reinterpret_cast< QString(*)>(_a[1]))); break; case 1: connectError(); break; default: ; } _id -= 2; } return _id; }
void ClientThread::run() { memset(&client, 0, sizeof(struct sockaddr)); client.sin_family = AF_INET; client.sin_addr.s_addr = INADDR_ANY; client.sin_port = 0; sock = socket(PF_INET, SOCK_DGRAM, 0); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if(gethostbyname_r(addr.toStdString().c_str(), &he, buf, sizeof(buf), &ip_addr, &status) || !ip_addr || sock < 0 || bind(sock, (struct sockaddr*)&client, sizeof(struct sockaddr)) < 0) { emit connectError(); ::close(sock); } else { memset(&server, 0, sizeof(struct sockaddr)); memcpy(&server.sin_addr.s_addr, ip_addr->h_addr, ip_addr->h_length); server.sin_family = AF_INET; server.sin_port = htons(port.toInt()); sendto(sock, "new0"+name.toUtf8(), name.toUtf8().length()+4, 0, (struct sockaddr*)&server, sizeof(struct sockaddr)); buf_size = recvfrom(sock, buf, 2048, 0, (struct sockaddr*)&server, &size); id = QString::fromUtf8(buf, buf_size); emit connectSuccess(id); while (true) { buf_size = recvfrom(sock, buf, 2048, 0, (struct sockaddr*)&consultant, &size); if(QString::fromUtf8(buf, 4) == "exit") { talk = false; emit newSysMessage("Rozmowa została zakończona."); sendto(sock, "exit"+id.toUtf8(), id.toUtf8().length()+4, 0, (struct sockaddr*)&server, sizeof(struct sockaddr)); emit exitTalk(); break; } else if(!talk && QString::fromUtf8(buf, 3) == "con") { talk = true; emit newSysMessage("Właśnie połączył się z Tobą konsultant "+QString::fromUtf8(buf, buf_size).mid(3,buf_size-3)+"."); emit startTalk(); } else if(talk && QString::fromUtf8(buf, 1) == ";") { emit newMessage(QString::fromUtf8(buf, buf_size).mid(1,buf_size-1)); } } } }
SocketPort::SocketPort(SocketService *svc, const IPV6Host &ih, tpport_t port) : Socket(AF_INET6, SOCK_STREAM, 0) { struct sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); next = prev = NULL; service = NULL; addr.sin6_family = AF_INET6; addr.sin6_addr = getaddress(ih); addr.sin6_port = htons(port); detect_pending = true; detect_disconnect = true; long opts = fcntl(so, F_GETFL); fcntl(so, F_SETFL, opts | O_NDELAY); int rtn = ::connect(so, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)); if(!rtn) { state = CONNECTED; } else { if(errno == EINPROGRESS) { state = CONNECTING; } else { endSocket(); connectError(); return; } } fcntl(so, F_SETFL, opts); setError(false); detect_output = (state == CONNECTING); if(svc) svc->attach(this); // if(state == CONNECTING) // setDetectOutput(true); }
void LanLinkProvider::connectError() { QSslSocket* socket = qobject_cast<QSslSocket*>(sender()); if (!socket) return; disconnect(socket, SIGNAL(connected()), this, SLOT(connected())); disconnect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectError())); qCDebug(KDECONNECT_CORE) << "Fallback (1), try reverse connection (send udp packet)" << socket->errorString(); NetworkPackage np(""); NetworkPackage::createIdentityPackage(&np); np.set("tcpPort", mTcpPort); mUdpSocket.writeDatagram(np.serialize(), receivedIdentityPackages[socket].sender, port); //The socket we created didn't work, and we didn't manage //to create a LanDeviceLink from it, deleting everything. delete receivedIdentityPackages.take(socket).np; delete socket; }
//I'm the existing device, a new device is kindly introducing itself. //I will create a TcpSocket and try to connect. This can result in either connected() or connectError(). void LanLinkProvider::newUdpConnection() //udpBroadcastReceived { while (mUdpSocket.hasPendingDatagrams()) { QByteArray datagram; datagram.resize(mUdpSocket.pendingDatagramSize()); QHostAddress sender; mUdpSocket.readDatagram(datagram.data(), datagram.size(), &sender); if (sender.isLoopback() && !mTestMode) continue; NetworkPackage* receivedPackage = new NetworkPackage(QLatin1String("")); bool success = NetworkPackage::unserialize(datagram, receivedPackage); //qCDebug(KDECONNECT_CORE) << "udp connection from " << receivedPackage->; //qCDebug(KDECONNECT_CORE) << "Datagram " << datagram.data() ; if (!success || receivedPackage->type() != PACKAGE_TYPE_IDENTITY) { delete receivedPackage; continue; } if (receivedPackage->get<QString>(QStringLiteral("deviceId")) == KdeConnectConfig::instance()->deviceId()) { //qCDebug(KDECONNECT_CORE) << "Ignoring my own broadcast"; delete receivedPackage; continue; } int tcpPort = receivedPackage->get<int>(QStringLiteral("tcpPort"), PORT); //qCDebug(KDECONNECT_CORE) << "Received Udp identity package from" << sender << " asking for a tcp connection on port " << tcpPort; QSslSocket* socket = new QSslSocket(this); receivedIdentityPackages[socket].np = receivedPackage; receivedIdentityPackages[socket].sender = sender; connect(socket, &QAbstractSocket::connected, this, &LanLinkProvider::connected); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectError())); socket->connectToHost(sender, tcpPort); } }
Socket::Error SocketPort::connect(const IPV6Address &ia, tpport_t port) { struct sockaddr_in6 addr; Error rtn = errSuccess; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr = getaddress(ia); addr.sin6_port = htons(port); long opts = fcntl(so, F_GETFL); fcntl(so, F_SETFL, opts | O_NDELAY); if(!memcmp(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any))) memcpy(&addr.sin6_addr, &in6addr_loopback, sizeof(in6addr_loopback)); if(::connect(so, (struct sockaddr *)&addr, (socklen_t)sizeof(addr))) rtn = connectError(); fcntl(so, F_SETFL, opts); return rtn; }
void LanLinkProvider::connected() { QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender()); if (!socket) return; disconnect(socket, SIGNAL(connected()), this, SLOT(connected())); disconnect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectError())); configureSocket(socket); NetworkPackage* receivedPackage = receivedIdentityPackages[socket].np; const QString& deviceId = receivedPackage->get<QString>("deviceId"); //qCDebug(KDECONNECT_CORE) << "Connected" << socket->isWritable(); LanDeviceLink* deviceLink = new LanDeviceLink(deviceId, this, socket); NetworkPackage np2(""); NetworkPackage::createIdentityPackage(&np2); bool success = deviceLink->sendPackage(np2); if (success) { //qCDebug(KDECONNECT_CORE) << "Handshaking done (i'm the existing device)"; connect(deviceLink, SIGNAL(destroyed(QObject*)), this, SLOT(deviceLinkDestroyed(QObject*))); Q_EMIT onConnectionReceived(*receivedPackage, deviceLink); //We kill any possible link from this same device QMap< QString, DeviceLink* >::iterator oldLinkIterator = mLinks.find(deviceId); if (oldLinkIterator != mLinks.end()) { DeviceLink* oldLink = oldLinkIterator.value(); disconnect(oldLink, SIGNAL(destroyed(QObject*)), this, SLOT(deviceLinkDestroyed(QObject*))); oldLink->deleteLater(); mLinks.erase(oldLinkIterator); } mLinks[deviceId] = deviceLink; } else {
Socket::Error UDPSocket::disconnect(void) { struct sockaddr_in addr; int len = sizeof(addr); if(so == INVALID_SOCKET) return errSuccess; Socket::state = BOUND; memset(&addr, 0, len); #ifndef _MSWINDOWS_ addr.sin_family = AF_UNSPEC; #else addr.sin_family = AF_INET; memset(&addr.sin_addr, 0, sizeof(addr.sin_addr)); #endif if(::connect(so, (sockaddr *)&addr, len)) return connectError(); return errSuccess; }
/*! * \fn int main(int argc, char **argv) * Fonction principale * \return Le code de fin d'execution de la main loop. */ int main (int argc,char **argv) { QApplication app(argc,argv); MainWindow *fen = new MainWindow(NULL); IIrcEngine *engine = NonNativeIrcEngine::engine(); QObject::connect(fen, SIGNAL(connectMe(const QString&, int, const QString&)), engine, SLOT(initiateConnection(const QString&, int, const QString&))); QObject::connect(engine, SIGNAL(lineReceived(QString)), fen, SLOT(readServer(QString))); QObject::connect(fen, SIGNAL(sendASCIIMessage(const QString&)), engine, SLOT(sendASCIIMessage(const QString&))); /* La QMainWindow */ MainWindowView *mW = new MainWindowView(fen,NULL); mW->show(); XmlConfManager *confMan = XmlConfManager::confManager(); /*confMan->addServer("test"); confMan->addNetwork("test", confMan->createNetwork("irc.fansub-irc.eu", "6667")); confMan->changeUser("test", confMan->createUser("pierre", "pierreghost", "user", "real")); confMan->changeFavChan("test", "#fsf,#Kyubi-Wolf"); confMan->changeCommand("test", "/ns identify albachat"); confMan->save();*/ confMan->read(); ServerList *serverList = new ServerList(); QObject::connect(serverList, SIGNAL(connectSignal(QString&, int, QString&)), fen, SLOT(connexion(QString&, int, QString&))); QObject::connect(engine, SIGNAL(connectError()), serverList, SLOT(reconnect())); serverList->show(); return app.exec(); }
SocketPort::SocketPort(SocketService *svc, const IPV6Host &ih, tpport_t port) : Socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP) { #ifdef WIN32 // FIXME: error handling event = CreateEvent(NULL,TRUE,FALSE,NULL); #endif struct sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); next = prev = NULL; service = NULL; addr.sin6_family = AF_INET6; addr.sin6_addr = getaddress(ih); addr.sin6_port = htons(port); detect_pending = true; detect_disconnect = true; #ifndef WIN32 long opts = fcntl(so, F_GETFL); fcntl(so, F_SETFL, opts | O_NDELAY); #else u_long opts = 1; ioctlsocket(so,FIONBIO,&opts); #endif int rtn = ::connect(so, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)); if(!rtn) { state = CONNECTED; } else { #ifndef WIN32 if(errno == EINPROGRESS) #else if(WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK) #endif { state = CONNECTING; } else { endSocket(); connectError(); return; } } #ifndef WIN32 fcntl(so, F_SETFL, opts); #else opts = 0; ioctlsocket(so,FIONBIO,&opts); #endif setError(false); detect_output = (state == CONNECTING); if(svc) svc->attach(this); // if(state == CONNECTING) // setDetectOutput(true); }
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); } #endif TCPStream::~TCPStream() { #ifdef CCXX_EXCEPTIONS try { endStream(); } catch( ... ) { if ( ! std::uncaught_exception()) throw;}; #else endStream(); #endif } #ifdef HAVE_GETADDRINFO void TCPStream::connect(const char *target, unsigned mss) { char namebuf[128]; char *cp; struct addrinfo hint, *list = NULL, *next, *first; bool connected = false; snprintf(namebuf, sizeof(namebuf), "%s", target); cp = strrchr(namebuf, '/'); if(!cp) cp = strrchr(namebuf, ':'); if(!cp) { endStream(); connectError(); return; } *(cp++) = 0; memset(&hint, 0, sizeof(hint)); hint.ai_family = family; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = IPPROTO_TCP; if(getaddrinfo(namebuf, cp, &hint, &list) || !list) { endStream(); connectError(); return; } first = list; #ifdef TCP_MAXSEG if(mss) setsockopt(so, IPPROTO_TCP, TCP_MAXSEG, (char *)&mss, sizeof(mss)); #endif while(list) { if(!::connect(so, list->ai_addr, (socklen_t)list->ai_addrlen)) { connected = true; break; } next = list->ai_next; list = next; } freeaddrinfo(first); if(!connected) { endStream(); connectError(); return; } segmentBuffering(mss); Socket::state = CONNECTED; }
void TCPStream::connect(const IPV6Host &host, tpport_t port, unsigned mss) { size_t i; fd_set fds; struct timeval to; bool connected = false; int rtn; int sockopt; socklen_t len = sizeof(sockopt); #ifdef TCP_MAXSEG if(mss) setsockopt(so, IPPROTO_TCP, TCP_MAXSEG, (char *)&mss, sizeof(mss)); #endif for(i = 0 ; i < host.getAddressCount(); i++) { struct sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr = host.getAddress(i); addr.sin6_port = htons(port); if(timeout) setCompletion(false); // Win32 will crash if you try to connect to INADDR_ANY. if ( !memcmp(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any))) memcpy(&addr.sin6_addr, &in6addr_loopback, sizeof(in6addr_loopback)); rtn = ::connect(so, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)); if(!rtn) { connected = true; break; } #ifndef _MSWINDOWS_ if(errno == EINPROGRESS) #else if(WSAGetLastError() == WSAEINPROGRESS) #endif { FD_ZERO(&fds); FD_SET(so, &fds); to.tv_sec = timeout / 1000; to.tv_usec = timeout % 1000 * 1000; // timeout check for connect completion if(::select((int)so + 1, NULL, &fds, NULL, &to) < 1) continue; getsockopt(so, SOL_SOCKET, SO_ERROR, (char *)&sockopt, &len); if(!sockopt) { connected = true; break; } endSocket(); so = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); if(so == INVALID_SOCKET) break; } } setCompletion(true); if(!connected) { rtn = errno; endStream(); errno = rtn; connectError(); return; } segmentBuffering(mss); Socket::state = CONNECTED; }
void closeConnect(int socket) { shutdown(socket, 2); if (close(socket) == SOCKET_ERROR) connectError("close"); }
void LanLinkProvider::connected() { qCDebug(KDECONNECT_CORE) << "Socket connected"; QSslSocket* socket = qobject_cast<QSslSocket*>(sender()); if (!socket) return; disconnect(socket, SIGNAL(connected()), this, SLOT(connected())); disconnect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectError())); configureSocket(socket); // If socket disconnects due to any reason after connection, link on ssl faliure connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater())); NetworkPackage* receivedPackage = receivedIdentityPackages[socket].np; const QString& deviceId = receivedPackage->get<QString>("deviceId"); //qCDebug(KDECONNECT_CORE) << "Connected" << socket->isWritable(); // If network is on ssl, do not believe when they are connected, believe when handshake is completed NetworkPackage np2(""); NetworkPackage::createIdentityPackage(&np2); socket->write(np2.serialize()); bool success = socket->waitForBytesWritten(); if (success) { qCDebug(KDECONNECT_CORE) << "Handshaking done (i'm the existing device)"; // if ssl supported if (receivedPackage->get<int>("protocolVersion") >= NetworkPackage::ProtocolVersion) { // since I support ssl and remote device support ssl socket->setPeerVerifyName(deviceId); QString certString = KdeConnectConfig::instance()->getDeviceProperty(deviceId, "certificate", QString()); if (!certString.isEmpty()) { qCDebug(KDECONNECT_CORE) << "Device trusted"; socket->addCaCertificate(QSslCertificate(certString.toLatin1())); socket->setPeerVerifyMode(QSslSocket::VerifyPeer); connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrors(QList<QSslError>))); } else { qCDebug(KDECONNECT_CORE) << "Device untrusted"; // Do not care about ssl errors here, socket will not be closed due to errors because of query peer socket->setPeerVerifyMode(QSslSocket::QueryPeer); connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsLogButIgnore(QList<QSslError>))); } qCDebug(KDECONNECT_CORE) << "Starting server ssl (I'm the client TCP socket)"; connect(socket, SIGNAL(encrypted()), this, SLOT(encrypted())); socket->startServerEncryption(); return; // Return statement prevents from deleting received package, needed in slot "encrypted" } else { qWarning() << "Incompatible protocol version, this won't work"; //addLink(deviceId, socket, receivedPackage, LanDeviceLink::Remotely); } } else { //I think this will never happen, but if it happens the deviceLink //(or the socket that is now inside it) might not be valid. Delete them. qCDebug(KDECONNECT_CORE) << "Fallback (2), try reverse connection (send udp packet)"; mUdpSocket.writeDatagram(np2.serialize(), receivedIdentityPackages[socket].sender, port); } delete receivedIdentityPackages.take(socket).np; //We don't delete the socket because now it's owned by the LanDeviceLink }
void MainWindow::initConnection() { // Show connecting dialog mConnectingDialog->show(); // Connection QNetworkConfigurationManager manager; const bool canStartIAP = (manager.capabilities() & QNetworkConfigurationManager::CanStartAndStopInterfaces); QNetworkConfiguration cfg = manager.defaultConfiguration(); if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) return; mNetworkSession = new QNetworkSession(cfg, this); connect(mNetworkSession, SIGNAL(opened()), this, SLOT(connectOpened())); connect(mNetworkSession, SIGNAL(error(QNetworkSession::SessionError)), this, SLOT(connectError(QNetworkSession::SessionError))); mNetworkSession->open(); }