KIO

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

KDE's Doxygen guidelines are available online.