kextsock.cpp

来自「konqueror3 embedded版本, KDE环境下的当家浏览器的嵌入式版」· C++ 代码 · 共 2,230 行 · 第 1/4 页

CPP
2,230 行
字号
		}	      else if (len == 0)		{		  // EOF condition here		  ::close(sockfd);		  sockfd = -1;	// we're closed		  d->qsnIn->deleteLater();		  delete d->qsnOut;		  d->qsnIn = d->qsnOut = NULL;		  d->status = done;		  emit closed(involuntary |			      (readBufferSize() ? availRead : 0) |			      (writeBufferSize() ? dirtyWrite : 0));		  return;		}	      else		{		  // error!		  setError(IO_ReadError, errno);		  return;		}	      // will loop only for normal read operations	    }	  while (len == sizeof(buf));	  feedReadBuffer(a.size(), a.data());	}      // UNLOCK MUTEX    }  else    {      // No input buffering, but the notifier fired      // That means that either there is data to be read or that the       // socket closed.      // try to read one byte. If we can't, then the socket got closed      char c;      int len = KSocks::self()->recv(sockfd, &c, sizeof(c), MSG_PEEK);      if (len == 0)	{	  // yes, it's an EOF condition	  d->qsnIn->setEnabled(false);	  ::close(sockfd);	  sockfd = -1;	  d->status = done;	  emit closed(involuntary);	  return;	}    }  if (d->emitRead)    emit readyRead();}void KExtendedSocket::socketActivityWrite(){  if (d->flags & passiveSocket)    return;  if (d->status == connecting)    {      connectionEvent();      return;    }  if (d->status != connected && d->status != closing)    return;  flush();  bool empty = writeBufferSize() == 0;  if (d->emitWrite && empty)    emit readyWrite();  else if (!d->emitWrite)    {      // check if we can disable the notifier      d->qsnOut->setEnabled(!empty); // leave it enabled only if we have more data to send    }  if (d->status == closing && empty)    {      // done sending the missing data!      d->status = done;      delete d->qsnOut;      ::close(sockfd);      d->qsnOut = NULL;      sockfd = -1;      emit closed(delayed | (readBufferSize() ? availRead : 0));    }}// this function is called whenever we have a "connection event"// that is, whenever our asynchronously connecting socket throws// an eventvoid KExtendedSocket::connectionEvent(){  if (d->status != connecting)    return;			// move along. There's nothing to see here  KResolverResults remote = d->resRemote.results();  if (remote.count() == 0)    {      // We have a problem! Abort?      kdError(170) << "KExtendedSocket::connectionEvent() called but no data available!\n";      return;    }  int errcode = 0;  if (sockfd != -1)    {      // our socket has activity      // find out what it was      int retval;      socklen_t len = sizeof(errcode);      retval = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char*)&errcode, &len);      if (retval == -1 || errcode != 0)	{	  // socket activity and there was error?	  // that means the socket probably did not connect	  if (d->qsnIn)	    delete d->qsnIn;	  if (d->qsnOut)	    delete d->qsnOut;	  ::close(sockfd);	  sockfd = -1;	  d->qsnIn = d->qsnOut = NULL;	  d->current++;	  setError(IO_ConnectError, errcode);	}      else	{	  // hmm, socket activity and there was no error?	  // that means it connected	  // YAY!	  cleanError();	  d->status = connected;	  setBlockingMode(true);	  setFlags(IO_Sequential | IO_Raw | IO_ReadWrite | IO_Open | IO_Async);	  setBufferSize(d->flags & inputBufferedSocket ? -1 : 0,			d->flags & outputBufferedSocket ? -1 : 0);	  emit connectionSuccess();	  return;	}    }  // ok, we have to try something here  // and sockfd == -1  KResolverResults local = d->resLocal.results();  unsigned localidx = 0;  for ( ; d->current < remote.count(); d->current++)    {      // same code as in connect()      if (local.count() != 0)	{	  // scan bindres for a local resuls family	  for (localidx = 0; localidx < local.count(); localidx++)	    if (remote[d->current].family() == local[localidx].family())	      break;	  if (remote[d->current].family() != local[localidx].family())	    {	      // no matching families for this	      continue;	    }	  errno = 0;	  sockfd = ::socket(remote[d->current].family(), remote[d->current].socketType(),			    remote[d->current].protocol());	  setError(IO_ConnectError, errno);	  errcode = errno;	  if (sockfd == -1)	    continue;		// cannot create this socket          fcntl(sockfd, F_SETFD, FD_CLOEXEC);	  if (d->addressReusable)	    setAddressReusable(sockfd, true);	  setIPv6Only(d->ipv6only);	  cleanError();	  if (KSocks::self()->bind(sockfd, local[localidx].address(), 				   local[localidx].length()) == -1)	    {	      ::close(sockfd);	      sockfd = -1;	      continue;	    }	}      else	{	  // no need to bind, just create	  sockfd = ::socket(remote[d->current].family(), remote[d->current].socketType(),			    remote[d->current].protocol());	  if (sockfd == -1)	    {	      setError(IO_ConnectError, errno);	      errcode = errno;	      continue;	    }          fcntl(sockfd, F_SETFD, FD_CLOEXEC);	  if (d->addressReusable)	    setAddressReusable(sockfd, true);	  setIPv6Only(d->ipv6only);	  cleanError();	}      if (KSocks::self()->hasWorkingAsyncConnect())        setBlockingMode(false);      if (KSocks::self()->connect(sockfd, remote[d->current].address(), 				  remote[d->current].length()) == -1)	{	  if (errno != EWOULDBLOCK && errno != EINPROGRESS)	    {	      setError(IO_ConnectError, errno);	      ::close(sockfd);	      sockfd = -1;	      errcode = errno;	      continue;	    }	  // error here is either EWOULDBLOCK or EINPROGRESS	  // so, it is a good condition	  d->qsnIn = new QSocketNotifier(sockfd, QSocketNotifier::Read);	  QObject::connect(d->qsnIn, SIGNAL(activated(int)), this, SLOT(socketActivityRead()));	  d->qsnOut = new QSocketNotifier(sockfd, QSocketNotifier::Write);	  QObject::connect(d->qsnOut, SIGNAL(activated(int)), this, SLOT(socketActivityWrite()));	  // ok, let the Qt event loop do the selecting for us	  return;	}      // eh, what?      // the non-blocking socket returned valid connection?      // already?      // I suppose that could happen...      cleanError();      d->status = connected;      setBlockingMode(true);      setFlags(IO_Sequential | IO_Raw | IO_ReadWrite | IO_Open | IO_Async);      setBufferSize(d->flags & inputBufferedSocket ? -1 : 0,		    d->flags & outputBufferedSocket ? -1 : 0);      emit connectionSuccess();      return;    }  // if we got here, it means that there are no more options to connect  d->status = lookupDone;	// go back  emit connectionFailed(errcode);}void KExtendedSocket::dnsResultsReady(){  // check that this function was called in a valid state  if (d->status != lookupInProgress)    return;  // valid state. Are results fully ready?  if (d->resRemote.isRunning() || d->resLocal.isRunning())    // no, still waiting for answer in one of the lookups    return;  // ok, we have all results  // count how many results we have  int n = d->resRemote.results().count() + d->resLocal.results().count();  if (n)    {      d->status = lookupDone;      cleanError();    }  else    {      d->status = nothing;      setError(IO_LookupError, KResolver::NoName);    }  emit lookupFinished(n);  return;}void KExtendedSocket::startAsyncConnectSlot(){  QObject::disconnect(this, SIGNAL(lookupFinished(int)), this, SLOT(startAsyncConnectSlot()));  if (d->status == lookupDone)    startAsyncConnect();}int KExtendedSocket::resolve(sockaddr *sock, ksocklen_t len, QString &host,			     QString &port, int flags){  kdDebug(170) << "Deprecated function called:" << k_funcinfo << endl;  int err;  char h[NI_MAXHOST], s[NI_MAXSERV];  h[0] = s[0] = '\0';  err = getnameinfo(sock, len, h, sizeof(h) - 1, s, sizeof(s) - 1, flags);  host = QString::fromUtf8(h);  port = QString::fromUtf8(s);  return err;}int KExtendedSocket::resolve(::KSocketAddress *sock, QString &host, QString &port,			     int flags){  return resolve(sock->data, sock->datasize, host, port, flags);}QPtrList<KAddressInfo> KExtendedSocket::lookup(const QString& host, const QString& port,					    int userflags, int *error){  kdDebug(170) << "Deprecated function called:" << k_funcinfo << endl;  int socktype, familyMask, flags;  unsigned i;  QPtrList<KAddressInfo> l;  /* check socket type flags */  if (!process_flags(userflags, socktype, familyMask, flags))    return l;//  kdDebug(170) << "Performing lookup on " << host << "|" << port << endl;  KResolverResults res = KResolver::resolve(host, port, flags, familyMask);  if (res.error())    {      if (error)	*error = res.error();      return l;    }  for (i = 0; i < res.count(); i++)    {      KAddressInfo *ai = new KAddressInfo();      // I should have known that using addrinfo was going to come      // and bite me back some day...      ai->ai = (addrinfo *) malloc(sizeof(addrinfo));      memset(ai->ai, 0, sizeof(addrinfo));      ai->ai->ai_family = res[i].family();      ai->ai->ai_socktype = res[i].socketType();      ai->ai->ai_protocol = res[i].protocol();      QString canon = res[i].canonicalName();      if (!canon.isEmpty())	{	  ai->ai->ai_canonname = (char *) malloc(canon.length()+1);	  strcpy(ai->ai->ai_canonname, canon.ascii()); // ASCII here is intentional	}      if ((ai->ai->ai_addrlen = res[i].length()))	{	  ai->ai->ai_addr = (struct sockaddr *) malloc(res[i].length());	  memcpy(ai->ai->ai_addr, res[i].address().address(), res[i].length());	}      else	{	  ai->ai->ai_addr = 0;	}      ai->addr = ::KSocketAddress::newAddress(ai->ai->ai_addr, ai->ai->ai_addrlen);      l.append(ai);    }  if ( error )      *error = 0;               // all is fine!  return l;}::KSocketAddress *KExtendedSocket::localAddress(int fd){  ::KSocketAddress *local;  struct sockaddr static_sa, *sa = &static_sa;  ksocklen_t len = sizeof(static_sa);  /* find out the socket length, in advance   * we use a sockaddr allocated on the heap just not to pass down   * a NULL pointer to the first call. Some systems are reported to   * set len to 0 if we pass NULL as the sockaddr */  if (KSocks::self()->getsockname(fd, sa, &len) == -1)    return NULL;		// error!  /* was it enough? */  if (len > sizeof(static_sa)#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN      || sa->sa_len > sizeof(static_sa)#endif      )    {      /* nope, malloc a new socket with the proper size */#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN      if (sa->sa_len != len)        len = sa->sa_len;#endif      sa = (sockaddr*)malloc(len);      if (sa == NULL)	return NULL;		// out of memory      if (KSocks::self()->getsockname(fd, sa, &len) == -1)	{	  free(sa);	  return NULL;	}      local = ::KSocketAddress::newAddress(sa, len);      free(sa);    }  else    local = ::KSocketAddress::newAddress(sa, len);  return local;}/* This is exactly the same code as localAddress, except * we call getpeername here */::KSocketAddress *KExtendedSocket::peerAddress(int fd){  ::KSocketAddress *peer;  struct sockaddr static_sa, *sa = &static_sa;  ksocklen_t len = sizeof(static_sa);  /* find out the socket length, in advance   * we use a sockaddr allocated on the heap just not to pass down   * a NULL pointer to the first call. Some systems are reported to   * set len to 0 if we pass NULL as the sockaddr */  if (KSocks::self()->getpeername(fd, sa, &len) == -1)    return NULL;		// error!  /* was it enough? */  if (len > sizeof(static_sa)#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN      || sa->sa_len > sizeof(static_sa)#endif      )    {      /* nope, malloc a new socket with the proper size */#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN      if (sa->sa_len != len)        len = sa->sa_len;#endif      sa = (sockaddr*)malloc(len);      if (sa == NULL)	return NULL;		// out of memory      if (KSocks::self()->getpeername(fd, sa, &len) == -1)	{	  free(sa);	  return NULL;	}      peer = ::KSocketAddress::newAddress(sa, len);      free(sa);    }  else    peer = ::KSocketAddress::newAddress(sa, len);  return peer;}QString KExtendedSocket::strError(int code, int syserr){  const char * msg;  if (code == IO_LookupError)    msg = gai_strerror(syserr);  else    msg = strerror(syserr);  return QString::fromLocal8Bit(msg);}QSocketNotifier *KExtendedSocket::readNotifier() { return d->qsnIn; }QSocketNotifier *KExtendedSocket::writeNotifier() { return d->qsnOut; }/* * class KAddressInfo */#if 0KAddressInfo::KAddressInfo(addrinfo *p){   ai = (addrinfo *) malloc(sizeof(addrinfo));   memcpy(ai, p, sizeof(addrinfo));   ai->ai_next = NULL;   if (p->ai_canonname)   {      ai->ai_canonname = (char *) malloc(strlen(p->ai_canonname)+1);      strcpy(ai->ai_canonname, p->ai_canonname);   }   if (p->ai_addr && p->ai_addrlen)   {      ai->ai_addr = (struct sockaddr *) malloc(p->ai_addrlen);      memcpy(ai->ai_addr, p->ai_addr, p->ai_addrlen);   }   else   {      ai->ai_addr = 0;      ai->ai_addrlen = 0;   }   addr = ::KSocketAddress::newAddress(ai->ai_addr, ai->ai_addrlen);}#endifKAddressInfo::~KAddressInfo(){  if (ai && ai->ai_canonname)    free(ai->ai_canonname);  if (ai && ai->ai_addr)    free(ai->ai_addr);    if (ai)    free(ai);  delete addr;}int KAddressInfo::flags() const{  return ai->ai_flags;}int KAddressInfo::family() const{  return ai->ai_family;}int KAddressInfo::socktype() const{  return ai->ai_socktype;}int KAddressInfo::protocol() const{  return ai->ai_protocol;}const char* KAddressInfo::canonname() const{  return ai->ai_canonname;}void KExtendedSocket::virtual_hook( int id, void* data ){ KBufferedIO::virtual_hook( id, data ); }#include "kextsock.moc"

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?