Vidalia  0.2.15
TorControl.h
Go to the documentation of this file.
00001 /*
00002 **  This file is part of Vidalia, and is subject to the license terms in the
00003 **  LICENSE file, found in the top level directory of this distribution. If 
00004 **  you did not receive the LICENSE file with this file, you may obtain it
00005 **  from the Vidalia source package distributed by the Vidalia Project at
00006 **  http://www.torproject.org/projects/vidalia.html. No part of Vidalia, 
00007 **  including this file, may be copied, modified, propagated, or distributed 
00008 **  except according to the terms described in the LICENSE file.
00009 */
00010 
00011 /* 
00012 ** \file TorControl.h
00013 ** \brief Object for interacting with the Tor process and control interface
00014 */
00015 
00016 #ifndef _TORCONTROL_H
00017 #define _TORCONTROL_H
00018 
00019 #include "tcglobal.h"
00020 #include "ControlConnection.h"
00021 #include "TorProcess.h"
00022 #include "TorEvents.h"
00023 #include "TorSignal.h"
00024 #include "RouterDescriptor.h"
00025 #include "RouterStatus.h"
00026 #include "BootstrapStatus.h"
00027 #include "Circuit.h"
00028 #include "Stream.h"
00029 #include "AddressMap.h"
00030 #include "ControlMethod.h"
00031 
00032 #if defined(Q_OS_WIN32)
00033 #include "TorService.h"
00034 #endif
00035 
00036 #include <QObject>
00037 #include <QHash>
00038 #include <QList>
00039 #include <QStringList>
00040 #include <QVariantMap>
00041 
00042 class ProtocolInfo;
00043 
00044 /** DescriptorAnnotations stores a map of annotation keys to (possibly empty)
00045  * annotation values. */
00046 typedef QHash<QString,QString> DescriptorAnnotations;
00047 
00048 
00049 class TorControl : public QObject
00050 {
00051   Q_OBJECT
00052   
00053 public:
00054   /** Default constructor */
00055   TorControl(ControlMethod::Method method = ControlMethod::Port);
00056   /** Default destructor */
00057   ~TorControl();
00058 
00059   /** Start the Tor process */
00060   void start(const QString &tor, const QStringList &args);
00061   /** Stop the Tor process */
00062   bool stop(QString *errmsg = 0);
00063   /** Detect if the Tor process is running */
00064   bool isRunning();
00065   /** Detects if the Tor process is running under Vidalia. */
00066   bool isVidaliaRunningTor();
00067   /** Stops reading log messages from the Tor process's stdout. This has no
00068    * effect if isVidaliaRunningTor() is false. */
00069   void closeTorStdout();
00070 
00071   /** Connect to Tor's control socket */
00072   void connect(const QHostAddress &address, quint16 port);
00073   void connect(const QString &path);
00074   /** Disconnect from Tor's control socket */
00075   void disconnect();
00076   /** Check if we're connected to Tor's control socket */
00077   bool isConnected();
00078   /** Sends an authentication cookie to Tor. */
00079   bool authenticate(const QByteArray cookie, QString *errmsg = 0);
00080   /** Sends an authentication password to Tor. */
00081   bool authenticate(const QString &password = QString(), QString *errmsg = 0);
00082   
00083   /** Sends a PROTOCOLINFO command to Tor and parses the response. */
00084   ProtocolInfo protocolInfo(QString *errmsg = 0);
00085 
00086   /** Returns the Tor software's current bootstrap phase and status. */
00087   BootstrapStatus bootstrapStatus(QString *errmsg = 0);
00088 
00089   /** Returns true if Tor either has an open circuit or (on Tor >= 
00090    * 0.2.0.1-alpha) has previously decided it's able to establish a circuit. */
00091   bool isCircuitEstablished();
00092 
00093   /** Sends a GETINFO message to Tor based on the given keys */
00094   bool getInfo(QHash<QString,QString> &map, QString *errmsg = 0);
00095   /** Sends a GETINFO message for a single info value to Tor */
00096   bool getInfo(QString key, QString &val, QString *errmsg = 0);
00097 
00098   /** Sends a GETINFO message to Tor using the given list of <b>keys</b> and
00099    * returns a QVariantMap containing the specified keys and their values as
00100    * returned by Tor. Returns a default constructed QVariantMap on failure. */
00101   QVariantMap getInfo(const QStringList &keys, QString *errmsg = 0);
00102   /** Sends a GETINFO message to Tor with a single <b>key</b> and returns a
00103    * QVariant containing the value returned by Tor. Returns a default
00104    * constructed QVariant on failure. */
00105   QVariant getInfo(const QString &key, QString *errmsg = 0);
00106 
00107   /** Sends a signal to Tor */
00108   bool signal(TorSignal::Signal sig, QString *errmsg = 0);
00109  
00110   /** Returns an address on which Tor is listening for application
00111    * requests. If none are available, a null QHostAddress is returned. */
00112   QHostAddress getSocksAddress(QString *errmsg = 0);
00113   /** Returns a (possibly empty) list of all currently configured 
00114    * SocksListenAddress entries. */
00115   QStringList getSocksAddressList(QString *errmsg = 0);
00116   /** Returns a valid SOCKS port for Tor, or 0 if Tor is not accepting
00117    * application requests. */
00118   quint16 getSocksPort(QString *errmsg = 0);
00119   /** Returns a list of all currently configured SOCKS ports. If Tor is not
00120    * accepting any application connections, an empty list will be returned. */
00121   QList<quint16> getSocksPortList(QString *errmsg = 0);
00122 
00123   /** Returns Tor's version as a string. */
00124   QString getTorVersionString();
00125   /** Returns Tor's version as a numeric value. */
00126   quint32 getTorVersion();
00127 
00128   /** Sets an event and its handler. If add is true, then the event is added,
00129    * otherwise it is removed. If set is true, then the given event will be
00130    * registered with Tor. */
00131   bool setEvent(TorEvents::Event e, bool add = true, bool set = true,
00132                 QString *errmsg = 0);
00133   /** Register events of interest with Tor */
00134   bool setEvents(QString *errmsg = 0);
00135 
00136   /** Sets each configuration key in <b>map</b> to the value associated with its key. */
00137   bool setConf(QHash<QString,QString> map, QString *errmsg = 0);
00138   /** Sets a single configuration key to the given value. */
00139   bool setConf(QString key, QString value, QString *errmsg = 0);
00140   /** Sets a single configuration string that is formatted <key=escaped value>. */
00141   bool setConf(QString keyAndValue, QString *errmsg = 0);
00142   /** Gets values for a set of configuration keys, each of which has a single
00143    * value. */
00144   bool getConf(QHash<QString,QString> &map, QString *errmsg = 0);
00145   /** Gets a set of configuration keyvalues and stores them in <b>map</b>. */
00146   bool getConf(QHash<QString,QStringList> &map, QString *errmsg = 0);
00147   /** Gets a single configuration value for <b>key</b>. */
00148   bool getConf(QString key, QString &value, QString *errmsg = 0);
00149   /** Gets a list of configuration values for <b>key</b>. */
00150   bool getConf(QString key, QStringList &value, QString *errmsg = 0);
00151 
00152   /** Sends a GETCONF message to Tor using the given list of <b>keys</b> and
00153    * returns a QVariantMap containing the specified keys and their values as
00154    * returned by Tor. Returns a default constructed QVariantMap on failure. */
00155   QVariantMap getConf(const QStringList &keys, QString *errmsg = 0);
00156   /** Sends a GETCONF message to Tor with a single <b>key</b> and returns a
00157    * QVariant containing the value returned by Tor. Returns a default
00158    * constructed QVariant on failure. */
00159   QVariant getConf(const QString &key, QString *errmsg = 0);
00160   /** Sends a GETCONF message to Tor with the single key and returns a QString
00161    * containing the value returned by Tor */
00162   QString getHiddenServiceConf(const QString &key, QString *errmsg = 0);
00163   
00164   /** Asks Tor to save the current configuration to its torrc */
00165   bool saveConf(QString *errmsg = 0);
00166   /** Tells Tor to reset the given configuration keys back to defaults. */
00167   bool resetConf(QStringList keys, QString *errmsg = 0);
00168   /** Tells Tor to reset a configuration key back to its default value. */
00169   bool resetConf(QString key, QString *errmsg = 0);
00170 
00171   /** Returns an unparsed router descriptor for the router whose fingerprint
00172    * matches <b>id</b>. The returned text can later be parsed by the
00173    * RouterDescriptor class. If <b>id</b> is invalid, then an empty
00174    * QStringList is returned. */
00175   QStringList getRouterDescriptorText(const QString &id, QString *errmsg = 0);
00176   /** Returns the descriptor for the router whose fingerprint matches
00177    * <b>id</b>. If <b>id</b> is invalid or the router's descriptor cannot be
00178    * parsed, then an invalid RouterDescriptor is returned. */
00179   RouterDescriptor getRouterDescriptor(const QString &id, QString *errmsg = 0);
00180   /** Returns the status of the router whose fingerprint matches <b>id</b>. If
00181    * <b>id</b> is invalid or the router's status cannot be parsed, then an
00182    * invalid RouterStatus is returned. */
00183   RouterStatus getRouterStatus(const QString &id, QString *errmsg = 0);
00184   /** Returns a RouterStatus object for every known router in the network. If
00185    * the network status document cannot be parsed, then an empty NetworkStatus
00186    * is returned. */
00187   NetworkStatus getNetworkStatus(QString *errmsg = 0);
00188   /** Returns the annotations for the router whose fingerprint matches
00189    * <b>id</b>. If <b>id</b> is invalid or the router's descriptor cannot be
00190    * parsed, then an empty DescriptorAnnotations is returned and
00191    * <b>errmsg</b> is set if it's not NULL. (Tor >= 0.2.0.13-alpha only) */
00192   DescriptorAnnotations getDescriptorAnnotations(const QString &id,
00193                                                  QString *errmsg = 0);
00194 
00195   /** Gets a list of current circuits. */
00196   CircuitList getCircuits(QString *errmsg = 0);
00197   /** Gets a list of current streams. */
00198   StreamList getStreams(QString *errmsg = 0);
00199   
00200   /** Gets a list of address mappings of the type specified by <b>type</b>
00201    * (defaults to <i>AddressMapAll</i>. */
00202   AddressMap getAddressMap(
00203     AddressMap::AddressMapType type = AddressMap::AddressMapAll,
00204     QString *errmsg = 0);
00205 
00206   /** Gets the ISO-3166 two-letter country code for <b>ip</b> from Tor.
00207    * Returns a default-constructed QString on failure or if a country code
00208    * is not known for <b>ip</b>. On failure, <b>errmsg</b> will be set if
00209    * it's not NULL. */
00210   QString ipToCountry(const QHostAddress &ip, QString *errmsg = 0);
00211 
00212 public slots:
00213   /** Closes the circuit specified by <b>circId</b>. If <b>ifUnused</b> is
00214    * true, then the circuit will not be closed unless it is unused. */
00215   bool closeCircuit(const CircuitId &circId, bool ifUnused = false,
00216                     QString *errmsg = 0);
00217   /** Closes the stream specified by <b>streamId</b>. */
00218   bool closeStream(const StreamId &streamId, QString *errmsg = 0);
00219 
00220 signals:
00221   /** Emitted when the Tor process has started */
00222   void started();
00223   /** Emitted when the Tor process fails to start. */
00224   void startFailed(QString errmsg);
00225   /** Emitted when the Tor process has stopped */
00226   void stopped(int exitCode, QProcess::ExitStatus exitStatus);
00227   /** Emitted when the Tor process has stopped. */
00228   void stopped();
00229   /** Emitted when the controller has connected to Tor */
00230   void connected();
00231   /** Emitted when the controller failed to connect to Tor. */
00232   void connectFailed(QString errmsg);
00233   /** Emitted when the controller has disconnected from Tor */
00234   void disconnected();
00235   /** Emitted when the control socket is connected and authenticated. */
00236   void authenticated();
00237   /** Emitted when Tor rejects our authentication attempt. */
00238   void authenticationFailed(QString errmsg);
00239 
00240   /** Emitted when Tor writes the message <b>msg</b> to the control port
00241    * with message severity <b>level</b>.
00242    */
00243   void logMessage(tc::Severity level, const QString &msg);
00244 
00245   /** Emitted when Tor sends a bandwidth usage update (roughly once every
00246    * second). <b>bytesReceived</b> is the number of bytes read by Tor over
00247    * the previous second and <b>bytesWritten</b> is the number of bytes
00248    * sent over the same interval.
00249    */
00250   void bandwidthUpdate(quint64 bytesReceived, quint64 bytesSent);
00251 
00252   /** Emitted when the stream status of <b>stream</b> has changed.
00253    */
00254   void streamStatusChanged(const Stream &stream);
00255 
00256   /** Emitted when the circuit status of <b>circuit</b> has changed.
00257    */
00258   void circuitStatusChanged(const Circuit &circuit);
00259 
00260   /** Emitted when Tor has mapped the address <b>from</b> to the address
00261    * <b>to</b>. <b>expires</b> indicates the time at which when the address
00262    * mapping will no longer be considered valid.
00263    */
00264   void addressMapped(const QString &from, const QString &to,
00265                      const QDateTime &expires);
00266 
00267   /** Emitted when Tor has received one or more new router descriptors.
00268    * <b>ids</b> contains a list of digests of the new descriptors.
00269    */
00270   void newDescriptors(const QStringList &ids);
00271 
00272   /** Indicates Tor has been able to successfully establish one or more
00273    * circuits.
00274    */
00275   void circuitEstablished();
00276 
00277   /** Indicates that Tor has decided the user's Tor software <b>version</b>
00278    * is no longer recommended for some <b>reason</b>. <b>recommended</b> is
00279    * a list of Tor software versions that are considered current.
00280    */
00281   void dangerousTorVersion(tc::TorVersionStatus reason,
00282                            const QString &version,
00283                            const QStringList &recommended);
00284 
00285   /** Emitted during Tor's startup process to indicate how far in its
00286    * bootstrapping process it has progressed. <b>status</b> may indicate
00287    * the current bootstrapping stage or an error during bootstrapping.
00288    */
00289   void bootstrapStatusChanged(const BootstrapStatus &status);
00290 
00291   /** Emitted when the user attempts to establish a connection to some
00292    * destination on port <b>port</b>, which is a port known to use
00293    * plaintext connections (as determined by Tor's WarnPlaintextPorts and
00294    * RejectPlaintextPorts torrc options). <b>rejected</b> indicates whether
00295    * Tor rejected the connection or permitted it to connect anyway.
00296    */
00297   void dangerousPort(quint16 port, bool rejected);
00298 
00299   /** Emitted when Tor detects a problem with a SOCKS connection from the
00300    * user, such as a bad hostname, dangerous SOCKS protocol type, or a bad
00301    * hostname. <b>type</b> indicates the type of error encountered and
00302    * <b>destination</b> (if non-empty) specifies the attempted connection
00303    * destination address or hostname.
00304    */
00305   void socksError(tc::SocksError type, const QString &destination);
00306 
00307   /** Emitted when Tor decides the client's external IP address has changed
00308    * to <b>ip</b>. If <b>hostname</b> is non-empty, Tor obtained the new
00309    * value for <b>ip</b> by resolving <b>hostname</b>. 
00310    */
00311   void externalAddressChanged(const QHostAddress &ip, const QString &hostname);
00312 
00313   /** Indicates that Tor has determined the client's clock is potentially
00314    * skewed by <b>skew</b> seconds relative to <b>source</b>.
00315    */
00316   void clockSkewed(int skew, const QString &source);
00317 
00318   /** Emitted when Tor has encountered an internal bug. <b>reason</b> is
00319    * Tor's description of the bug.
00320    */
00321   void bug(const QString &reason);
00322 
00323   /** Emitted when Tor determines that the user's DNS provider is providing
00324    * an address for non-existent domains when it should really be saying
00325    * "NXDOMAIN".
00326    */
00327   void dnsHijacked();
00328 
00329   /** Emitted when Tor determines that the user's DNS provider is providing
00330    * a hijacked address even for well-known websites.
00331    */
00332   void dnsUseless();
00333 
00334   /** Indicates Tor has started testing the reachability of its OR port 
00335    * using the IP address <b>ip</b> and port <b>port</b>.
00336    */
00337   void checkingOrPortReachability(const QHostAddress &ip, quint16 port);
00338 
00339   /** Tor has completed testing the reachability of its OR port using
00340    * the IP address <b>ip</b> and port <b>port</b>. If the user's OR port
00341    * was reachable, <b>reachable</b> will be set to true.
00342    */
00343   void orPortReachabilityFinished(const QHostAddress &ip, quint16 port,
00344                                   bool reachable);
00345 
00346   /** Indicates Tor has started testing the reachability of its directory
00347    * port using the IP address <b>ip</b> and port <b>port</b>.
00348    */
00349   void checkingDirPortReachability(const QHostAddress &ip, quint16 port);
00350 
00351   /** Tor has completed testing the reachability of its directory port using
00352    * the IP address <b>ip</b> and port <b>port</b>. If the user's directory
00353    * port was reachable, <b>reachable</b> will be set to true.
00354    */
00355   void dirPortReachabilityFinished(const QHostAddress &ip, quint16 port,
00356                                    bool reachable);
00357 
00358   /** Emitted when the directory authority with IP address <b>ip</b> and
00359    * port <b>port</b> rejected the user's server descriptor. <b>reason</b>
00360    * describes why the descriptor was rejected (e.g., malformed, skewed
00361    * clock, etc.).
00362    */
00363   void serverDescriptorRejected(const QHostAddress &ip, quint16 port,
00364                                 const QString &reason);
00365 
00366   /** Emitted when the directory authority with IP address <b>ip</b> and
00367    * port <b>port</b> accepted the user's server descriptor.
00368    */
00369   void serverDescriptorAccepted(const QHostAddress &ip, quint16 port);
00370 
00371   /** Emitted when at least one directory authority has accepted the user's
00372    * server descriptor.
00373    */
00374   void serverDescriptorAccepted();
00375 
00376 private:
00377   /** Instantiates a connection used to talk to Tor's control port */
00378   ControlConnection* _controlConn;
00379   /** Manages and monitors the Tor process */
00380   TorProcess* _torProcess;
00381   /** Keep track of which events we're interested in */
00382   TorEvents* _eventHandler;
00383   TorEvents::Events _events;
00384   /** The version of Tor we're currently talking to. */
00385   QString _torVersion;
00386   ControlMethod::Method _method;
00387 #if defined(Q_OS_WIN32)
00388   /** Manages the Tor service, if supported and enabled */
00389   TorService* _torService;
00390 #endif
00391 
00392   /** Send a message to Tor and read the response */
00393   bool send(ControlCommand cmd, ControlReply &reply, QString *errmsg = 0);
00394   /** Send a message to Tor and discard the response */
00395   bool send(ControlCommand cmd, QString *errmsg = 0);
00396   /** Tells Tor the controller wants to enable <b>feature</b> via the
00397    * USEFEATURE control command. Returns true if the given feature was
00398    * successfully enabled. */
00399   bool useFeature(const QString &feature, QString *errmsg = 0);
00400 
00401 /* The slots below simply relay signals from the appropriate member objects */
00402 private slots:
00403   void onStopped(int exitCode, QProcess::ExitStatus exitStatus);
00404   void onDisconnected();
00405   void onLogStdout(const QString &severity, const QString &message);
00406   void onAuthenticated();
00407 };
00408 
00409 #endif
00410