kresolver.cpp

00001 /*  -*- C++ -*-
00002  *  Copyright (C) 2003-2005 Thiago Macieira <thiago.macieira@kdemail.net>
00003  *
00004  *
00005  *  Permission is hereby granted, free of charge, to any person obtaining
00006  *  a copy of this software and associated documentation files (the
00007  *  "Software"), to deal in the Software without restriction, including
00008  *  without limitation the rights to use, copy, modify, merge, publish,
00009  *  distribute, sublicense, and/or sell copies of the Software, and to
00010  *  permit persons to whom the Software is furnished to do so, subject to
00011  *  the following conditions:
00012  *
00013  *  The above copyright notice and this permission notice shall be included
00014  *  in all copies or substantial portions of the Software.
00015  *
00016  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
00017  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
00018  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
00019  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
00020  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
00021  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
00022  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
00023  */
00024 
00025 #include "config.h"
00026 
00027 // System includes
00028 #include <sys/types.h>
00029 #include <sys/socket.h>
00030 #include <sys/param.h>
00031 #include <errno.h>
00032 #include <netdb.h>
00033 #include <time.h>
00034 #include <arpa/inet.h>
00035 #include <netinet/in.h>
00036 #include <stdlib.h>
00037 #include <unistd.h>
00038 
00039 // Qt includes
00040 #include <qapplication.h>
00041 #include <qstring.h>
00042 #include <qcstring.h>
00043 #include <qstrlist.h>
00044 #include <qstringlist.h>
00045 #include <qshared.h>
00046 #include <qdatetime.h>
00047 #include <qtimer.h>
00048 #include <qmutex.h>
00049 #include <qguardedptr.h>
00050 
00051 // IDN
00052 #ifdef HAVE_IDNA_H
00053 # include <idna.h>
00054 #endif
00055 
00056 // KDE
00057 #include <klocale.h>
00058 
00059 // Us
00060 #include "kresolver.h"
00061 #include "kresolver_p.h"
00062 #include "ksocketaddress.h"
00063 
00064 #ifdef NEED_MUTEX
00065 #warning "mutex"
00066 QMutex getXXbyYYmutex;
00067 #endif
00068 
00069 using namespace KNetwork;
00070 using namespace KNetwork::Internal;
00071 
00073 // class KResolverEntry
00074 
00075 class KNetwork::KResolverEntryPrivate: public QShared
00076 {
00077 public:
00078   KSocketAddress addr;
00079   int socktype;
00080   int protocol;
00081   QString canonName;
00082   QCString encodedName;
00083 
00084   inline KResolverEntryPrivate() :
00085     socktype(0), protocol(0)
00086   { }
00087 };
00088 
00089 // default constructor
00090 KResolverEntry::KResolverEntry() :
00091   d(0L)
00092 {
00093 }
00094 
00095 // constructor with stuff
00096 KResolverEntry::KResolverEntry(const KSocketAddress& addr, int socktype, int protocol,
00097                    const QString& canonName, const QCString& encodedName) :
00098   d(new KResolverEntryPrivate)
00099 {
00100   d->addr = addr;
00101   d->socktype = socktype;
00102   d->protocol = protocol;
00103   d->canonName = canonName;
00104   d->encodedName = encodedName;
00105 }
00106 
00107 // constructor with even more stuff
00108 KResolverEntry::KResolverEntry(const struct sockaddr* sa, Q_UINT16 salen, int socktype,
00109                    int protocol, const QString& canonName,
00110                    const QCString& encodedName) :
00111   d(new KResolverEntryPrivate)
00112 {
00113   d->addr = KSocketAddress(sa, salen);
00114   d->socktype = socktype;
00115   d->protocol = protocol;
00116   d->canonName = canonName;
00117   d->encodedName = encodedName;
00118 }
00119 
00120 // copy constructor
00121 KResolverEntry::KResolverEntry(const KResolverEntry& that) :
00122   d(0L)
00123 {
00124   *this = that;
00125 }
00126 
00127 // destructor
00128 KResolverEntry::~KResolverEntry()
00129 {
00130   if (d == 0L)
00131     return;
00132 
00133   if (d->deref())
00134     delete d;
00135 }
00136 
00137 // returns the socket address
00138 KSocketAddress KResolverEntry::address() const
00139 {
00140   return d ? d->addr : KSocketAddress();
00141 }
00142 
00143 // returns the length
00144 Q_UINT16 KResolverEntry::length() const
00145 {
00146   return d ? d->addr.length() : 0;
00147 }
00148 
00149 // returns the family
00150 int KResolverEntry::family() const
00151 {
00152   return d ? d->addr.family() : AF_UNSPEC;
00153 }
00154 
00155 // returns the canonical name
00156 QString KResolverEntry::canonicalName() const
00157 {
00158   return d ? d->canonName : QString::null;
00159 }
00160 
00161 // returns the encoded name
00162 QCString KResolverEntry::encodedName() const
00163 {
00164   return d ? d->encodedName : QCString();
00165 }
00166 
00167 // returns the socket type
00168 int KResolverEntry::socketType() const
00169 {
00170   return d ? d->socktype : 0;
00171 }
00172 
00173 // returns the protocol
00174 int KResolverEntry::protocol() const
00175 {
00176   return d ? d->protocol : 0;
00177 }
00178 
00179 // assignment operator
00180 KResolverEntry& KResolverEntry::operator= (const KResolverEntry& that)
00181 {
00182   // copy the data
00183   if (that.d)
00184     that.d->ref();
00185 
00186   if (d && d->deref())
00187     delete d;
00188 
00189   d = that.d;
00190   return *this;
00191 }
00192 
00194 // class KResolverResults
00195 
00196 class KNetwork::KResolverResultsPrivate
00197 {
00198 public:
00199   QString node, service;
00200   int errorcode, syserror;
00201 
00202   KResolverResultsPrivate() :
00203     errorcode(0), syserror(0)
00204   { }
00205 };
00206 
00207 // default constructor
00208 KResolverResults::KResolverResults()
00209   : d(new KResolverResultsPrivate)
00210 {
00211 }
00212 
00213 // copy constructor
00214 KResolverResults::KResolverResults(const KResolverResults& other)
00215   : QValueList<KResolverEntry>(other), d(new KResolverResultsPrivate)
00216 {
00217   *d = *other.d;
00218 }
00219 
00220 // destructor
00221 KResolverResults::~KResolverResults()
00222 {
00223   delete d;
00224 }
00225 
00226 // assignment operator
00227 KResolverResults&
00228 KResolverResults::operator= (const KResolverResults& other)
00229 {
00230   if (this == &other)
00231     return *this;
00232 
00233   // copy over the other data
00234   *d = *other.d;
00235 
00236   // now let QValueList do the rest of the work
00237   QValueList<KResolverEntry>::operator =(other);
00238 
00239   return *this;
00240 }
00241 
00242 // gets the error code
00243 int KResolverResults::error() const
00244 {
00245   return d->errorcode;
00246 }
00247 
00248 // gets the system errno
00249 int KResolverResults::systemError() const
00250 {
00251   return d->syserror;
00252 }
00253 
00254 // sets the error codes
00255 void KResolverResults::setError(int errorcode, int systemerror)
00256 {
00257   d->errorcode = errorcode;
00258   d->syserror = systemerror;
00259 }
00260 
00261 // gets the hostname
00262 QString KResolverResults::nodeName() const
00263 {
00264   return d->node;
00265 }
00266 
00267 // gets the service name
00268 QString KResolverResults::serviceName() const
00269 {
00270   return d->service;
00271 }
00272 
00273 // sets the address
00274 void KResolverResults::setAddress(const QString& node,
00275                   const QString& service)
00276 {
00277   d->node = node;
00278   d->service = service;
00279 }
00280 
00281 void KResolverResults::virtual_hook( int, void* )
00282 { /*BASE::virtual_hook( id, data );*/ }
00283 
00284 
00286 // class KResolver
00287 
00288 QStringList *KResolver::idnDomains = 0;
00289 
00290 
00291 // default constructor
00292 KResolver::KResolver(QObject *parent, const char *name)
00293   : QObject(parent, name), d(new KResolverPrivate(this))
00294 {
00295 }
00296 
00297 // constructor with host and service
00298 KResolver::KResolver(const QString& nodename, const QString& servicename,
00299            QObject *parent, const char *name)
00300   : QObject(parent, name), d(new KResolverPrivate(this, nodename, servicename))
00301 {
00302 }
00303 
00304 // destructor
00305 KResolver::~KResolver()
00306 {
00307   cancel(false);
00308   delete d;
00309 }
00310 
00311 // get the status
00312 int KResolver::status() const
00313 {
00314   return d->status;
00315 }
00316 
00317 // get the error code
00318 int KResolver::error() const
00319 {
00320   return d->errorcode;
00321 }
00322 
00323 // get the errno
00324 int KResolver::systemError() const
00325 {
00326   return d->syserror;
00327 }
00328 
00329 // are we running?
00330 bool KResolver::isRunning() const
00331 {
00332   return d->status > 0 && d->status < Success;
00333 }
00334 
00335 // get the hostname
00336 QString KResolver::nodeName() const
00337 {
00338   return d->input.node;
00339 }
00340 
00341 // get the service
00342 QString KResolver::serviceName() const
00343 {
00344   return d->input.service;
00345 }
00346 
00347 // sets the hostname
00348 void KResolver::setNodeName(const QString& nodename)
00349 {
00350   // don't touch those values if we're working!
00351   if (!isRunning())
00352     {
00353       d->input.node = nodename;
00354       d->status = Idle;
00355       d->results.setAddress(nodename, d->input.service);
00356     }
00357 }
00358 
00359 // sets the service
00360 void KResolver::setServiceName(const QString& service)
00361 {
00362   // don't change if running
00363   if (!isRunning())
00364     {
00365       d->input.service = service;
00366       d->status = Idle;
00367       d->results.setAddress(d->input.node, service);
00368     }
00369 }
00370 
00371 // sets the address
00372 void KResolver::setAddress(const QString& nodename, const QString& service)
00373 {
00374   setNodeName(nodename);
00375   setServiceName(service);
00376 }
00377 
00378 // get the flags
00379 int KResolver::flags() const
00380 {
00381   return d->input.flags;
00382 }
00383 
00384 // sets the flags
00385 int KResolver::setFlags(int flags)
00386 {
00387   int oldflags = d->input.flags;
00388   if (!isRunning())
00389     {
00390       d->input.flags = flags;
00391       d->status = Idle;
00392     }
00393   return oldflags;
00394 }
00395 
00396 // sets the family mask
00397 void KResolver::setFamily(int families)
00398 {
00399   if (!isRunning())
00400     {
00401       d->input.familyMask = families;
00402       d->status = Idle;
00403     }
00404 }
00405 
00406 // sets the socket type
00407 void KResolver::setSocketType(int type)
00408 {
00409   if (!isRunning())
00410     {
00411       d->input.socktype = type;
00412       d->status = Idle;
00413     }
00414 }
00415 
00416 // sets the protocol
00417 void KResolver::setProtocol(int protonum, const char *name)
00418 {
00419   if (isRunning())
00420     return;         // can't change now
00421 
00422   // we copy the given protocol name. If it isn't an empty string
00423   // and the protocol number was 0, we will look it up in /etc/protocols
00424   // we also leave the error reporting to the actual lookup routines, in
00425   // case the given protocol name doesn't exist
00426 
00427   d->input.protocolName = name;
00428   if (protonum == 0 && name != 0L && *name != '\0')
00429     {
00430       // must look up the protocol number
00431       d->input.protocol = KResolver::protocolNumber(name);
00432     }
00433   else
00434     d->input.protocol = protonum;
00435   d->status = Idle;
00436 }
00437 
00438 bool KResolver::start()
00439 {
00440   if (!isRunning())
00441     {
00442       d->results.empty();
00443 
00444       // is there anything to be queued?
00445       if (d->input.node.isEmpty() && d->input.service.isEmpty())
00446     {
00447       d->status = KResolver::Success;
00448       emitFinished();
00449     }
00450       else
00451     KResolverManager::manager()->enqueue(this, 0L);
00452     }
00453 
00454   return true;
00455 }
00456 
00457 bool KResolver::wait(int msec)
00458 {
00459   if (!isRunning())
00460     {
00461       emitFinished();
00462       return true;
00463     }
00464 
00465   QMutexLocker locker(&d->mutex);
00466 
00467   if (!isRunning())
00468     {
00469       // it was running and no longer is?
00470       // That means the manager has finished its processing and has posted
00471       // an event for the signal to be emitted already. This means the signal
00472       // will be emitted twice!
00473 
00474       emitFinished();
00475       return true;
00476     }
00477   else
00478     {
00479       QTime t;
00480       t.start();
00481 
00482       while (!msec || t.elapsed() < msec)
00483     {
00484       // wait on the manager to broadcast completion
00485       d->waiting = true;
00486       if (msec)
00487         KResolverManager::manager()->notifyWaiters.wait(&d->mutex, msec - t.elapsed());
00488       else
00489         KResolverManager::manager()->notifyWaiters.wait(&d->mutex);
00490 
00491       // the manager has processed
00492       // see if this object is done
00493       if (!isRunning())
00494         {
00495           // it's done
00496           d->waiting = false;
00497           emitFinished();
00498           return true;
00499         }
00500     }
00501 
00502       // if we've got here, we've timed out
00503       d->waiting = false;
00504       return false;
00505     }
00506 }
00507 
00508 void KResolver::cancel(bool emitSignal)
00509 {
00510   KResolverManager::manager()->dequeue(this);
00511   if (emitSignal)
00512     emitFinished();
00513 }
00514 
00515 KResolverResults
00516 KResolver::results() const
00517 {
00518   if (!isRunning())
00519     return d->results;
00520 
00521   // return a dummy, empty result
00522   KResolverResults r;
00523   r.setAddress(d->input.node, d->input.service);
00524   r.setError(d->errorcode, d->syserror);
00525   return r;
00526 }
00527 
00528 bool KResolver::event(QEvent* e)
00529 {
00530   if (static_cast<int>(e->type()) == KResolverManager::ResolutionCompleted)
00531     {
00532       emitFinished();
00533       return true;
00534     }
00535 
00536   return false;
00537 }
00538 
00539 void KResolver::emitFinished()
00540 {
00541   if (isRunning())
00542     d->status = KResolver::Success;
00543 
00544   QGuardedPtr<QObject> p = this; // guard against deletion
00545 
00546   emit finished(d->results);
00547 
00548   if (p && d->deleteWhenDone)
00549     deleteLater();      // in QObject
00550 }
00551 
00552 QString KResolver::errorString(int errorcode, int syserror)
00553 {
00554   // no i18n now...
00555   static const char * const messages[] =
00556   {
00557     I18N_NOOP("no error"),  // NoError
00558     I18N_NOOP("requested family not supported for this host name"), // AddrFamily
00559     I18N_NOOP("temporary failure in name resolution"),  // TryAgain
00560     I18N_NOOP("non-recoverable failure in name resolution"), // NonRecoverable
00561     I18N_NOOP("invalid flags"),         // BadFlags
00562     I18N_NOOP("memory allocation failure"), // Memory
00563     I18N_NOOP("name or service not known"), // NoName
00564     I18N_NOOP("requested family not supported"),    // UnsupportedFamily
00565     I18N_NOOP("requested service not supported for this socket type"), // UnsupportedService
00566     I18N_NOOP("requested socket type not supported"),   // UnsupportedSocketType
00567     I18N_NOOP("unknown error"),         // UnknownError
00568     I18N_NOOP2("1: the i18n'ed system error code, from errno",
00569           "system error: %1")       // SystemError
00570   };
00571 
00572   // handle the special value
00573   if (errorcode == Canceled)
00574     return i18n("request was canceled");
00575 
00576   if (errorcode > 0 || errorcode < SystemError)
00577     return QString::null;
00578 
00579   QString msg = i18n(messages[-errorcode]);
00580   if (errorcode == SystemError)
00581     msg.arg(QString::fromLocal8Bit(strerror(syserror)));
00582 
00583   return msg;
00584 }
00585 
00586 KResolverResults
00587 KResolver::resolve(const QString& host, const QString& service, int flags,
00588           int families)
00589 {
00590   KResolver qres(host, service, qApp, "synchronous KResolver");
00591   qres.setFlags(flags);
00592   qres.setFamily(families);
00593   qres.start();
00594   qres.wait();
00595   return qres.results();
00596 }
00597 
00598 bool KResolver::resolveAsync(QObject* userObj, const char *userSlot,
00599                  const QString& host, const QString& service,
00600                  int flags, int families)
00601 {
00602   KResolver* qres = new KResolver(host, service, qApp, "asynchronous KResolver");
00603   QObject::connect(qres, SIGNAL(finished(KResolverResults)), userObj, userSlot);
00604   qres->setFlags(flags);
00605   qres->setFamily(families);
00606   qres->d->deleteWhenDone = true; // this is the only difference from the example code
00607   return qres->start();
00608 }
00609 
00610 QStrList KResolver::protocolName(int protonum)
00611 {
00612   struct protoent *pe;
00613 #ifndef HAVE_GETPROTOBYNAME_R
00614   QMutexLocker locker(&getXXbyYYmutex);
00615 
00616   pe = getprotobynumber(protonum);
00617 
00618 #else
00619   size_t buflen = 1024;
00620   struct protoent protobuf;
00621   char *buf;
00622   do
00623     {
00624       buf = new char[buflen];
00625 # ifdef USE_SOLARIS // Solaris uses a 4 argument getprotobynumber_r which returns struct *protoent or NULL
00626       if ((pe = getprotobynumber_r(protonum, &protobuf, buf, buflen)) && (errno == ERANGE))
00627 # else
00628       if (getprotobynumber_r(protonum, &protobuf, buf, buflen, &pe) == ERANGE)
00629 # endif
00630     {
00631       buflen += 1024;
00632       delete [] buf;
00633     }
00634       else
00635     break;
00636     }
00637   while (pe == 0L);
00638 #endif
00639 
00640   // Do common processing
00641   QStrList lst(true);   // use deep copies
00642   if (pe != NULL)
00643     {
00644       lst.append(pe->p_name);
00645       for (char **p = pe->p_aliases; *p; p++)
00646     lst.append(*p);
00647     }
00648 
00649 #ifdef HAVE_GETPROTOBYNAME_R
00650   delete [] buf;
00651 #endif
00652 
00653   return lst;
00654 }
00655 
00656 QStrList KResolver::protocolName(const char *protoname)
00657 {
00658   struct protoent *pe;
00659 #ifndef HAVE_GETPROTOBYNAME_R
00660   QMutexLocker locker(&getXXbyYYmutex);
00661 
00662   pe = getprotobyname(protoname);
00663 
00664 #else
00665   size_t buflen = 1024;
00666   struct protoent protobuf;
00667   char *buf;
00668   do
00669     {
00670       buf = new char[buflen];
00671 # ifdef USE_SOLARIS // Solaris uses a 4 argument getprotobyname_r which returns struct *protoent or NULL
00672       if ((pe = getprotobyname_r(protoname, &protobuf, buf, buflen)) && (errno == ERANGE))
00673 # else
00674       if (getprotobyname_r(protoname, &protobuf, buf, buflen, &pe) == ERANGE)
00675 # endif
00676     {
00677       buflen += 1024;
00678       delete [] buf;
00679     }
00680       else
00681     break;
00682     }
00683   while (pe == 0L);
00684 #endif
00685 
00686   // Do common processing
00687   QStrList lst(true);   // use deep copies
00688   if (pe != NULL)
00689     {
00690       lst.append(pe->p_name);
00691       for (char **p = pe->p_aliases; *p; p++)
00692     lst.append(*p);
00693     }
00694 
00695 #ifdef HAVE_GETPROTOBYNAME_R
00696   delete [] buf;
00697 #endif
00698 
00699   return lst;
00700 }
00701 
00702 int KResolver::protocolNumber(const char *protoname)
00703 {
00704   struct protoent *pe;
00705 #ifndef HAVE_GETPROTOBYNAME_R
00706   QMutexLocker locker(&getXXbyYYmutex);
00707 
00708   pe = getprotobyname(protoname);
00709 
00710 #else
00711   size_t buflen = 1024;
00712   struct protoent protobuf;
00713   char *buf;
00714   do
00715     {
00716       buf = new char[buflen];
00717 # ifdef USE_SOLARIS // Solaris uses a 4 argument getprotobyname_r which returns struct *protoent or NULL
00718       if ((pe = getprotobyname_r(protoname, &protobuf, buf, buflen)) && (errno == ERANGE))
00719 # else
00720       if (getprotobyname_r(protoname, &protobuf, buf, buflen, &pe) == ERANGE)
00721 # endif
00722     {
00723       buflen += 1024;
00724       delete [] buf;
00725     }
00726       else
00727     break;
00728     }
00729   while (pe == 0L);
00730 #endif
00731 
00732   // Do common processing
00733   int protonum = -1;
00734   if (pe != NULL)
00735     protonum = pe->p_proto;
00736 
00737 #ifdef HAVE_GETPROTOBYNAME_R
00738   delete [] buf;
00739 #endif
00740 
00741   return protonum;
00742 }
00743 
00744 int KResolver::servicePort(const char *servname, const char *protoname)
00745 {
00746   struct servent *se;
00747 #ifndef HAVE_GETSERVBYNAME_R
00748   QMutexLocker locker(&getXXbyYYmutex);
00749 
00750   se = getservbyname(servname, protoname);
00751 
00752 #else
00753   size_t buflen = 1024;
00754   struct servent servbuf;
00755   char *buf;
00756   do
00757     {
00758       buf = new char[buflen];
00759 # ifdef USE_SOLARIS // Solaris uses a 5 argument getservbyname_r which returns struct *servent or NULL
00760       if ((se = getservbyname_r(servname, protoname, &servbuf, buf, buflen)) && (errno == ERANGE))
00761 # else
00762       if (getservbyname_r(servname, protoname, &servbuf, buf, buflen, &se) == ERANGE)
00763 # endif
00764     {
00765       buflen += 1024;
00766       delete [] buf;
00767     }
00768       else
00769     break;
00770     }
00771   while (se == 0L);
00772 #endif
00773 
00774   // Do common processing
00775   int servport = -1;
00776   if (se != NULL)
00777     servport = ntohs(se->s_port);
00778 
00779 #ifdef HAVE_GETSERVBYNAME_R
00780   delete [] buf;
00781 #endif
00782 
00783   return servport;
00784 }
00785 
00786 QStrList KResolver::serviceName(const char* servname, const char *protoname)
00787 {
00788   struct servent *se;
00789 #ifndef HAVE_GETSERVBYNAME_R
00790   QMutexLocker locker(&getXXbyYYmutex);
00791 
00792   se = getservbyname(servname, protoname);
00793 
00794 #else
00795   size_t buflen = 1024;
00796   struct servent servbuf;
00797   char *buf;
00798   do
00799     {
00800       buf = new char[buflen];
00801 # ifdef USE_SOLARIS // Solaris uses a 5 argument getservbyname_r which returns struct *servent or NULL
00802       if ((se = getservbyname_r(servname, protoname, &servbuf, buf, buflen)) && (errno == ERANGE))
00803 # else
00804       if (getservbyname_r(servname, protoname, &servbuf, buf, buflen, &se) == ERANGE)
00805 # endif
00806     {
00807       buflen += 1024;
00808       delete [] buf;
00809     }
00810       else
00811     break;
00812     }
00813   while (se == 0L);
00814 #endif
00815 
00816   // Do common processing
00817   QStrList lst(true);   // use deep copies
00818   if (se != NULL)
00819     {
00820       lst.append(se->s_name);
00821       for (char **p = se->s_aliases; *p; p++)
00822     lst.append(*p);
00823     }
00824 
00825 #ifdef HAVE_GETSERVBYNAME_R
00826   delete [] buf;
00827 #endif
00828 
00829   return lst;
00830 }
00831 
00832 QStrList KResolver::serviceName(int port, const char *protoname)
00833 {
00834   struct servent *se;
00835 #ifndef HAVE_GETSERVBYPORT_R
00836   QMutexLocker locker(&getXXbyYYmutex);
00837 
00838   se = getservbyport(port, protoname);
00839 
00840 #else
00841   size_t buflen = 1024;
00842   struct servent servbuf;
00843   char *buf;
00844   do
00845     {
00846       buf = new char[buflen];
00847 # ifdef USE_SOLARIS // Solaris uses a 5 argument getservbyport_r which returns struct *servent or NULL
00848       if ((se = getservbyport_r(port, protoname, &servbuf, buf, buflen)) && (errno == ERANGE))
00849 # else
00850       if (getservbyport_r(port, protoname, &servbuf, buf, buflen, &se) == ERANGE)
00851 # endif
00852     {
00853       buflen += 1024;
00854       delete [] buf;
00855     }
00856       else
00857     break;
00858     }
00859   while (se == 0L);
00860 #endif
00861 
00862   // Do common processing
00863   QStrList lst(true);   // use deep copies
00864   if (se != NULL)
00865     {
00866       lst.append(se->s_name);
00867       for (char **p = se->s_aliases; *p; p++)
00868     lst.append(*p);
00869     }
00870 
00871 #ifdef HAVE_GETSERVBYPORT_R
00872   delete [] buf;
00873 #endif
00874 
00875   return lst;
00876 }
00877 
00878 QString KResolver::localHostName()
00879 {
00880   QCString name;
00881   int len;
00882 
00883 #ifdef MAXHOSTNAMELEN
00884   len = MAXHOSTNAMELEN;
00885 #else
00886   len = 256;
00887 #endif
00888 
00889   while (true)
00890     {
00891       name.resize(len);
00892 
00893       if (gethostname(name.data(), len - 1) == 0)
00894     {
00895       // Call succeeded, but it's not guaranteed to be NUL-terminated
00896       // Note that some systems return success even if they did truncation
00897       name[len - 1] = '\0';
00898       break;
00899     }
00900 
00901       // Call failed
00902       if (errno == ENAMETOOLONG || errno == EINVAL)
00903     len += 256;
00904       else
00905     {
00906       // Oops! Unknown error!
00907       name = QCString();
00908     }
00909     }
00910 
00911   if (name.isEmpty())
00912     return QString::fromLatin1("localhost");
00913 
00914   if (name.find('.') == -1)
00915     {
00916       // not fully qualified
00917       // must resolve
00918       KResolverResults results = resolve(name, "0", CanonName);
00919       if (results.isEmpty())
00920     // cannot find a valid hostname!
00921     return QString::fromLatin1("localhost");
00922       else
00923     return results.first().canonicalName();
00924     }
00925 
00926   return domainToUnicode(name);
00927 }
00928 
00929 
00930 // forward declaration
00931 static QStringList splitLabels(const QString& unicodeDomain);
00932 static QCString ToASCII(const QString& label);
00933 static QString ToUnicode(const QString& label);
00934 
00935 static QStringList *KResolver_initIdnDomains()
00936 {
00937   const char *kde_use_idn = getenv("KDE_USE_IDN");
00938   if (!kde_use_idn)
00939      kde_use_idn = "ac:at:br:ch:cl:cn:de:dk:fi:hu:info:io:jp:kr:li:lt:museum:no:se:sh:th:tm:tw:vn";
00940   return new QStringList(QStringList::split(':', QString::fromLatin1(kde_use_idn).lower()));
00941 }
00942 
00943 // implement the ToAscii function, as described by IDN documents
00944 QCString KResolver::domainToAscii(const QString& unicodeDomain)
00945 {
00946   if (!idnDomains)
00947     idnDomains = KResolver_initIdnDomains();
00948 
00949   QCString retval;
00950   // RFC 3490, section 4 describes the operation:
00951   // 1) this is a query, so don't allow unassigned
00952 
00953   // 2) split the domain into individual labels, without
00954   // separators.
00955   QStringList input = splitLabels(unicodeDomain);
00956 
00957   // Do we allow IDN names for this TLD?
00958   if (input.count() && !idnDomains->contains(input[input.count()-1].lower()))
00959     return input.join(".").lower().latin1(); // No IDN allowed for this TLD
00960 
00961   // 3) decide whether to enforce the STD3 rules for chars < 0x7F
00962   // we don't enforce
00963 
00964   // 4) for each label, apply ToASCII
00965   QStringList::Iterator it = input.begin();
00966   const QStringList::Iterator end = input.end();
00967   for ( ; it != end; ++it)
00968     {
00969       QCString cs = ToASCII(*it);
00970       if (cs.isNull())
00971     return QCString();  // error!
00972 
00973       // no, all is Ok.
00974       if (!retval.isEmpty())
00975     retval += '.';
00976       retval += cs;
00977     }
00978 
00979   return retval;
00980 }
00981 
00982 QString KResolver::domainToUnicode(const QCString& asciiDomain)
00983 {
00984   return domainToUnicode(QString::fromLatin1(asciiDomain));
00985 }
00986 
00987 // implement the ToUnicode function, as described by IDN documents
00988 QString KResolver::domainToUnicode(const QString& asciiDomain)
00989 {
00990   if (asciiDomain.isEmpty())
00991     return asciiDomain;
00992   if (!idnDomains)
00993     idnDomains = KResolver_initIdnDomains();
00994 
00995   QString retval;
00996 
00997   // draft-idn-idna-14.txt, section 4 describes the operation:
00998   // 1) this is a query, so don't allow unassigned
00999   //   besides, input is ASCII
01000 
01001   // 2) split the domain into individual labels, without
01002   // separators.
01003   QStringList input = splitLabels(asciiDomain);
01004 
01005   // Do we allow IDN names for this TLD?
01006   if (input.count() && !idnDomains->contains(input[input.count()-1].lower()))
01007     return asciiDomain.lower(); // No TLDs allowed
01008 
01009   // 3) decide whether to enforce the STD3 rules for chars < 0x7F
01010   // we don't enforce
01011 
01012   // 4) for each label, apply ToUnicode
01013   QStringList::Iterator it;
01014   const QStringList::Iterator end = input.end();
01015   for (it = input.begin(); it != end; ++it)
01016     {
01017       QString label = ToUnicode(*it).lower();
01018 
01019       // ToUnicode can't fail
01020       if (!retval.isEmpty())
01021     retval += '.';
01022       retval += label;
01023     }
01024 
01025   return retval;
01026 }
01027 
01028 QString KResolver::normalizeDomain(const QString& domain)
01029 {
01030   return domainToUnicode(domainToAscii(domain));
01031 }
01032 
01033 void KResolver::virtual_hook( int, void* )
01034 { /*BASE::virtual_hook( id, data );*/ }
01035 
01036 // here follows IDN functions
01037 // all IDN functions conform to the following documents:
01038 //  RFC 3454 - Preparation of Internationalized Strings
01039 //  RFC 3490 - Internationalizing Domain Names in Applications (IDNA)
01040 //  RFC 3491 - Nameprep: A Stringprep Profile for
01041 //                Internationalized Domain Names (IDN
01042 //  RFC 3492 - Punycode: A Bootstring encoding of Unicode
01043 //          for Internationalized Domain Names in Applications (IDNA)
01044 
01045 static QStringList splitLabels(const QString& unicodeDomain)
01046 {
01047   // From RFC 3490 section 3.1:
01048   // "Whenever dots are used as label separators, the following characters
01049   // MUST be recognized as dots: U+002E (full stop), U+3002 (ideographic full
01050   // stop), U+FF0E (fullwidth full stop), U+FF61 (halfwidth ideographic full
01051   // stop)."
01052   static const unsigned int separators[] = { 0x002E, 0x3002, 0xFF0E, 0xFF61 };
01053 
01054   QStringList lst;
01055   int start = 0;
01056   uint i;
01057   for (i = 0; i < unicodeDomain.length(); i++)
01058     {
01059       unsigned int c = unicodeDomain[i].unicode();
01060 
01061       if (c == separators[0] ||
01062       c == separators[1] ||
01063       c == separators[2] ||
01064       c == separators[3])
01065     {
01066       // found a separator!
01067       lst << unicodeDomain.mid(start, i - start);
01068       start = i + 1;
01069     }
01070     }
01071   if ((long)i >= start)
01072     // there is still one left
01073     lst << unicodeDomain.mid(start, i - start);
01074 
01075   return lst;
01076 }
01077 
01078 static QCString ToASCII(const QString& label)
01079 {
01080 #ifdef HAVE_IDNA_H
01081   // We have idna.h, so we can use the idna_to_ascii
01082   // function :)
01083 
01084   if (label.length() > 64)
01085     return (char*)0L;       // invalid label
01086 
01087   if (label.length() == 0)
01088     // this is allowed
01089     return QCString("");    // empty, not null
01090 
01091   QCString retval;
01092   char buf[65];
01093 
01094   Q_UINT32* ucs4 = new Q_UINT32[label.length() + 1];
01095 
01096   uint i;
01097   for (i = 0; i < label.length(); i++)
01098     ucs4[i] = (unsigned long)label[i].unicode();
01099   ucs4[i] = 0;          // terminate with NUL, just to be on the safe side
01100 
01101   if (idna_to_ascii_4i(ucs4, label.length(), buf, 0) == IDNA_SUCCESS)
01102     // success!
01103     retval = buf;
01104 
01105   delete [] ucs4;
01106   return retval;
01107 #else
01108   return label.latin1();
01109 #endif
01110 }
01111 
01112 static QString ToUnicode(const QString& label)
01113 {
01114 #ifdef HAVE_IDNA_H
01115   // We have idna.h, so we can use the idna_to_unicode
01116   // function :)
01117 
01118   Q_UINT32 *ucs4_input, *ucs4_output;
01119   size_t outlen;
01120 
01121   ucs4_input = new Q_UINT32[label.length() + 1];
01122   for (uint i = 0; i < label.length(); i++)
01123     ucs4_input[i] = (unsigned long)label[i].unicode();
01124 
01125   // try the same length for output
01126   ucs4_output = new Q_UINT32[outlen = label.length()];
01127 
01128   idna_to_unicode_44i(ucs4_input, label.length(),
01129               ucs4_output, &outlen,
01130               0);
01131 
01132   if (outlen > label.length())
01133     {
01134       // it must have failed
01135       delete [] ucs4_output;
01136       ucs4_output = new Q_UINT32[outlen];
01137 
01138       idna_to_unicode_44i(ucs4_input, label.length(),
01139               ucs4_output, &outlen,
01140               0);
01141     }
01142 
01143   // now set the answer
01144   QString result;
01145   result.setLength(outlen);
01146   for (uint i = 0; i < outlen; i++)
01147     result[i] = (unsigned int)ucs4_output[i];
01148 
01149   delete [] ucs4_input;
01150   delete [] ucs4_output;
01151 
01152   return result;
01153 #else
01154   return label;
01155 #endif
01156 }
01157 
01158 #include "kresolver.moc"
KDE Home | KDE Accessibility Home | Description of Access Keys