Vidalia  0.2.17
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   /** Takes ownership of the tor process it's communicating to */
00213   bool takeOwnership(QString *errmsg);
00214 
00215 public slots:
00216   /** Closes the circuit specified by <b>circId</b>. If <b>ifUnused</b> is
00217    * true, then the circuit will not be closed unless it is unused. */
00218   bool closeCircuit(const CircuitId &circId, bool ifUnused = false,
00219                     QString *errmsg = 0);
00220   /** Closes the stream specified by <b>streamId</b>. */
00221   bool closeStream(const StreamId &streamId, QString *errmsg = 0);
00222 
00223 signals:
00224   /** Emitted when the Tor process has started */
00225   void started();
00226   /** Emitted when the Tor process fails to start. */
00227   void startFailed(QString errmsg);
00228   /** Emitted when the Tor process has stopped */
00229   void stopped(int exitCode, QProcess::ExitStatus exitStatus);
00230   /** Emitted when the Tor process has stopped. */
00231   void stopped();
00232   /** Emitted when the controller has connected to Tor */
00233   void connected();
00234   /** Emitted when the controller failed to connect to Tor. */
00235   void connectFailed(QString errmsg);
00236   /** Emitted when the controller has disconnected from Tor */
00237   void disconnected();
00238   /** Emitted when the control socket is connected and authenticated. */
00239   void authenticated();
00240   /** Emitted when Tor rejects our authentication attempt. */
00241   void authenticationFailed(QString errmsg);
00242 
00243   /** Emitted when Tor writes the message <b>msg</b> to the control port
00244    * with message severity <b>level</b>.
00245    */
00246   void logMessage(tc::Severity level, const QString &msg);
00247 
00248   /** Emitted when Tor sends a bandwidth usage update (roughly once every
00249    * second). <b>bytesReceived</b> is the number of bytes read by Tor over
00250    * the previous second and <b>bytesWritten</b> is the number of bytes
00251    * sent over the same interval.
00252    */
00253   void bandwidthUpdate(quint64 bytesReceived, quint64 bytesSent);
00254 
00255   /** Emitted when the stream status of <b>stream</b> has changed.
00256    */
00257   void streamStatusChanged(const Stream &stream);
00258 
00259   /** Emitted when the circuit status of <b>circuit</b> has changed.
00260    */
00261   void circuitStatusChanged(const Circuit &circuit);
00262 
00263   /** Emitted when Tor has mapped the address <b>from</b> to the address
00264    * <b>to</b>. <b>expires</b> indicates the time at which when the address
00265    * mapping will no longer be considered valid.
00266    */
00267   void addressMapped(const QString &from, const QString &to,
00268                      const QDateTime &expires);
00269 
00270   /** Emitted when Tor has received one or more new router descriptors.
00271    * <b>ids</b> contains a list of digests of the new descriptors.
00272    */
00273   void newDescriptors(const QStringList &ids);
00274 
00275   /** Indicates Tor has been able to successfully establish one or more
00276    * circuits.
00277    */
00278   void circuitEstablished();
00279 
00280   /** Indicates that Tor has decided the user's Tor software <b>version</b>
00281    * is no longer recommended for some <b>reason</b>. <b>recommended</b> is
00282    * a list of Tor software versions that are considered current.
00283    */
00284   void dangerousTorVersion(tc::TorVersionStatus reason,
00285                            const QString &version,
00286                            const QStringList &recommended);
00287 
00288   /** Emitted during Tor's startup process to indicate how far in its
00289    * bootstrapping process it has progressed. <b>status</b> may indicate
00290    * the current bootstrapping stage or an error during bootstrapping.
00291    */
00292   void bootstrapStatusChanged(const BootstrapStatus &status);
00293 
00294   /** Emitted when the user attempts to establish a connection to some
00295    * destination on port <b>port</b>, which is a port known to use
00296    * plaintext connections (as determined by Tor's WarnPlaintextPorts and
00297    * RejectPlaintextPorts torrc options). <b>rejected</b> indicates whether
00298    * Tor rejected the connection or permitted it to connect anyway.
00299    */
00300   void dangerousPort(quint16 port, bool rejected);
00301 
00302   /** Emitted when Tor detects a problem with a SOCKS connection from the
00303    * user, such as a bad hostname, dangerous SOCKS protocol type, or a bad
00304    * hostname. <b>type</b> indicates the type of error encountered and
00305    * <b>destination</b> (if non-empty) specifies the attempted connection
00306    * destination address or hostname.
00307    */
00308   void socksError(tc::SocksError type, const QString &destination);
00309 
00310   /** Emitted when Tor decides the client's external IP address has changed
00311    * to <b>ip</b>. If <b>hostname</b> is non-empty, Tor obtained the new
00312    * value for <b>ip</b> by resolving <b>hostname</b>. 
00313    */
00314   void externalAddressChanged(const QHostAddress &ip, const QString &hostname);
00315 
00316   /** Indicates that Tor has determined the client's clock is potentially
00317    * skewed by <b>skew</b> seconds relative to <b>source</b>.
00318    */
00319   void clockSkewed(int skew, const QString &source);
00320 
00321   /** Emitted when Tor has encountered an internal bug. <b>reason</b> is
00322    * Tor's description of the bug.
00323    */
00324   void bug(const QString &reason);
00325 
00326   /** Emitted when Tor determines that the user's DNS provider is providing
00327    * an address for non-existent domains when it should really be saying
00328    * "NXDOMAIN".
00329    */
00330   void dnsHijacked();
00331 
00332   /** Emitted when Tor determines that the user's DNS provider is providing
00333    * a hijacked address even for well-known websites.
00334    */
00335   void dnsUseless();
00336 
00337   /** Indicates Tor has started testing the reachability of its OR port 
00338    * using the IP address <b>ip</b> and port <b>port</b>.
00339    */
00340   void checkingOrPortReachability(const QHostAddress &ip, quint16 port);
00341 
00342   /** Tor has completed testing the reachability of its OR port using
00343    * the IP address <b>ip</b> and port <b>port</b>. If the user's OR port
00344    * was reachable, <b>reachable</b> will be set to true.
00345    */
00346   void orPortReachabilityFinished(const QHostAddress &ip, quint16 port,
00347                                   bool reachable);
00348 
00349   /** Indicates Tor has started testing the reachability of its directory
00350    * port using the IP address <b>ip</b> and port <b>port</b>.
00351    */
00352   void checkingDirPortReachability(const QHostAddress &ip, quint16 port);
00353 
00354   /** Tor has completed testing the reachability of its directory port using
00355    * the IP address <b>ip</b> and port <b>port</b>. If the user's directory
00356    * port was reachable, <b>reachable</b> will be set to true.
00357    */
00358   void dirPortReachabilityFinished(const QHostAddress &ip, quint16 port,
00359                                    bool reachable);
00360 
00361   /** Emitted when the directory authority with IP address <b>ip</b> and
00362    * port <b>port</b> rejected the user's server descriptor. <b>reason</b>
00363    * describes why the descriptor was rejected (e.g., malformed, skewed
00364    * clock, etc.).
00365    */
00366   void serverDescriptorRejected(const QHostAddress &ip, quint16 port,
00367                                 const QString &reason);
00368 
00369   /** Emitted when the directory authority with IP address <b>ip</b> and
00370    * port <b>port</b> accepted the user's server descriptor.
00371    */
00372   void serverDescriptorAccepted(const QHostAddress &ip, quint16 port);
00373 
00374   /** Emitted when at least one directory authority has accepted the user's
00375    * server descriptor.
00376    */
00377   void serverDescriptorAccepted();
00378 
00379 private:
00380   /** Instantiates a connection used to talk to Tor's control port */
00381   ControlConnection* _controlConn;
00382   /** Manages and monitors the Tor process */
00383   TorProcess* _torProcess;
00384   /** Keep track of which events we're interested in */
00385   TorEvents* _eventHandler;
00386   TorEvents::Events _events;
00387   /** The version of Tor we're currently talking to. */
00388   QString _torVersion;
00389   ControlMethod::Method _method;
00390 #if defined(Q_OS_WIN32)
00391   /** Manages the Tor service, if supported and enabled */
00392   TorService* _torService;
00393 #endif
00394 
00395   /** Send a message to Tor and read the response */
00396   bool send(ControlCommand cmd, ControlReply &reply, QString *errmsg = 0);
00397   /** Send a message to Tor and discard the response */
00398   bool send(ControlCommand cmd, QString *errmsg = 0);
00399   /** Tells Tor the controller wants to enable <b>feature</b> via the
00400    * USEFEATURE control command. Returns true if the given feature was
00401    * successfully enabled. */
00402   bool useFeature(const QString &feature, QString *errmsg = 0);
00403 
00404 /* The slots below simply relay signals from the appropriate member objects */
00405 private slots:
00406   void onStopped(int exitCode, QProcess::ExitStatus exitStatus);
00407   void getBootstrapPhase();
00408   void onDisconnected();
00409   void onLogStdout(const QString &severity, const QString &message);
00410   void onAuthenticated();
00411 };
00412 
00413 #endif
00414