KIO

slavebase.h
1/*
2 SPDX-FileCopyrightText: 2000 David Faure <faure@kde.org>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5*/
6
7#ifndef SLAVEBASE_H
8#define SLAVEBASE_H
9
10#include "job_base.h" // for KIO::JobFlags
11#include <kio/authinfo.h>
12#include <kio/global.h>
13#include <kio/udsentry.h>
14
15#include <QByteArray>
16#include <QHostInfo>
17#include <QSsl>
18
19#include <memory>
20
21class KConfigGroup;
22class KRemoteEncoding;
23class QUrl;
24
25namespace KIO
26{
27class Connection;
28class SlaveBasePrivate;
29
30// TODO: Enable once file KIO worker is ported away and add endif, similar in the cpp file
31// #if KIOCORE_ENABLE_DEPRECATED_SINCE(version where file:/ KIO worker was ported)
32
33/**
34 * @class KIO::SlaveBase slavebase.h <KIO/SlaveBase>
35 *
36 * There are two classes that specifies the protocol between application (job)
37 * and kioslave. SlaveInterface is the class to use on the application end,
38 * SlaveBase is the one to use on the slave end.
39 *
40 * Slave implementations should simply inherit SlaveBase
41 *
42 * A call to foo() results in a call to slotFoo() on the other end.
43 *
44 * Note that a kioslave doesn't have a Qt event loop. When idle, it's waiting for a command
45 * on the socket that connects it to the application. So don't expect a kioslave to react
46 * to D-Bus signals for instance. KIOSlaves are short-lived anyway, so any kind of watching
47 * or listening for notifications should be done elsewhere, for instance in a kded module
48 * (see kio_desktop's desktopnotifier.cpp for an example).
49 *
50 * If a kioslave needs a Qt event loop within the implementation of one method, e.g. to
51 * wait for an asynchronous operation to finish, that is possible, using QEventLoop.
52 *
53 * @deprecated Since 5.96, use WorkerBase.
54 */
55class SlaveBase
56{
57public:
58 KIOCORE_DEPRECATED_VERSION_BELATED(5, 101, 5, 96, "Use WorkerBase")
59 SlaveBase(const QByteArray &protocol, const QByteArray &pool_socket, const QByteArray &app_socket);
60 virtual ~SlaveBase();
61
62 /**
63 * @internal
64 * Terminate the slave by calling the destructor and then ::exit()
65 */
66 void exit();
67
68 /**
69 * @internal
70 */
71 void dispatchLoop();
72
73 ///////////
74 // Message Signals to send to the job
75 ///////////
76
77 /**
78 * Sends data in the slave to the job (i.e.\ in get).
79 *
80 * To signal end of data, simply send an empty
81 * QByteArray().
82 *
83 * @param data the data read by the slave
84 */
85 void data(const QByteArray &data);
86
87 /**
88 * Asks for data from the job.
89 * @see readData
90 */
91 void dataReq();
92
93 /**
94 * open succeeds
95 * @see open()
96 */
97 void opened();
98
99 /**
100 * Call to signal an error.
101 * This also finishes the job, so you must not call
102 * finished() after calling this.
103 *
104 * If the error code is KIO::ERR_SLAVE_DEFINED then the
105 * _text should contain the complete translated text of
106 * of the error message.
107 *
108 * For all other error codes, _text should match the corresponding
109 * error code. Usually, _text is a file or host name, or the error which
110 * was passed from the server.<br>
111 * For example, for KIO::ERR_DOES_NOT_EXIST, _text may only
112 * be the file or folder which does not exist, nothing else. Otherwise,
113 * this would break error strings generated by KIO::buildErrorString().<br>
114 * If you have to add more details than what the standard error codes
115 * provide, you'll need to use KIO::ERR_SLAVE_DEFINED.
116 * For a complete list of what _text should contain for each error code,
117 * look at the source of KIO::buildErrorString().
118 *
119 * You can add rich text markup to the message, the places where the
120 * error message will be displayed are rich text aware.
121 *
122 * @see KIO::Error
123 * @see KIO::buildErrorString
124 * @param _errid the error code from KIO::Error
125 * @param _text the rich text error message
126 */
127 void error(int _errid, const QString &_text);
128
129 /**
130 * Call in openConnection, if you reimplement it, when you're done.
131 */
132 void connected();
133
134 /**
135 * Call to signal successful completion of any command
136 * besides openConnection and closeConnection. Do not
137 * call this after calling error().
138 */
139 void finished();
140
141 /**
142 * Used to report the status of the slave.
143 * @param host the slave is currently connected to. (Should be
144 * empty if not connected)
145 * @param connected Whether an actual network connection exists.
146 **/
147 void slaveStatus(const QString &host, bool connected);
148
149 /**
150 * Call this from stat() to express details about an object, the
151 * UDSEntry customarily contains the atoms describing file name, size,
152 * MIME type, etc.
153 * @param _entry The UDSEntry containing all of the object attributes.
154 */
155 void statEntry(const UDSEntry &_entry);
156
157 /**
158 * Call this in listDir, each time you have a bunch of entries
159 * to report.
160 * @param _entry The UDSEntry containing all of the object attributes.
161 */
162 void listEntries(const UDSEntryList &_entry);
163
164 /**
165 * Call this at the beginning of put(), to give the size of the existing
166 * partial file, if there is one. The @p offset argument notifies the
167 * other job (the one that gets the data) about the offset to use.
168 * In this case, the boolean returns whether we can indeed resume or not
169 * (we can't if the protocol doing the get() doesn't support setting an offset)
170 */
171 bool canResume(KIO::filesize_t offset);
172
173 /**
174 * Call this at the beginning of get(), if the "range-start" metadata was set
175 * and returning byte ranges is implemented by this protocol.
176 */
177 void canResume();
178
179 ///////////
180 // Info Signals to send to the job
181 ///////////
182
183 /**
184 * Call this in get and copy, to give the total size
185 * of the file.
186 */
187 void totalSize(KIO::filesize_t _bytes);
188 /**
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.
192 */
193 void processedSize(KIO::filesize_t _bytes);
194
195 void position(KIO::filesize_t _pos);
196
197 void written(KIO::filesize_t _bytes);
198
199 /**
200 * @since 5.66
201 */
202 void truncated(KIO::filesize_t _length);
203
204 /**
205 * Only use this if you can't know in advance the size of the
206 * copied data. For example, if you're doing variable bitrate
207 * compression of the source.
208 *
209 * STUB ! Currently unimplemented. Here now for binary compatibility.
210 *
211 * Call this during get and copy, once in a while,
212 * to give some info about the current state.
213 * Don't emit it in listDir, listEntries speaks for itself.
214 */
215 void processedPercent(float percent); // KF6 TODO REMOVE
216
217 /**
218 * Call this in get and copy, to give the current transfer
219 * speed, but only if it can't be calculated out of the size you
220 * passed to processedSize (in most cases you don't want to call it)
221 */
222 void speed(unsigned long _bytes_per_second);
223
224 /**
225 * Call this to signal a redirection.
226 * The job will take care of going to that url.
227 */
228 void redirection(const QUrl &_url);
229
230 /**
231 * Call this in mimetype() and in get(), when you know the MIME type.
232 * See mimetype() about other ways to implement it.
233 */
234 void mimeType(const QString &_type);
235
236 /**
237 * Call to signal a warning, to be displayed in a dialog box.
238 */
239 void warning(const QString &msg);
240
241 /**
242 * Call to signal a message, to be displayed if the application wants to,
243 * for instance in a status bar. Usual examples are "connecting to host xyz", etc.
244 */
245 void infoMessage(const QString &msg);
246
247 /**
248 * Type of message box. Should be kept in sync with KMessageBox::DialogType.
249 */
251 QuestionTwoActions = 1, ///< @since 5.100
252 WarningTwoActions = 2, ///< @since 5.100
253 WarningContinueCancel = 3,
254 WarningTwoActionsCancel = 4, ///< @since 5.100
255 Information = 5,
256 // In KMessageBox::DialogType; <unused> = 7, Error = 8, QuestionTwoActionsCancel = 9
257 WarningContinueCancelDetailed = 10,
258 };
259
260 /**
261 * Button codes. Should be kept in sync with KMessageBox::ButtonCode
262 */
264 Ok = 1,
265 Cancel = 2,
266 PrimaryAction = 3, ///< @since 5.100
267 SecondaryAction = 4, ///< @since 5.100
268 Continue = 5,
269 };
270
271 /**
272 * Call this to show a message box from the slave
273 * @param type type of message box: QuestionTwoActions, WarningTwoActions, WarningContinueCancel...
274 * @param text Message string. May contain newlines.
275 * @param title Message box title.
276 * @param primaryActionText the text for the first button.
277 * Ignored for @p type Information & SSLMessageBox.
278 * @param secondaryActionText the text for the second button.
279 * Ignored for @p type WarningContinueCancel, WarningContinueCancelDetailed,
280 * Information & SSLMessageBox.
281 * @return a button code, as defined in ButtonCode, or 0 on communication error.
282 */
283 int messageBox(MessageBoxType type,
284 const QString &text,
285 const QString &title = QString(),
286 const QString &primaryActionText = QString(),
287 const QString &secondaryActionText = QString());
288
289 int sslError(const QVariantMap &sslData);
290
291 /**
292 * Call this to show a message box from the slave
293 * @param text Message string. May contain newlines.
294 * @param type type of message box: QuestionTwoActions, WarningTwoActions, WarningContinueCancel...
295 * @param title Message box title.
296 * @param primaryActionText the text for the first button.
297 * Ignored for @p type Information & SSLMessageBox.
298 * @param secondaryActionText the text for the second button.
299 * Ignored for @p type WarningContinueCancel, WarningContinueCancelDetailed,
300 * Information & SSLMessageBox.
301 * @param dontAskAgainName the name used to store result from 'Do not ask again' checkbox.
302 * @return a button code, as defined in ButtonCode, or 0 on communication error.
303 */
304 int messageBox(const QString &text,
305 MessageBoxType type,
306 const QString &title = QString(),
307 const QString &primaryActionText = QString(),
308 const QString &secondaryActionText = QString(),
309 const QString &dontAskAgainName = QString());
310
311 /**
312 * Sets meta-data to be send to the application before the first
313 * data() or finished() signal.
314 */
315 void setMetaData(const QString &key, const QString &value);
316
317 /**
318 * Queries for the existence of a certain config/meta-data entry
319 * send by the application to the slave.
320 */
321 bool hasMetaData(const QString &key) const;
322
323 /**
324 * Queries for config/meta-data send by the application to the slave.
325 */
326 QString metaData(const QString &key) const;
327
328 /**
329 * @internal for ForwardingSlaveBase
330 * Contains all metadata (but no config) sent by the application to the slave.
331 */
332 MetaData allMetaData() const;
333
334 /**
335 * Returns a map to query config/meta-data information from.
336 *
337 * The application provides the slave with all configuration information
338 * relevant for the current protocol and host.
339 *
340 * Use configValue() as shortcut.
341 * @since 5.64
342 */
344
345 /**
346 * Returns a bool from the config/meta-data information.
347 * @since 5.64
348 */
349 bool configValue(const QString &key, bool defaultValue) const;
350
351 /**
352 * Returns an int from the config/meta-data information.
353 * @since 5.64
354 */
355 int configValue(const QString &key, int defaultValue) const;
356
357 /**
358 * Returns a QString from the config/meta-data information.
359 * @since 5.64
360 */
361 QString configValue(const QString &key, const QString &defaultValue = QString()) const;
362
363 /**
364 * Returns a configuration object to query config/meta-data information
365 * from.
366 *
367 * The application provides the slave with all configuration information
368 * relevant for the current protocol and host.
369 *
370 * @note Since 5.64 prefer to use mapConfig() or one of the configValue(...) overloads.
371 * @todo Find replacements for the other current usages of this method.
372 */
374 // KF6: perhaps rename mapConfig() to config() when removing this
375
376 /**
377 * Returns an object that can translate remote filenames into proper
378 * Unicode forms. This encoding can be set by the user.
379 */
381
382 ///////////
383 // Commands sent by the job, the slave has to
384 // override what it wants to implement
385 ///////////
386
387 /**
388 * Set the host
389 *
390 * Called directly by createWorker, this is why there is no equivalent in
391 * SlaveInterface, unlike the other methods.
392 *
393 * This method is called whenever a change in host, port or user occurs.
394 */
395 virtual void setHost(const QString &host, quint16 port, const QString &user, const QString &pass);
396
397 /**
398 * Opens the connection (forced).
399 *
400 * When this function gets called the slave is operating in
401 * connection-oriented mode.
402 * When a connection gets lost while the slave operates in
403 * connection oriented mode, the slave should report
404 * ERR_CONNECTION_BROKEN instead of reconnecting. The user is
405 * expected to disconnect the slave in the error handler.
406 */
407 virtual void openConnection();
408
409 /**
410 * Closes the connection (forced).
411 *
412 * Called when the application disconnects the slave to close
413 * any open network connections.
414 *
415 * When the slave was operating in connection-oriented mode,
416 * it should reset itself to connectionless (default) mode.
417 */
418 virtual void closeConnection();
419
420 /**
421 * get, aka read.
422 * @param url the full url for this request. Host, port and user of the URL
423 * can be assumed to be the same as in the last setHost() call.
424 *
425 * The slave should first "emit" the MIME type by calling mimeType(),
426 * and then "emit" the data using the data() method.
427 *
428 * The reason why we need get() to emit the MIME type is:
429 * when pasting a URL in krunner, or konqueror's location bar,
430 * we have to find out what is the MIME type of that URL.
431 * Rather than doing it with a call to mimetype(), then the app or part
432 * would have to do a second request to the same server, this is done
433 * like this: get() is called, and when it emits the MIME type, the job
434 * is put on hold and the right app or part is launched. When that app
435 * or part calls get(), the slave is magically reused, and the download
436 * can now happen. All with a single call to get() in the slave.
437 * This mechanism is also described in KIO::get().
438 */
439 virtual void get(const QUrl &url);
440
441 /**
442 * open.
443 * @param url the full url for this request. Host, port and user of the URL
444 * can be assumed to be the same as in the last setHost() call.
445 * @param mode see \ref QIODevice::OpenMode
446 */
447 virtual void open(const QUrl &url, QIODevice::OpenMode mode);
448
449 /**
450 * read.
451 * @param size the requested amount of data to read
452 * @see KIO::FileJob::read()
453 */
454 virtual void read(KIO::filesize_t size);
455 /**
456 * write.
457 * @param data the data to write
458 * @see KIO::FileJob::write()
459 */
460 virtual void write(const QByteArray &data);
461 /**
462 * seek.
463 * @param offset the requested amount of data to read
464 * @see KIO::FileJob::read()
465 */
466 virtual void seek(KIO::filesize_t offset);
467 /**
468 * close.
469 * @see KIO::FileJob::close()
470 */
471 virtual void close();
472
473 /**
474 * put, i.e.\ write data into a file.
475 *
476 * @param url where to write the file
477 * @param permissions may be -1. In this case no special permission mode is set.
478 * @param flags We support Overwrite here. Hopefully, we're going to
479 * support Resume in the future, too.
480 * If the file indeed already exists, the slave should NOT apply the
481 * permissions change to it.
482 * The support for resuming using .part files is done by calling canResume().
483 *
484 * IMPORTANT: Use the "modified" metadata in order to set the modification time of the file.
485 *
486 * @see canResume()
487 */
488 virtual void put(const QUrl &url, int permissions, JobFlags flags);
489
490 /**
491 * Finds all details for one file or directory.
492 * The information returned is the same as what listDir returns,
493 * but only for one file or directory.
494 * Call statEntry() after creating the appropriate UDSEntry for this
495 * url.
496 *
497 * You can use the "details" metadata to optimize this method to only
498 * do as much work as needed by the application.
499 * By default details is 2 (all details wanted, including modification time, size, etc.),
500 * details==1 is used when deleting: we don't need all the information if it takes
501 * too much time, no need to follow symlinks etc.
502 * details==0 is used for very simple probing: we'll only get the answer
503 * "it's a file or a directory (or a symlink), or it doesn't exist".
504 */
505 virtual void stat(const QUrl &url);
506
507 /**
508 * Finds MIME type for one file or directory.
509 *
510 * This method should either emit 'mimeType' or it
511 * should send a block of data big enough to be able
512 * to determine the MIME type.
513 *
514 * If the slave doesn't reimplement it, a get will
515 * be issued, i.e. the whole file will be downloaded before
516 * determining the MIME type on it - this is obviously not a
517 * good thing in most cases.
518 */
519 virtual void mimetype(const QUrl &url);
520
521 /**
522 * Lists the contents of @p url.
523 * The slave should emit ERR_CANNOT_ENTER_DIRECTORY if it doesn't exist,
524 * if we don't have enough permissions.
525 * You should not list files if the path in @p url is empty, but redirect
526 * to a non-empty path instead.
527 */
528 virtual void listDir(const QUrl &url);
529
530 /**
531 * Create a directory
532 * @param url path to the directory to create
533 * @param permissions the permissions to set after creating the directory
534 * (-1 if no permissions to be set)
535 * The slave emits ERR_CANNOT_MKDIR if failure.
536 */
537 virtual void mkdir(const QUrl &url, int permissions);
538
539 /**
540 * Rename @p oldname into @p newname.
541 * If the slave returns an error ERR_UNSUPPORTED_ACTION, the job will
542 * ask for copy + del instead.
543 *
544 * Important: the slave must implement the logic "if the destination already
545 * exists, error ERR_DIR_ALREADY_EXIST or ERR_FILE_ALREADY_EXIST".
546 * For performance reasons no stat is done in the destination before hand,
547 * the slave must do it.
548 *
549 * By default, rename() is only called when renaming (moving) from
550 * yourproto://host/path to yourproto://host/otherpath.
551 *
552 * If you set renameFromFile=true then rename() will also be called when
553 * moving a file from file:///path to yourproto://host/otherpath.
554 * Otherwise such a move would have to be done the slow way (copy+delete).
555 * See KProtocolManager::canRenameFromFile() for more details.
556 *
557 * If you set renameToFile=true then rename() will also be called when
558 * moving a file from yourproto: to file:.
559 * See KProtocolManager::canRenameToFile() for more details.
560 *
561 * @param src where to move the file from
562 * @param dest where to move the file to
563 * @param flags We support Overwrite here
564 */
565 virtual void rename(const QUrl &src, const QUrl &dest, JobFlags flags);
566
567 /**
568 * Creates a symbolic link named @p dest, pointing to @p target, which
569 * may be a relative or an absolute path.
570 * @param target The string that will become the "target" of the link (can be relative)
571 * @param dest The symlink to create.
572 * @param flags We support Overwrite here
573 */
574 virtual void symlink(const QString &target, const QUrl &dest, JobFlags flags);
575
576 /**
577 * Change permissions on @p url.
578 *
579 * The slave emits ERR_DOES_NOT_EXIST or ERR_CANNOT_CHMOD
580 */
581 virtual void chmod(const QUrl &url, int permissions);
582
583 /**
584 * Change ownership of @p url.
585 *
586 * The slave emits ERR_DOES_NOT_EXIST or ERR_CANNOT_CHOWN
587 */
588 virtual void chown(const QUrl &url, const QString &owner, const QString &group);
589
590 /**
591 * Sets the modification time for @p url.
592 *
593 * For instance this is what CopyJob uses to set mtime on dirs at the end of a copy.
594 * It could also be used to set the mtime on any file, in theory.
595 * The usual implementation on unix is to call utime(path, &myutimbuf).
596 * The slave emits ERR_DOES_NOT_EXIST or ERR_CANNOT_SETTIME
597 */
598 virtual void setModificationTime(const QUrl &url, const QDateTime &mtime);
599
600 /**
601 * Copy @p src into @p dest.
602 *
603 * By default, copy() is only called when copying a file from
604 * yourproto://host/path to yourproto://host/otherpath.
605 *
606 * If you set copyFromFile=true then copy() will also be called when
607 * moving a file from file:///path to yourproto://host/otherpath.
608 * Otherwise such a copy would have to be done the slow way (get+put).
609 * See also KProtocolManager::canCopyFromFile().
610 *
611 * If you set copyToFile=true then copy() will also be called when
612 * moving a file from yourproto: to file:.
613 * See also KProtocolManager::canCopyToFile().
614 *
615 * If the slave returns an error ERR_UNSUPPORTED_ACTION, the job will
616 * ask for get + put instead.
617 *
618 * If the slave returns an error ERR_FILE_ALREADY_EXIST, the job will
619 * ask for a different destination filename.
620 *
621 * @param src where to copy the file from (decoded)
622 * @param dest where to copy the file to (decoded)
623 * @param permissions may be -1. In this case no special permission mode is set,
624 * and the owner and group permissions are not preserved.
625 * @param flags We support Overwrite here
626 *
627 * Don't forget to set the modification time of @p dest to be the modification time of @p src.
628 */
629 virtual void copy(const QUrl &src, const QUrl &dest, int permissions, JobFlags flags);
630
631 /**
632 * Delete a file or directory.
633 * @param url file/directory to delete
634 * @param isfile if true, a file should be deleted.
635 * if false, a directory should be deleted.
636 *
637 * By default, del() on a directory should FAIL if the directory is not empty.
638 * However, if metadata("recurse") == "true", then the slave can do a recursive deletion.
639 * This behavior is only invoked if the slave specifies deleteRecursive=true in its protocol file.
640 */
641 virtual void del(const QUrl &url, bool isfile);
642
643 /**
644 * Change the destination of a symlink
645 * @param url the url of the symlink to modify
646 * @param target the new destination (target) of the symlink
647 */
648 virtual void setLinkDest(const QUrl &url, const QString &target);
649
650 /**
651 * Used for any command that is specific to this slave (protocol).
652 *
653 * Examples are : HTTP POST, mount and unmount (kio_file)
654 *
655 * @param data packed data; the meaning is completely dependent on the
656 * slave, but usually starts with an int for the command number.
657 * Document your slave's commands, at least in its header file.
658 */
659 virtual void special(const QByteArray &data);
660
661 /**
662 * Called to get the status of the slave. Slave should respond
663 * by calling slaveStatus(...)
664 */
665 virtual void slave_status();
666
667 /**
668 * Called by the scheduler to tell the slave that the configuration
669 * changed (i.e.\ proxy settings).
670 */
671 virtual void reparseConfiguration();
672
673 /**
674 * @return timeout value for connecting to remote host.
675 */
676 int connectTimeout();
677
678 /**
679 * @return timeout value for connecting to proxy in secs.
680 */
682
683 /**
684 * @return timeout value for read from first data from
685 * remote host in seconds.
686 */
687 int responseTimeout();
688
689 /**
690 * @return timeout value for read from subsequent data from
691 * remote host in secs.
692 */
693 int readTimeout();
694
695 /**
696 * This function sets a timeout of @p timeout seconds and calls
697 * special(data) when the timeout occurs as if it was called by the
698 * application.
699 *
700 * A timeout can only occur when the slave is waiting for a command
701 * from the application.
702 *
703 * Specifying a negative timeout cancels a pending timeout.
704 *
705 * Only one timeout at a time is supported, setting a timeout
706 * cancels any pending timeout.
707 */
708 void setTimeoutSpecialCommand(int timeout, const QByteArray &data = QByteArray());
709
710 /////////////////
711 // Dispatching (internal)
712 ////////////////
713
714 /**
715 * @internal
716 */
717 virtual void dispatch(int command, const QByteArray &data);
718
719 /**
720 * @internal
721 */
722 virtual void dispatchOpenCommand(int command, const QByteArray &data);
723
724 /**
725 * Read data sent by the job, after a dataReq
726 *
727 * @param buffer buffer where data is stored
728 * @return 0 on end of data,
729 * > 0 bytes read
730 * < 0 error
731 **/
732 int readData(QByteArray &buffer);
733
734 /**
735 * It collects entries and emits them via listEntries
736 * when enough of them are there or a certain time
737 * frame exceeded (to make sure the app gets some
738 * items in time but not too many items one by one
739 * as this will cause a drastic performance penalty).
740 * @param entry The UDSEntry containing all of the object attributes.
741 * @since 5.0
742 */
743 void listEntry(const UDSEntry &entry);
744
745 /**
746 * internal function to connect a slave to/ disconnect from
747 * either the slave pool or the application
748 */
749 void connectSlave(const QString &path);
750 void disconnectSlave();
751
752 /**
753 * Prompt the user for Authorization info (login & password).
754 *
755 * Use this function to request authorization information from
756 * the end user. You can also pass an error message which explains
757 * why a previous authorization attempt failed. Here is a very
758 * simple example:
759 *
760 * \code
761 * KIO::AuthInfo authInfo;
762 * int errorCode = openPasswordDialogV2(authInfo);
763 * if (!errorCode) {
764 * qDebug() << QLatin1String("User: ") << authInfo.username;
765 * qDebug() << QLatin1String("Password: not displayed here!");
766 * } else {
767 * error(errorCode, QString());
768 * }
769 * \endcode
770 *
771 * You can also preset some values like the username, caption or
772 * comment as follows:
773 *
774 * \code
775 * KIO::AuthInfo authInfo;
776 * authInfo.caption = i18n("Acme Password Dialog");
777 * authInfo.username = "Wile E. Coyote";
778 * QString errorMsg = i18n("You entered an incorrect password.");
779 * int errorCode = openPasswordDialogV2(authInfo, errorMsg);
780 * [...]
781 * \endcode
782 *
783 * \note You should consider using checkCachedAuthentication() to
784 * see if the password is available in kpasswdserver before calling
785 * this function.
786 *
787 * \note A call to this function can fail and return @p false,
788 * if the password server could not be started for whatever reason.
789 *
790 * \note This function does not store the password information
791 * automatically (and has not since kdelibs 4.7). If you want to
792 * store the password information in a persistent storage like
793 * KWallet, then you MUST call @ref cacheAuthentication.
794 *
795 * @see checkCachedAuthentication
796 * @param info See AuthInfo.
797 * @param errorMsg Error message to show
798 * @return a KIO error code: NoError (0), KIO::USER_CANCELED, or other error codes.
799 */
800 int openPasswordDialogV2(KIO::AuthInfo &info, const QString &errorMsg = QString());
801
802 /**
803 * Checks for cached authentication based on parameters
804 * given by @p info.
805 *
806 * Use this function to check if any cached password exists
807 * for the URL given by @p info. If @p AuthInfo::realmValue
808 * and/or @p AuthInfo::verifyPath flag is specified, then
809 * they will also be factored in determining the presence
810 * of a cached password. Note that @p Auth::url is a required
811 * parameter when attempting to check for cached authorization
812 * info. Here is a simple example:
813 *
814 * \code
815 * AuthInfo info;
816 * info.url = QUrl("https://www.foobar.org/foo/bar");
817 * info.username = "somename";
818 * info.verifyPath = true;
819 * if ( !checkCachedAuthentication( info ) )
820 * {
821 * int errorCode = openPasswordDialogV2(info);
822 * ....
823 * }
824 * \endcode
825 *
826 * @param info See AuthInfo.
827 * @return @p true if cached Authorization is found, false otherwise.
828 */
830
831 /**
832 * Caches @p info in a persistent storage like KWallet.
833 *
834 * Note that calling openPasswordDialogV2 does not store passwords
835 * automatically for you (and has not since kdelibs 4.7).
836 *
837 * Here is a simple example of how to use cacheAuthentication:
838 *
839 * \code
840 * AuthInfo info;
841 * info.url = QUrl("https://www.foobar.org/foo/bar");
842 * info.username = "somename";
843 * info.verifyPath = true;
844 * if ( !checkCachedAuthentication( info ) ) {
845 * int errorCode = openPasswordDialogV2(info);
846 * if (!errorCode) {
847 * if (info.keepPassword) { // user asked password be save/remembered
848 * cacheAuthentication(info);
849 * }
850 * }
851 * }
852 * \endcode
853 *
854 * @param info See AuthInfo.
855 * @return @p true if @p info was successfully cached.
856 */
857 bool cacheAuthentication(const AuthInfo &info);
858
859 /**
860 * Wait for an answer to our request, until we get @p expected1 or @p expected2
861 * @return the result from readData, as well as the cmd in *pCmd if set, and the data in @p data
862 */
863 int waitForAnswer(int expected1, int expected2, QByteArray &data, int *pCmd = nullptr);
864
865 /**
866 * Internal function to transmit meta data to the application.
867 * m_outgoingMetaData will be cleared; this means that if the slave is for
868 * example put on hold and picked up by a different KIO::Job later the new
869 * job will not see the metadata sent before.
870 * See kio/DESIGN.krun for an overview of the state
871 * progression of a job/slave.
872 * @warning calling this method may seriously interfere with the operation
873 * of KIO which relies on the presence of some metadata at some points in time.
874 * You should not use it if you are not familiar with KIO and not before
875 * the slave is connected to the last job before returning to idle state.
876 */
877 void sendMetaData();
878
879 /**
880 * Internal function to transmit meta data to the application.
881 * Like sendMetaData() but m_outgoingMetaData will not be cleared.
882 * This method is mainly useful in code that runs before the slave is connected
883 * to its final job.
884 */
885 void sendAndKeepMetaData();
886
887 /** If your ioslave was killed by a signal, wasKilled() returns true.
888 Check it regularly in lengthy functions (e.g. in get();) and return
889 as fast as possible from this function if wasKilled() returns true.
890 This will ensure that your slave destructor will be called correctly.
891 */
892 bool wasKilled() const;
893
894 /** Internally used.
895 * @internal
896 */
897 void setKillFlag();
898
899 /** Internally used
900 * @internal
901 */
902 void lookupHost(const QString &host);
903
904 /** Internally used
905 * @internal
906 */
907 int waitForHostInfo(QHostInfo &info);
908
909 /**
910 * Checks with job if privilege operation is allowed.
911 * @return privilege operation status.
912 * @see PrivilegeOperationStatus
913 * @since 5.66
914 */
916
917 /**
918 * Adds @p action to the list of PolicyKit actions which the
919 * slave is authorized to perform.
920 *
921 * @param action the PolicyKit action
922 * @since 5.45
923 */
924 void addTemporaryAuthorization(const QString &action);
925
926protected:
927 /**
928 * Name of the protocol supported by this slave
929 */
931 // Often used by TcpSlaveBase and unlikely to change
932 MetaData mOutgoingMetaData;
933 MetaData mIncomingMetaData;
934
935 enum VirtualFunctionId {
936 AppConnectionMade = 0,
937 GetFileSystemFreeSpace = 1, // KF6 TODO: Turn into a virtual method
938 Truncate = 2, // KF6 TODO: Turn into a virtual method
939 };
940 virtual void virtual_hook(int id, void *data);
941
942private:
943 // Convenience function converting mProtocol to QString as unsupportedActionErrorString(), which
944 // is used in many places in the code, takes a QString parameter
945 inline const QString protocolName() const
946 {
948 }
949
950 void setRunInThread(bool b);
951
952 // This helps catching missing tr()/i18n() calls in error().
953 void error(int _errid, const QByteArray &_text);
954 void send(int cmd, const QByteArray &arr = QByteArray());
955
956 std::unique_ptr<SlaveBasePrivate> const d;
957 friend class SlaveBasePrivate;
958 friend class WorkerThread;
959 friend class WorkerBasePrivate;
960 friend class WorkerSlaveBaseBridge;
961};
962}
963
964#endif
965
966// HACK see comments in workerbase.h for same include/declaration guard
967#ifndef KIO_UNSUPPORTEDACTIONERRORSTRING
968#define KIO_UNSUPPORTEDACTIONERRORSTRING
969
970namespace KIO
971{
972
973/**
974 * Returns an appropriate error message if the given command @p cmd
975 * is an unsupported action (ERR_UNSUPPORTED_ACTION).
976 * @param protocol name of the protocol
977 * @param cmd given command
978 * @see enum Command
979 */
980KIOCORE_EXPORT QString unsupportedActionErrorString(const QString &protocol, int cmd);
981}
982
983#endif
This class is intended to make it easier to prompt for, cache and retrieve authorization information.
MetaData is a simple map of key/value strings.
There are two classes that specifies the protocol between application (job) and kioslave.
void addTemporaryAuthorization(const QString &action)
Adds action to the list of PolicyKit actions which the slave is authorized to perform.
int proxyConnectTimeout()
virtual void mimetype(const QUrl &url)
Finds MIME type for one file or directory.
bool wasKilled() const
If your ioslave was killed by a signal, wasKilled() returns true.
MetaData allMetaData() const
void mimeType(const QString &_type)
Call this in mimetype() and in get(), when you know the MIME type.
virtual void dispatch(int command, const QByteArray &data)
QMap< QString, QVariant > mapConfig() const
Returns a map to query config/meta-data information from.
virtual void get(const QUrl &url)
get, aka read.
PrivilegeOperationStatus requestPrivilegeOperation(const QString &operationDetails)
Checks with job if privilege operation is allowed.
QString metaData(const QString &key) const
Queries for config/meta-data send by the application to the slave.
int openPasswordDialogV2(KIO::AuthInfo &info, const QString &errorMsg=QString())
Prompt the user for Authorization info (login & password).
void redirection(const QUrl &_url)
Call this to signal a redirection.
virtual void copy(const QUrl &src, const QUrl &dest, int permissions, JobFlags flags)
Copy src into dest.
void sendAndKeepMetaData()
Internal function to transmit meta data to the application.
void speed(unsigned long _bytes_per_second)
Call this in get and copy, to give the current transfer speed, but only if it can't be calculated out...
void infoMessage(const QString &msg)
Call to signal a message, to be displayed if the application wants to, for instance in a status bar.
void processedSize(KIO::filesize_t _bytes)
Call this during get and copy, once in a while, to give some info about the current state.
virtual void reparseConfiguration()
Called by the scheduler to tell the slave that the configuration changed (i.e. proxy settings).
void setTimeoutSpecialCommand(int timeout, const QByteArray &data=QByteArray())
This function sets a timeout of timeout seconds and calls special(data) when the timeout occurs as if...
int messageBox(MessageBoxType type, const QString &text, const QString &title=QString(), const QString &primaryActionText=QString(), const QString &secondaryActionText=QString())
Call this to show a message box from the slave.
virtual void open(const QUrl &url, QIODevice::OpenMode mode)
open.
ButtonCode
Button codes.
Definition slavebase.h:263
void warning(const QString &msg)
Call to signal a warning, to be displayed in a dialog box.
virtual void seek(KIO::filesize_t offset)
seek.
void finished()
Call to signal successful completion of any command besides openConnection and closeConnection.
virtual void openConnection()
Opens the connection (forced).
void slaveStatus(const QString &host, bool connected)
Used to report the status of the slave.
bool cacheAuthentication(const AuthInfo &info)
Caches info in a persistent storage like KWallet.
void dataReq()
Asks for data from the job.
virtual void rename(const QUrl &src, const QUrl &dest, JobFlags flags)
Rename oldname into newname.
virtual void write(const QByteArray &data)
write.
void error(int _errid, const QString &_text)
Call to signal an error.
QByteArray mProtocol
Name of the protocol supported by this slave.
Definition slavebase.h:930
virtual void setLinkDest(const QUrl &url, const QString &target)
Change the destination of a symlink.
void truncated(KIO::filesize_t _length)
virtual void listDir(const QUrl &url)
Lists the contents of url.
void sendMetaData()
Internal function to transmit meta data to the application.
void listEntry(const UDSEntry &entry)
It collects entries and emits them via listEntries when enough of them are there or a certain time fr...
bool hasMetaData(const QString &key) const
Queries for the existence of a certain config/meta-data entry send by the application to the slave.
void statEntry(const UDSEntry &_entry)
Call this from stat() to express details about an object, the UDSEntry customarily contains the atoms...
virtual void setHost(const QString &host, quint16 port, const QString &user, const QString &pass)
Set the host.
virtual void chown(const QUrl &url, const QString &owner, const QString &group)
Change ownership of url.
void connected()
Call in openConnection, if you reimplement it, when you're done.
KRemoteEncoding * remoteEncoding()
Returns an object that can translate remote filenames into proper Unicode forms.
void dispatchLoop()
virtual void dispatchOpenCommand(int command, const QByteArray &data)
virtual void symlink(const QString &target, const QUrl &dest, JobFlags flags)
Creates a symbolic link named dest, pointing to target, which may be a relative or an absolute path.
int readData(QByteArray &buffer)
Read data sent by the job, after a dataReq.
MessageBoxType
Type of message box.
Definition slavebase.h:250
@ WarningTwoActionsCancel
Definition slavebase.h:254
void connectSlave(const QString &path)
internal function to connect a slave to/ disconnect from either the slave pool or the application
virtual void put(const QUrl &url, int permissions, JobFlags flags)
put, i.e. write data into a file.
int waitForHostInfo(QHostInfo &info)
Internally used.
void processedPercent(float percent)
Only use this if you can't know in advance the size of the copied data.
virtual void special(const QByteArray &data)
Used for any command that is specific to this slave (protocol).
virtual void del(const QUrl &url, bool isfile)
Delete a file or directory.
void data(const QByteArray &data)
Sends data in the slave to the job (i.e. in get).
virtual void chmod(const QUrl &url, int permissions)
Change permissions on url.
void listEntries(const UDSEntryList &_entry)
Call this in listDir, each time you have a bunch of entries to report.
virtual void setModificationTime(const QUrl &url, const QDateTime &mtime)
Sets the modification time for url.
virtual void slave_status()
Called to get the status of the slave.
void totalSize(KIO::filesize_t _bytes)
Call this in get and copy, to give the total size of the file.
virtual void closeConnection()
Closes the connection (forced).
virtual void read(KIO::filesize_t size)
read.
void setKillFlag()
Internally used.
virtual void stat(const QUrl &url)
Finds all details for one file or directory.
virtual void mkdir(const QUrl &url, int permissions)
Create a directory.
int waitForAnswer(int expected1, int expected2, QByteArray &data, int *pCmd=nullptr)
Wait for an answer to our request, until we get expected1 or expected2.
void canResume()
Call this at the beginning of get(), if the "range-start" metadata was set and returning byte ranges ...
bool checkCachedAuthentication(AuthInfo &info)
Checks for cached authentication based on parameters given by info.
void setMetaData(const QString &key, const QString &value)
Sets meta-data to be send to the application before the first data() or finished() signal.
KConfigGroup * config()
Returns a configuration object to query config/meta-data information from.
virtual void close()
close.
void lookupHost(const QString &host)
Internally used.
void opened()
open succeeds
bool configValue(const QString &key, bool defaultValue) const
Returns a bool from the config/meta-data information.
Universal Directory Service.
Allows encoding and decoding properly remote filenames into Unicode.
A namespace for KIO globals.
KIOCORE_EXPORT QString unsupportedActionErrorString(const QString &protocol, int cmd)
Returns an appropriate error message if the given command cmd is an unsupported action (ERR_UNSUPPORT...
PrivilegeOperationStatus
Specifies privilege file operation status.
Definition global.h:239
qulonglong filesize_t
64-bit file size
Definition global.h:35
QString fromLatin1(QByteArrayView str)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Dec 20 2024 11:49:55 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.