2 Copyright (C) 2000 David Faure <faure@kde.org>
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public
6 License as published by the Free Software Foundation; either
7 version 2 of the License, or (at your option) any later version.
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public License
15 along with this library; see the file COPYING.LIB. If not, write to
16 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 Boston, MA 02110-1301, USA.
23 #include <kio/global.h>
24 #include <kio/udsentry.h>
25 #include <kio/authinfo.h>
26 #include <kio/jobclasses.h> // for KIO::JobFlags
29 #include <QtCore/QByteArray>
30 #include <QtNetwork/QHostInfo>
33 class KRemoteEncoding
;
39 class SlaveBasePrivate
;
42 * There are two classes that specifies the protocol between application (job)
43 * and kioslave. SlaveInterface is the class to use on the application end,
44 * SlaveBase is the one to use on the slave end.
46 * Slave implementations should simply inherit SlaveBase
48 * A call to foo() results in a call to slotFoo() on the other end.
50 class KIO_EXPORT SlaveBase
53 SlaveBase( const QByteArray
&protocol
, const QByteArray
&pool_socket
, const QByteArray
&app_socket
);
58 * Terminate the slave by calling the destructor and then ::exit()
68 // Message Signals to send to the job
72 * Sends data in the slave to the job (i.e. in get).
74 * To signal end of data, simply send an empty
77 * @param data the data read by the slave
79 void data( const QByteArray
&data
);
82 * Asks for data from the job.
94 * Call to signal an error.
95 * This also finishes the job, so you must not call
96 * finished() after calling this.
98 * If the error code is KIO::ERR_SLAVE_DEFINED then the
99 * _text should contain the complete translated text of
100 * of the error message.
102 * For all other error codes, _text should match the corresponding
103 * error code. Usually,, _text is a file or host name, or the error which
104 * was passed from the server.<br>
105 * For example, for KIO::ERR_DOES_NOT_EXIST, _text may only
106 * be the file or folder which does not exist, nothing else. Otherwise,
107 * this would break error strings generated by KIO::buildErrorString().<br>
108 * If you have to add more details than what the standard error codes
109 * provide, you'll need to use KIO::ERR_SLAVE_DEFINED.
110 * For a complete list of what _text should contain for each error code,
111 * look at the source of KIO::buildErrorString().
113 * You can add rich text markup to the message, the places where the
114 * error message will be displayed are rich text aware.
117 * @see KIO::buildErrorString
118 * @param _errid the error code from KIO::Error
119 * @param _text the rich text error message
121 void error( int _errid
, const QString
&_text
);
124 * Call in openConnection, if you reimplement it, when you're done.
129 * Call to signal successful completion of any command
130 * besides openConnection and closeConnection. Do not
131 * call this after calling error().
136 * Call to signal that data from the sub-URL is needed
138 void needSubUrlData();
141 * Used to report the status of the slave.
142 * @param host the slave is currently connected to. (Should be
143 * empty if not connected)
144 * @param connected Whether an actual network connection exists.
146 void slaveStatus(const QString
&host
, bool connected
);
149 * Call this from stat() to express details about an object, the
150 * UDSEntry customarily contains the atoms describing file name, size,
152 * @param _entry The UDSEntry containing all of the object attributes.
154 void statEntry( const UDSEntry
& _entry
);
157 * Call this in listDir, each time you have a bunch of entries
159 * @param _entry The UDSEntry containing all of the object attributes.
161 void listEntries( const UDSEntryList
& _entry
);
164 * Call this at the beginning of put(), to give the size of the existing
165 * partial file, if there is one. The @p offset argument notifies the
166 * other job (the one that gets the data) about the offset to use.
167 * In this case, the boolean returns whether we can indeed resume or not
168 * (we can't if the protocol doing the get() doesn't support setting an offset)
170 bool canResume( KIO::filesize_t offset
);
173 * Call this at the beginning of get(), if the "resume" metadata was set
174 * and resuming is implemented by this protocol.
179 // Info Signals to send to the job
183 * Call this in get and copy, to give the total size
185 * Call in listDir too, when you know the total number of items.
187 void totalSize( KIO::filesize_t _bytes
);
189 * Call this during get and copy, once in a while,
190 * to give some info about the current state.
191 * Don't emit it in listDir, listEntries speaks for itself.
193 void processedSize( KIO::filesize_t _bytes
);
195 void position( KIO::filesize_t _pos
);
197 void written( KIO::filesize_t _bytes
);
200 * Only use this if you can't know in advance the size of the
201 * copied data. For example, if you're doing variable bitrate
202 * compression of the source.
204 * STUB ! Currently unimplemented. Here now for binary compatibility.
206 * Call this during get and copy, once in a while,
207 * to give some info about the current state.
208 * Don't emit it in listDir, listEntries speaks for itself.
210 void processedPercent( float percent
);
213 * Call this in get and copy, to give the current transfer
214 * speed, but only if it can't be calculated out of the size you
215 * passed to processedSize (in most cases you don't want to call it)
217 void speed( unsigned long _bytes_per_second
);
220 * Call this to signal a redirection
221 * The job will take care of going to that url.
223 void redirection( const KUrl
&_url
);
226 * Tell that we will only get an error page here.
227 * This means: the data you'll get isn't the data you requested,
228 * but an error page (usually HTML) that describes an error.
233 * Call this in mimetype() and in get(), when you know the mimetype.
234 * See mimetype about other ways to implement it.
236 void mimeType( const QString
&_type
);
239 * Call to signal a warning, to be displayed in a dialog box.
241 void warning( const QString
&msg
);
244 * Call to signal a message, to be displayed if the application wants to,
245 * for instance in a status bar. Usual examples are "connecting to host xyz", etc.
247 void infoMessage( const QString
&msg
);
249 enum MessageBoxType
{ QuestionYesNo
= 1, WarningYesNo
= 2, WarningContinueCancel
= 3, WarningYesNoCancel
= 4, Information
= 5, SSLMessageBox
= 6 };
252 * Call this to show a message box from the slave
253 * @param type type of message box: QuestionYesNo, WarningYesNo, WarningContinueCancel...
254 * @param text Message string. May contain newlines.
255 * @param caption Message box title.
256 * @param buttonYes The text for the first button.
257 * The default is i18n("&Yes").
258 * @param buttonNo The text for the second button.
259 * The default is i18n("&No").
260 * Note: for ContinueCancel, buttonYes is the continue button and buttonNo is unused.
261 * and for Information, none is used.
262 * @return a button code, as defined in KMessageBox, or 0 on communication error.
264 int messageBox( MessageBoxType type
, const QString
&text
,
265 const QString
&caption
= QString(),
266 const QString
&buttonYes
= i18n("&Yes"),
267 const QString
&buttonNo
= i18n("&No"));
270 * Call this to show a message box from the slave
271 * @param text Message string. May contain newlines.
272 * @param type type of message box: QuestionYesNo, WarningYesNo, WarningContinueCancel...
273 * @param caption Message box title.
274 * @param buttonYes The text for the first button.
275 * The default is i18n("&Yes").
276 * @param buttonNo The text for the second button.
277 * The default is i18n("&No").
278 * Note: for ContinueCancel, buttonYes is the continue button and buttonNo is unused.
279 * and for Information, none is used.
280 * @param dontAskAgain A checkbox is added with which further confirmation can be turned off.
281 * If the checkbox was ticked @p*dontAskAgain will be set to true, otherwise false.
282 * @return a button code, as defined in KMessageBox, or 0 on communication error.
284 int messageBox( const QString
&text
, MessageBoxType type
,
285 const QString
&caption
= QString(),
286 const QString
&buttonYes
= i18n("&Yes"),
287 const QString
&buttonNo
= i18n("&No"),
288 const QString
&dontAskAgainName
= QString() );
291 * Sets meta-data to be send to the application before the first
292 * data() or finished() signal.
294 void setMetaData(const QString
&key
, const QString
&value
);
297 * Queries for the existence of a certain config/meta-data entry
298 * send by the application to the slave.
300 bool hasMetaData(const QString
&key
) const;
303 * Queries for config/meta-data send by the application to the slave.
305 QString
metaData(const QString
&key
) const;
309 * @internal for ForwardingSlaveBase
310 * Contains all metadata (but no config) sent by the application to the slave.
312 MetaData
allMetaData() const;
315 * Returns a configuration object to query config/meta-data information
318 * The application provides the slave with all configuration information
319 * relevant for the current protocol and host.
321 KConfigGroup
* config();
324 * Returns an object that can translate remote filenames into proper
325 * Unicode forms. This encoding can be set by the user.
327 KRemoteEncoding
* remoteEncoding();
331 // Commands sent by the job, the slave has to
332 // override what it wants to implement
341 * Called directly by createSlave, this is why there is no equivalent in
342 * SlaveInterface, unlike the other methods.
344 * This method is called whenever a change in host, port or user occurs.
346 virtual void setHost(const QString
& host
, quint16 port
, const QString
& user
, const QString
& pass
);
349 * Prepare slave for streaming operation
351 virtual void setSubUrl(const KUrl
&url
);
354 * Opens the connection (forced)
355 * When this function gets called the slave is operating in
356 * connection-oriented mode.
357 * When a connection gets lost while the slave operates in
358 * connection oriented mode, the slave should report
359 * ERR_CONNECTION_BROKEN instead of reconnecting. The user is
360 * expected to disconnect the slave in the error handler.
362 virtual void openConnection();
365 * Closes the connection (forced)
366 * Called when the application disconnects the slave to close
367 * any open network connections.
369 * When the slave was operating in connection-oriented mode,
370 * it should reset itself to connectionless (default) mode.
372 virtual void closeConnection();
376 * @param url the full url for this request. Host, port and user of the URL
377 * can be assumed to be the same as in the last setHost() call.
378 * The slave should first emit mimeType(), and then emit the data using the data() method.
380 virtual void get( const KUrl
& url
);
384 * @param url the full url for this request. Host, port and user of the URL
385 * can be assumed to be the same as in the last setHost() call.
386 * @param mode see \ref QIODevice::OpenMode
388 virtual void open( const KUrl
&url
, QIODevice::OpenMode mode
);
390 virtual void read( KIO::filesize_t size
);
391 virtual void write( const QByteArray
&data
);
392 virtual void seek( KIO::filesize_t offset
);
393 virtual void close();
396 * put, i.e. write data into a file.
398 * @param url where to write the file
399 * @param permissions may be -1. In this case no special permission mode is set.
400 * @param flags: We support Overwrite here. Hopefully, we're going to
401 * support Resume in the future, too.
402 * If the file indeed already exists, the slave should NOT apply the
403 * permissions change to it.
404 * The support for resuming using .part files is done by calling canResume().
406 * IMPORTANT: Use the "modified" metadata in order to set the modification time of the file.
410 virtual void put( const KUrl
& url
, int permissions
, JobFlags flags
);
413 * Finds all details for one file or directory.
414 * The information returned is the same as what listDir returns,
415 * but only for one file or directory.
416 * Call statEntry() after creating the appropriate UDSEntry for this
419 * You can use the "details" metadata to optimize this method to only
420 * do as much work as needed by the application.
421 * By default details is 2 (all details wanted, including modification time, size, etc.),
422 * details==1 is used when deleting: we don't need all the information if it takes
423 * too much time, no need to follow symlinks etc.
424 * details==0 is used for very simple probing: we'll only get the answer
425 * "it's a file or a directory (or a symlink), or it doesn't exist".
427 virtual void stat( const KUrl
& url
);
430 * Finds mimetype for one file or directory.
432 * This method should either emit 'mimeType' or it
433 * should send a block of data big enough to be able
434 * to determine the mimetype.
436 * If the slave doesn't reimplement it, a get will
437 * be issued, i.e. the whole file will be downloaded before
438 * determining the mimetype on it - this is obviously not a
439 * good thing in most cases.
441 virtual void mimetype( const KUrl
& url
);
444 * Lists the contents of @p url.
445 * The slave should emit ERR_CANNOT_ENTER_DIRECTORY if it doesn't exist,
446 * if we don't have enough permissions, or if it is a file
447 * It should also emit totalFiles as soon as it knows how many
448 * files it will list.
450 virtual void listDir( const KUrl
& url
);
454 * @param url path to the directory to create
455 * @param permissions the permissions to set after creating the directory
456 * (-1 if no permissions to be set)
457 * The slave emits ERR_COULD_NOT_MKDIR if failure.
459 virtual void mkdir( const KUrl
&url
, int permissions
);
462 * Rename @p oldname into @p newname.
463 * If the slave returns an error ERR_UNSUPPORTED_ACTION, the job will
464 * ask for copy + del instead.
466 * Important: the slave must implement the logic "if the destination already
467 * exists, error ERR_DIR_ALREADY_EXIST or ERR_FILE_ALREADY_EXIST".
468 * For performance reasons no stat is done in the destination before hand,
469 * the slave must do it.
471 * @param src where to move the file from
472 * @param dest where to move the file to
473 * @param flags: We support Overwrite here
475 virtual void rename( const KUrl
& src
, const KUrl
& dest
, JobFlags flags
);
478 * Creates a symbolic link named @p dest, pointing to @p target, which
479 * may be a relative or an absolute path.
480 * @param target The string that will become the "target" of the link (can be relative)
481 * @param dest The symlink to create.
482 * @param flags: We support Overwrite here
484 virtual void symlink( const QString
& target
, const KUrl
& dest
, JobFlags flags
);
487 * Change permissions on @p url
488 * The slave emits ERR_DOES_NOT_EXIST or ERR_CANNOT_CHMOD
490 virtual void chmod( const KUrl
& url
, int permissions
);
493 * Change ownership of @p url
494 * The slave emits ERR_DOES_NOT_EXIST or ERR_CANNOT_CHOWN
496 virtual void chown( const KUrl
& url
, const QString
& owner
, const QString
& group
);
499 * Sets the modification time for @url
500 * For instance this is what CopyJob uses to set mtime on dirs at the end of a copy.
501 * It could also be used to set the mtime on any file, in theory.
502 * The usual implementation on unix is to call utime(path, &myutimbuf).
503 * The slave emits ERR_DOES_NOT_EXIST or ERR_CANNOT_SETTIME
505 virtual void setModificationTime( const KUrl
& url
, const QDateTime
& mtime
);
508 * Copy @p src into @p dest.
509 * If the slave returns an error ERR_UNSUPPORTED_ACTION, the job will
510 * ask for get + put instead.
511 * @param src where to copy the file from (decoded)
512 * @param dest where to copy the file to (decoded)
513 * @param permissions may be -1. In this case no special permission mode is set.
514 * @param flags: We support Overwrite here
516 * Don't forget to set the modification time of @p dest to be the modification time of @p src.
518 virtual void copy( const KUrl
&src
, const KUrl
&dest
, int permissions
, JobFlags flags
);
521 * Delete a file or directory.
522 * @param url file/directory to delete
523 * @param isfile if true, a file should be deleted.
524 * if false, a directory should be deleted.
526 virtual void del( const KUrl
&url
, bool isfile
);
528 // TODO KDE4: use setLinkDest for kio_file but also kio_remote (#97129)
529 // For kio_file it's the same as del+symlink, but for kio_remote it allows
530 // to keep the icon etc.
533 * Change the destination of a symlink
534 * @param url the url of the symlink to modify
535 * @param target the new destination (target) of the symlink
537 virtual void setLinkDest( const KUrl
& url
, const QString
& target
);
540 * Used for any command that is specific to this slave (protocol)
541 * Examples are : HTTP POST, mount and unmount (kio_file)
543 * @param data packed data; the meaning is completely dependent on the
544 * slave, but usually starts with an int for the command number.
545 * Document your slave's commands, at least in its header file.
547 virtual void special( const QByteArray
& data
);
550 * Used for multiple get. Currently only used foir HTTP pielining
553 * @param data packed data; Contains number of URLs to fetch, and for
554 * each URL the URL itself and its associated MetaData.
556 virtual void multiGet( const QByteArray
& data
);
559 * Called to get the status of the slave. Slave should respond
560 * by calling slaveStatus(...)
562 virtual void slave_status();
565 * Called by the scheduler to tell the slave that the configuration
566 * changed (i.e. proxy settings) .
568 virtual void reparseConfiguration();
572 * @return timeout value for connecting to remote host.
574 int connectTimeout();
577 * @return timeout value for connecting to proxy in secs.
579 int proxyConnectTimeout();
582 * @return timeout value for read from first data from
583 * remote host in seconds.
585 int responseTimeout();
588 * @return timeout value for read from subsequent data from
589 * remote host in secs.
594 * This function sets a timeout of @p timeout seconds and calls
595 * special(data) when the timeout occurs as if it was called by the
598 * A timeout can only occur when the slave is waiting for a command
599 * from the application.
601 * Specifying a negative timeout cancels a pending timeout.
603 * Only one timeout at a time is supported, setting a timeout
604 * cancels any pending timeout.
606 void setTimeoutSpecialCommand(int timeout
, const QByteArray
&data
=QByteArray());
609 // Dispatching (internal)
615 virtual void dispatch( int command
, const QByteArray
&data
);
620 virtual void dispatchOpenCommand( int command
, const QByteArray
&data
);
623 * Read data sent by the job, after a dataReq
625 * @param buffer buffer where data is stored
626 * @return 0 on end of data,
630 int readData( QByteArray
&buffer
);
633 * internal function to be called by the slave.
634 * It collects entries and emits them via listEntries
635 * when enough of them are there or a certain time
636 * frame exceeded (to make sure the app gets some
637 * items in time but not too many items one by one
638 * as this will cause a drastic performance penalty)
639 * @param _entry The UDSEntry containing all of the object attributes.
640 * @param ready set to true after emitting all items. @p _entry is not
643 void listEntry( const UDSEntry
& _entry
, bool ready
);
646 * internal function to connect a slave to/ disconnect from
647 * either the slave pool or the application
649 void connectSlave(const QString
& path
);
650 void disconnectSlave();
653 * Prompt the user for Authorization info (login & password).
655 * Use this function to request authorization information from
656 * the end user. You can also pass an error message which explains
657 * why a previous authorization attempt failed. Here is a very
661 * KIO::AuthInfo authInfo;
662 * if ( openPasswordDialog( authInfo ) )
664 * kDebug() << QLatin1String("User: ")
665 * << authInfo.username << endl;
666 * kDebug() << QLatin1String("Password: ")
667 * << QLatin1String("Not displayed here!") << endl;
671 * You can also preset some values like the username, caption or
672 * comment as follows:
675 * KIO::AuthInfo authInfo;
676 * authInfo.caption= "Acme Password Dialog";
677 * authInfo.username= "Wile E. Coyote";
678 * QString errorMsg = "You entered an incorrect password.";
679 * if ( openPasswordDialog( authInfo, errorMsg ) )
681 * kDebug() << QLatin1String("User: ")
682 * << authInfo.username << endl;
683 * kDebug() << QLatin1String("Password: ")
684 * << QLatin1String("Not displayed here!") << endl;
688 * \note You should consider using checkCachedAuthentication() to
689 * see if the password is available in kpasswdserver before calling
692 * \note A call to this function can fail and return @p false,
693 * if the UIServer could not be started for whatever reason.
695 * @see checkCachedAuthentication
696 * @param info See AuthInfo.
697 * @param errorMsg Error message to show
698 * @return @p true if user clicks on "OK", @p false otherwsie.
700 bool openPasswordDialog( KIO::AuthInfo
& info
, const QString
&errorMsg
= QString() );
703 * Checks for cached authentication based on parameters
706 * Use this function to check if any cached password exists
707 * for the URL given by @p info. If @p AuthInfo::realmValue
708 * and/or @p AuthInfo::verifyPath flag is specified, then
709 * they will also be factored in determining the presence
710 * of a cached password. Note that @p Auth::url is a required
711 * parameter when attempting to check for cached authorization
712 * info. Here is a simple example:
716 * info.url = KUrl("http://www.foobar.org/foo/bar");
717 * info.username = "somename";
718 * info.verifyPath = true;
719 * if ( !checkCachedAuthentication( info ) )
721 * if ( !openPasswordDialog(info) )
726 * @param info See AuthInfo.
727 * @return @p true if cached Authorization is found, false otherwise.
729 bool checkCachedAuthentication( AuthInfo
& info
);
732 * Explicitly store authentication information. openPasswordDialog already
733 * stores password information automatically, you only need to call
734 * this function if you want to store authentication information that
735 * is different from the information returned by openPasswordDialog.
737 bool cacheAuthentication( const AuthInfo
& info
);
740 * Used by the slave to check if it can connect
741 * to a given host. This should be called where the slave is ready
742 * to do a ::connect() on a socket. For each call to
743 * requestNetwork must exist a matching call to
744 * dropNetwork, or the system will stay online until
745 * KNetMgr gets closed (or the SlaveBase gets destructed)!
747 * If KNetMgr is not running, then this is a no-op and returns true
749 * @param host tells the netmgr the host the slave wants to connect
750 * to. As this could also be a proxy, we can't just take
751 * the host currenctly connected to (but that's the default
754 * @return true in theorie, the host is reachable
755 * false the system is offline and the host is in a remote network.
757 bool requestNetwork(const QString
& host
= QString());
760 * Used by the slave to withdraw a connection requested by
761 * requestNetwork. This function cancels the last call to
762 * requestNetwork. If a client uses more than one internet
763 * connection, it must use dropNetwork(host) to
766 * If KNetMgr is not running, then this is a no-op.
768 * @param host the host passed to requestNetwork
770 * A slave should call this function every time it disconnect from a host.
772 void dropNetwork(const QString
& host
= QString());
775 * Wait for an answer to our request, until we get @p expected1 or @p expected2
776 * @return the result from readData, as well as the cmd in *pCmd if set, and the data in @p data
778 int waitForAnswer( int expected1
, int expected2
, QByteArray
& data
, int * pCmd
= 0 );
781 * Internal function to transmit meta data to the application.
782 * m_outgoingMetaData will be cleared; this means that if the slave is for
783 * example put on hold and picked up by a different KIO::Job later the new
784 * job will not see the metadata sent before.
785 * See kio/DESIGN.krun for an overview of the state
786 * progression of a job/slave.
787 * @warning calling this method may seriously interfere with the operation
788 * of KIO which relies on the presence of some metadata at some points in time.
789 * You should not use it if you are not familiar with KIO and not before
790 * the slave is connected to the last job before returning to idle state.
795 * Internal function to transmit meta data to the application.
796 * Like sendMetaData() but m_outgoingMetaData will not be cleared.
797 * This method is mainly useful in code that runs before the slave is connected
800 void sendAndKeepMetaData();
802 /** If your ioslave was killed by a signal, wasKilled() returns true.
803 Check it regularly in lengthy functions (e.g. in get();) and return
804 as fast as possible from this function if wasKilled() returns true.
805 This will ensure that your slave destructor will be called correctly.
807 bool wasKilled() const;
817 void lookupHost(const QString
& host
);
822 int waitForHostInfo(QHostInfo
& info
);
826 * Name of the protocol supported by this slave
828 QByteArray mProtocol
;
829 //Often used by TcpSlaveBase and unlikely to change
830 MetaData mOutgoingMetaData
;
831 MetaData mIncomingMetaData
;
833 virtual void virtual_hook( int id
, void* data
);
836 void send(int cmd
, const QByteArray
& arr
= QByteArray());
837 SlaveBasePrivate
* const d
;
838 friend class SlaveBasePrivate
;