/
file_unix.cpp
1595 lines (1447 loc) · 51.3 KB
/
file_unix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
SPDX-FileCopyrightText: 2000-2002 Stephan Kulow <coolo@kde.org>
SPDX-FileCopyrightText: 2000-2002 David Faure <faure@kde.org>
SPDX-FileCopyrightText: 2000-2002 Waldo Bastian <bastian@kde.org>
SPDX-FileCopyrightText: 2006 Allan Sandfeld Jensen <sandfeld@kde.org>
SPDX-FileCopyrightText: 2007 Thiago Macieira <thiago@kde.org>
SPDX-FileCopyrightText: 2007 Christian Ehrlicher <ch.ehrlicher@gmx.de>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "file.h"
#include <config-kioslave-file.h>
#include <QDir>
#include <QFile>
#include <QMimeDatabase>
#include <QStandardPaths>
#include <QThread>
#include <qplatformdefs.h>
#include <KConfigGroup>
#include <KLocalizedString>
#include <QDebug>
#include <kmountpoint.h>
#include <cerrno>
#include <stdint.h>
#include <utime.h>
#include <KAuth>
#include <KRandom>
#include "fdreceiver.h"
#include "statjob.h"
#if HAVE_STATX
#include <sys/stat.h>
#include <sys/sysmacros.h> // for makedev()
#endif
#ifdef Q_OS_LINUX
#include <linux/fs.h>
#include <sys/ioctl.h>
#endif
// sendfile has different semantics in different platforms
#if HAVE_SENDFILE && defined Q_OS_LINUX
#define USE_SENDFILE 1
#include <sys/sendfile.h>
#endif
#if HAVE_SYS_XATTR_H
#include <sys/xattr.h>
// BSD uses a different include
#elif HAVE_SYS_EXTATTR_H
#include <sys/extattr.h>
#endif
using namespace KIO;
/* 512 kB */
static constexpr int s_maxIPCSize = 1024 * 512;
static bool same_inode(const QT_STATBUF &src, const QT_STATBUF &dest)
{
if (src.st_ino == dest.st_ino && src.st_dev == dest.st_dev) {
return true;
}
return false;
}
static const QString socketPath()
{
const QString runtimeDir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
return QStringLiteral("%1/filehelper%2%3").arg(runtimeDir, KRandom::randomString(6)).arg(getpid());
}
static QString actionDetails(ActionType actionType, const QVariantList &args)
{
QString action, detail;
switch (actionType) {
case CHMOD:
action = i18n("Change File Permissions");
detail = i18n("New Permissions: %1", args[1].toInt());
break;
case CHOWN:
action = i18n("Change File Owner");
detail = i18n("New Owner: UID=%1, GID=%2", args[1].toInt(), args[2].toInt());
break;
case DEL:
action = i18n("Remove File");
break;
case RMDIR:
action = i18n("Remove Directory");
break;
case MKDIR:
action = i18n("Create Directory");
detail = i18n("Directory Permissions: %1", args[1].toInt());
break;
case OPEN:
action = i18n("Open File");
break;
case OPENDIR:
action = i18n("Open Directory");
break;
case RENAME:
action = i18n("Rename");
detail = i18n("New Filename: %1", args[1].toString());
break;
case SYMLINK:
action = i18n("Create Symlink");
detail = i18n("Target: %1", args[1].toString());
break;
case UTIME:
action = i18n("Change Timestamp");
break;
default:
action = i18n("Unknown Action");
break;
}
const QString metadata = i18n(
"Action: %1\n"
"Source: %2\n"
"%3",
action,
args[0].toString(),
detail);
return metadata;
}
bool FileProtocol::privilegeOperationUnitTestMode()
{
return (metaData(QStringLiteral("UnitTesting")) == QLatin1String("true"))
&& (requestPrivilegeOperation(QStringLiteral("Test Call")) == KIO::OperationAllowed);
}
/*************************************
*
* ACL handling helpers
*
*************************************/
#if HAVE_POSIX_ACL
static QString aclToText(acl_t acl)
{
ssize_t size = 0;
char *txt = acl_to_text(acl, &size);
const QString ret = QString::fromLatin1(txt, size);
acl_free(txt);
return ret;
}
bool FileProtocol::isExtendedACL(acl_t acl)
{
return (acl_equiv_mode(acl, nullptr) != 0);
}
static void appendACLAtoms(const QByteArray &path, UDSEntry &entry, mode_t type)
{
// first check for a noop
if (acl_extended_file(path.data()) == 0) {
return;
}
acl_t acl = nullptr;
acl_t defaultAcl = nullptr;
bool isDir = (type & QT_STAT_MASK) == QT_STAT_DIR;
// do we have an acl for the file, and/or a default acl for the dir, if it is one?
acl = acl_get_file(path.data(), ACL_TYPE_ACCESS);
/* Sadly libacl does not provided a means of checking for extended ACL and default
* ACL separately. Since a directory can have both, we need to check again. */
if (isDir) {
if (acl) {
if (!FileProtocol::isExtendedACL(acl)) {
acl_free(acl);
acl = nullptr;
}
}
defaultAcl = acl_get_file(path.data(), ACL_TYPE_DEFAULT);
}
if (acl || defaultAcl) {
// qDebug() << path.constData() << "has extended ACL entries";
entry.fastInsert(KIO::UDSEntry::UDS_EXTENDED_ACL, 1);
if (acl) {
const QString str = aclToText(acl);
entry.fastInsert(KIO::UDSEntry::UDS_ACL_STRING, str);
// qDebug() << path.constData() << "ACL:" << str;
acl_free(acl);
}
if (defaultAcl) {
const QString str = aclToText(defaultAcl);
entry.fastInsert(KIO::UDSEntry::UDS_DEFAULT_ACL_STRING, str);
// qDebug() << path.constData() << "DEFAULT ACL:" << str;
acl_free(defaultAcl);
}
}
}
#endif
static QHash<KUserId, QString> staticUserCache;
static QHash<KGroupId, QString> staticGroupCache;
static QString getUserName(KUserId uid)
{
if (Q_UNLIKELY(!uid.isValid())) {
return QString();
}
auto it = staticUserCache.find(uid);
if (it == staticUserCache.end()) {
KUser user(uid);
QString name = user.loginName();
if (name.isEmpty()) {
name = uid.toString();
}
it = staticUserCache.insert(uid, name);
}
return *it;
}
static QString getGroupName(KGroupId gid)
{
if (Q_UNLIKELY(!gid.isValid())) {
return QString();
}
auto it = staticGroupCache.find(gid);
if (it == staticGroupCache.end()) {
KUserGroup group(gid);
QString name = group.name();
if (name.isEmpty()) {
name = gid.toString();
}
it = staticGroupCache.insert(gid, name);
}
return *it;
}
#if HAVE_STATX
// statx syscall is available
inline int LSTAT(const char *path, struct statx *buff, KIO::StatDetails details)
{
uint32_t mask = 0;
if (details & KIO::StatBasic) {
// filename, access, type, size, linkdest
mask |= STATX_SIZE | STATX_TYPE;
}
if (details & KIO::StatUser) {
// uid, gid
mask |= STATX_UID | STATX_GID;
}
if (details & KIO::StatTime) {
// atime, mtime, btime
mask |= STATX_ATIME | STATX_MTIME | STATX_BTIME;
}
if (details & KIO::StatInode) {
// dev, inode
mask |= STATX_INO;
}
return statx(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW, mask, buff);
}
inline int STAT(const char *path, struct statx *buff, KIO::StatDetails details)
{
uint32_t mask = 0;
// KIO::StatAcl needs type
if (details & (KIO::StatBasic | KIO::StatAcl | KIO::StatResolveSymlink)) {
// filename, access, type
mask |= STATX_TYPE;
}
if (details & (KIO::StatBasic | KIO::StatResolveSymlink)) {
// size, linkdest
mask |= STATX_SIZE;
}
if (details & KIO::StatUser) {
// uid, gid
mask |= STATX_UID | STATX_GID;
}
if (details & KIO::StatTime) {
// atime, mtime, btime
mask |= STATX_ATIME | STATX_MTIME | STATX_BTIME;
}
// KIO::Inode is ignored as when STAT is called, the entry inode field has already been filled
return statx(AT_FDCWD, path, AT_STATX_SYNC_AS_STAT, mask, buff);
}
inline static uint16_t stat_mode(struct statx &buf)
{
return buf.stx_mode;
}
inline static dev_t stat_dev(struct statx &buf)
{
return makedev(buf.stx_dev_major, buf.stx_dev_minor);
}
inline static uint64_t stat_ino(struct statx &buf)
{
return buf.stx_ino;
}
inline static uint64_t stat_size(struct statx &buf)
{
return buf.stx_size;
}
inline static uint32_t stat_uid(struct statx &buf)
{
return buf.stx_uid;
}
inline static uint32_t stat_gid(struct statx &buf)
{
return buf.stx_gid;
}
inline static int64_t stat_atime(struct statx &buf)
{
return buf.stx_atime.tv_sec;
}
inline static int64_t stat_mtime(struct statx &buf)
{
return buf.stx_mtime.tv_sec;
}
#else
// regular stat struct
inline int LSTAT(const char *path, QT_STATBUF *buff, KIO::StatDetails details)
{
Q_UNUSED(details)
return QT_LSTAT(path, buff);
}
inline int STAT(const char *path, QT_STATBUF *buff, KIO::StatDetails details)
{
Q_UNUSED(details)
return QT_STAT(path, buff);
}
inline static mode_t stat_mode(QT_STATBUF &buf)
{
return buf.st_mode;
}
inline static dev_t stat_dev(QT_STATBUF &buf)
{
return buf.st_dev;
}
inline static ino_t stat_ino(QT_STATBUF &buf)
{
return buf.st_ino;
}
inline static off_t stat_size(QT_STATBUF &buf)
{
return buf.st_size;
}
inline static uid_t stat_uid(QT_STATBUF &buf)
{
return buf.st_uid;
}
inline static gid_t stat_gid(QT_STATBUF &buf)
{
return buf.st_gid;
}
inline static time_t stat_atime(QT_STATBUF &buf)
{
return buf.st_atime;
}
inline static time_t stat_mtime(QT_STATBUF &buf)
{
return buf.st_mtime;
}
#endif
static bool createUDSEntry(const QString &filename, const QByteArray &path, UDSEntry &entry, KIO::StatDetails details)
{
assert(entry.count() == 0); // by contract :-)
int entries = 0;
if (details & KIO::StatBasic) {
// filename, access, type, size, linkdest
entries += 5;
}
if (details & KIO::StatUser) {
// uid, gid
entries += 2;
}
if (details & KIO::StatTime) {
// atime, mtime, btime
entries += 3;
}
if (details & KIO::StatAcl) {
// acl data
entries += 3;
}
if (details & KIO::StatInode) {
// dev, inode
entries += 2;
}
if (details & KIO::StatMimeType) {
// mimetype
entries += 1;
}
entry.reserve(entries);
if (details & KIO::StatBasic) {
entry.fastInsert(KIO::UDSEntry::UDS_NAME, filename);
}
bool isBrokenSymLink = false;
#if HAVE_POSIX_ACL
QByteArray targetPath = path;
#endif
#if HAVE_STATX
// statx syscall is available
struct statx buff;
#else
QT_STATBUF buff;
#endif
if (LSTAT(path.data(), &buff, details) == 0) {
if ((stat_mode(buff) & QT_STAT_MASK) == QT_STAT_LNK) {
QByteArray linkTargetBuffer;
if (details & (KIO::StatBasic | KIO::StatResolveSymlink)) {
// Use readlink on Unix because symLinkTarget turns relative targets into absolute (#352927)
#if HAVE_STATX
size_t lowerBound = 256;
size_t higherBound = 1024;
uint64_t s = stat_size(buff);
if (s > SIZE_MAX) {
qCWarning(KIO_FILE) << "file size bigger than SIZE_MAX, too big for readlink use!" << path;
return false;
}
size_t size = static_cast<size_t>(s);
using SizeType = size_t;
#else
off_t lowerBound = 256;
off_t higherBound = 1024;
off_t size = stat_size(buff);
using SizeType = off_t;
#endif
SizeType bufferSize = qBound(lowerBound, size + 1, higherBound);
linkTargetBuffer.resize(bufferSize);
while (true) {
ssize_t n = readlink(path.constData(), linkTargetBuffer.data(), bufferSize);
if (n < 0 && errno != ERANGE) {
qCWarning(KIO_FILE) << "readlink failed!" << path;
return false;
} else if (n > 0 && static_cast<SizeType>(n) != bufferSize) {
// the buffer was not filled in the last iteration
// we are finished reading, break the loop
linkTargetBuffer.truncate(n);
break;
}
bufferSize *= 2;
linkTargetBuffer.resize(bufferSize);
}
const QString linkTarget = QFile::decodeName(linkTargetBuffer);
entry.fastInsert(KIO::UDSEntry::UDS_LINK_DEST, linkTarget);
}
// A symlink
if (details & KIO::StatResolveSymlink) {
if (STAT(path.constData(), &buff, details) == -1) {
isBrokenSymLink = true;
} else {
#if HAVE_POSIX_ACL
if (details & KIO::StatAcl) {
// valid symlink, will get the ACLs of the destination
targetPath = linkTargetBuffer;
}
#endif
}
}
}
} else {
// qCWarning(KIO_FILE) << "lstat didn't work on " << path.data();
return false;
}
mode_t type = 0;
if (details & (KIO::StatBasic | KIO::StatAcl)) {
mode_t access;
signed long long size;
if (isBrokenSymLink) {
// It is a link pointing to nowhere
type = S_IFMT - 1;
access = S_IRWXU | S_IRWXG | S_IRWXO;
size = 0LL;
} else {
type = stat_mode(buff) & S_IFMT; // extract file type
access = stat_mode(buff) & 07777; // extract permissions
size = stat_size(buff);
}
if (details & KIO::StatBasic) {
entry.fastInsert(KIO::UDSEntry::UDS_FILE_TYPE, type);
entry.fastInsert(KIO::UDSEntry::UDS_ACCESS, access);
entry.fastInsert(KIO::UDSEntry::UDS_SIZE, size);
}
#if HAVE_POSIX_ACL
if (details & KIO::StatAcl) {
/* Append an atom indicating whether the file has extended acl information
* and if withACL is specified also one with the acl itself. If it's a directory
* and it has a default ACL, also append that. */
appendACLAtoms(targetPath, entry, type);
}
#endif
}
if (details & KIO::StatUser) {
entry.fastInsert(KIO::UDSEntry::UDS_USER, getUserName(KUserId(stat_uid(buff))));
entry.fastInsert(KIO::UDSEntry::UDS_GROUP, getGroupName(KGroupId(stat_gid(buff))));
}
if (details & KIO::StatTime) {
entry.fastInsert(KIO::UDSEntry::UDS_MODIFICATION_TIME, stat_mtime(buff));
entry.fastInsert(KIO::UDSEntry::UDS_ACCESS_TIME, stat_atime(buff));
#ifdef st_birthtime
/* For example FreeBSD's and NetBSD's stat contains a field for
* the inode birth time: st_birthtime
* This however only works on UFS and ZFS, and not, on say, NFS.
* Instead of setting a bogus fallback like st_mtime, only use
* it if it is greater than 0. */
if (buff.st_birthtime > 0) {
entry.fastInsert(KIO::UDSEntry::UDS_CREATION_TIME, buff.st_birthtime);
}
#elif defined __st_birthtime
/* As above, but OpenBSD calls it slightly differently. */
if (buff.__st_birthtime > 0) {
entry.fastInsert(KIO::UDSEntry::UDS_CREATION_TIME, buff.__st_birthtime);
}
#elif HAVE_STATX
/* And linux version using statx syscall */
if (buff.stx_mask & STATX_BTIME) {
entry.fastInsert(KIO::UDSEntry::UDS_CREATION_TIME, buff.stx_btime.tv_sec);
}
#endif
}
if (details & KIO::StatInode) {
entry.fastInsert(KIO::UDSEntry::UDS_DEVICE_ID, stat_dev(buff));
entry.fastInsert(KIO::UDSEntry::UDS_INODE, stat_ino(buff));
}
if (details & KIO::StatMimeType) {
QMimeDatabase db;
entry.fastInsert(KIO::UDSEntry::UDS_MIME_TYPE, db.mimeTypeForFile(filename).name());
}
return true;
}
PrivilegeOperationReturnValue FileProtocol::tryOpen(QFile &f, const QByteArray &path, int flags, int mode, int errcode)
{
const QString sockPath = socketPath();
FdReceiver fdRecv(QFile::encodeName(sockPath).toStdString());
if (!fdRecv.isListening()) {
return PrivilegeOperationReturnValue::failure(errcode);
}
QIODevice::OpenMode openMode;
if (flags & O_RDONLY) {
openMode |= QIODevice::ReadOnly;
}
if (flags & O_WRONLY || flags & O_CREAT) {
openMode |= QIODevice::WriteOnly;
}
if (flags & O_RDWR) {
openMode |= QIODevice::ReadWrite;
}
if (flags & O_TRUNC) {
openMode |= QIODevice::Truncate;
}
if (flags & O_APPEND) {
openMode |= QIODevice::Append;
}
if (auto err = execWithElevatedPrivilege(OPEN, {path, flags, mode, sockPath}, errcode)) {
return err;
} else {
int fd = fdRecv.fileDescriptor();
if (fd < 3 || !f.open(fd, openMode, QFileDevice::AutoCloseHandle)) {
return PrivilegeOperationReturnValue::failure(errcode);
}
}
return PrivilegeOperationReturnValue::success();
}
PrivilegeOperationReturnValue FileProtocol::tryChangeFileAttr(ActionType action, const QVariantList &args, int errcode)
{
KAuth::Action execAction(QStringLiteral("org.kde.kio.file.exec"));
execAction.setHelperId(QStringLiteral("org.kde.kio.file"));
if (execAction.status() == KAuth::Action::AuthorizedStatus) {
return execWithElevatedPrivilege(action, args, errcode);
}
return PrivilegeOperationReturnValue::failure(errcode);
}
#if HAVE_SYS_XATTR_H || HAVE_SYS_EXTATTR_H
bool FileProtocol::copyXattrs(const int src_fd, const int dest_fd)
{
// Get the list of keys
ssize_t listlen = 0;
QByteArray keylist;
while (true) {
keylist.resize(listlen);
#if HAVE_SYS_XATTR_H && !defined(__stub_getxattr) && !defined(Q_OS_MAC)
listlen = flistxattr(src_fd, keylist.data(), listlen);
#elif defined(Q_OS_MAC)
listlen = flistxattr(src_fd, keylist.data(), listlen, 0);
#elif HAVE_SYS_EXTATTR_H
listlen = extattr_list_fd(src_fd, EXTATTR_NAMESPACE_USER, listlen == 0 ? nullptr : keylist.data(), listlen);
#endif
if (listlen > 0 && keylist.size() == 0) {
continue;
}
if (listlen > 0 && keylist.size() > 0) {
break;
}
if (listlen == -1 && errno == ERANGE) {
listlen = 0;
continue;
}
if (listlen == 0) {
qCDebug(KIO_FILE) << "the file doesn't have any xattr";
return true;
}
Q_ASSERT_X(listlen == -1, "copyXattrs", "unexpected return value from listxattr");
if (listlen == -1 && errno == ENOTSUP) {
qCDebug(KIO_FILE) << "source filesystem does not support xattrs";
}
return false;
}
keylist.resize(listlen);
// Linux and MacOS return a list of null terminated strings, each string = [data,'\0']
// BSDs return a list of items, each item consisting of the size byte
// prepended to the key = [size, data]
QByteArray::const_iterator keyPtr = keylist.cbegin();
size_t keyLen;
QByteArray value;
// For each key
while (keyPtr != keylist.cend()) {
// Get size of the key
#if HAVE_SYS_XATTR_H
keyLen = strlen(keyPtr);
#elif HAVE_SYS_EXTATTR_H
keyLen = static_cast<unsigned char>(*keyPtr);
keyPtr++;
#endif
QByteArray key(keyPtr, keyLen);
// Get the value for key
ssize_t valuelen = 0;
do {
value.resize(valuelen);
#if HAVE_SYS_XATTR_H && !defined(__stub_getxattr) && !defined(Q_OS_MAC)
valuelen = fgetxattr(src_fd, key.constData(), value.data(), valuelen);
#elif defined(Q_OS_MAC)
valuelen = fgetxattr(src_fd, key.constData(), value.data(), valuelen, 0, 0);
#elif HAVE_SYS_EXTATTR_H
valuelen = extattr_get_fd(src_fd, EXTATTR_NAMESPACE_USER, key.constData(), valuelen == 0 ? nullptr : value.data(), valuelen);
#endif
if (valuelen > 0 && value.size() == 0) {
continue;
}
if (valuelen > 0 && value.size() > 0) {
break;
}
if (valuelen == -1 && errno == ERANGE) {
valuelen = 0;
continue;
}
// happens when attr value is an empty string
if (valuelen == 0) {
break;
}
Q_ASSERT_X(valuelen == -1, "copyXattrs", "unexpected return value from getxattr");
// Some other error, skip to the next attribute, most notably
// - ENOTSUP: invalid (inaccassible) attribute namespace, e.g. with SELINUX
break;
} while (true);
if (valuelen < 0) {
continue;
}
// Write key:value pair on destination
#if HAVE_SYS_XATTR_H && !defined(__stub_getxattr) && !defined(Q_OS_MAC)
ssize_t destlen = fsetxattr(dest_fd, key.constData(), value.constData(), valuelen, 0);
#elif defined(Q_OS_MAC)
ssize_t destlen = fsetxattr(dest_fd, key.constData(), value.constData(), valuelen, 0, 0);
#elif HAVE_SYS_EXTATTR_H
ssize_t destlen = extattr_set_fd(dest_fd, EXTATTR_NAMESPACE_USER, key.constData(), value.constData(), valuelen);
#endif
if (destlen == -1 && errno == ENOTSUP) {
qCDebug(KIO_FILE) << "Destination filesystem does not support xattrs";
return false;
}
if (destlen == -1 && (errno == ENOSPC || errno == EDQUOT)) {
return false;
}
#if HAVE_SYS_XATTR_H
keyPtr += keyLen + 1;
#elif HAVE_SYS_EXTATTR_H
keyPtr += keyLen;
#endif
}
return true;
}
#endif // HAVE_SYS_XATTR_H || HAVE_SYS_EXTATTR_H
void FileProtocol::copy(const QUrl &srcUrl, const QUrl &destUrl, int _mode, JobFlags _flags)
{
if (privilegeOperationUnitTestMode()) {
finished();
return;
}
qCDebug(KIO_FILE) << "copy()" << srcUrl << "to" << destUrl << "mode=" << _mode;
const QString src = srcUrl.toLocalFile();
QString dest = destUrl.toLocalFile();
QByteArray _src(QFile::encodeName(src));
QByteArray _dest(QFile::encodeName(dest));
QByteArray _dest_backup;
QT_STATBUF buff_src;
#if HAVE_POSIX_ACL
acl_t acl;
#endif
if (QT_STAT(_src.data(), &buff_src) == -1) {
if (errno == EACCES) {
error(KIO::ERR_ACCESS_DENIED, src);
} else {
error(KIO::ERR_DOES_NOT_EXIST, src);
}
return;
}
if ((buff_src.st_mode & QT_STAT_MASK) == QT_STAT_DIR) {
error(KIO::ERR_IS_DIRECTORY, src);
return;
}
if (S_ISFIFO(buff_src.st_mode) || S_ISSOCK(buff_src.st_mode)) {
error(KIO::ERR_CANNOT_OPEN_FOR_READING, src);
return;
}
QT_STATBUF buff_dest;
bool dest_exists = (QT_LSTAT(_dest.data(), &buff_dest) != -1);
if (dest_exists) {
if (same_inode(buff_dest, buff_src)) {
error(KIO::ERR_IDENTICAL_FILES, dest);
return;
}
if ((buff_dest.st_mode & QT_STAT_MASK) == QT_STAT_DIR) {
error(KIO::ERR_DIR_ALREADY_EXIST, dest);
return;
}
if (_flags & KIO::Overwrite) {
// If the destination is a symlink and overwrite is TRUE,
// remove the symlink first to prevent the scenario where
// the symlink actually points to current source!
if ((buff_dest.st_mode & QT_STAT_MASK) == QT_STAT_LNK) {
// qDebug() << "copy(): LINK DESTINATION";
if (!QFile::remove(dest)) {
if (auto err = execWithElevatedPrivilege(DEL, {_dest}, errno)) {
if (!err.wasCanceled()) {
error(KIO::ERR_CANNOT_DELETE_ORIGINAL, dest);
}
return;
}
}
} else if ((buff_dest.st_mode & QT_STAT_MASK) == QT_STAT_REG) {
_dest_backup = _dest;
dest.append(QStringLiteral(".part"));
_dest = QFile::encodeName(dest);
}
} else {
error(KIO::ERR_FILE_ALREADY_EXIST, dest);
return;
}
}
QFile src_file(src);
if (!src_file.open(QIODevice::ReadOnly)) {
if (auto err = tryOpen(src_file, _src, O_RDONLY, S_IRUSR, errno)) {
if (!err.wasCanceled()) {
error(KIO::ERR_CANNOT_OPEN_FOR_READING, src);
}
return;
}
}
#if HAVE_FADVISE
posix_fadvise(src_file.handle(), 0, 0, POSIX_FADV_SEQUENTIAL);
#endif
QFile dest_file(dest);
if (!dest_file.open(QIODevice::Truncate | QIODevice::WriteOnly)) {
if (auto err = tryOpen(dest_file, _dest, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR, errno)) {
if (!err.wasCanceled()) {
// qDebug() << "###### COULD NOT WRITE " << dest;
if (err == EACCES) {
error(KIO::ERR_WRITE_ACCESS_DENIED, dest);
} else {
error(KIO::ERR_CANNOT_OPEN_FOR_WRITING, dest);
}
}
src_file.close();
return;
}
}
// nobody shall be allowed to peek into the file during creation
// Note that error handling is omitted for this call, we don't want to error on e.g. VFAT
dest_file.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);
#if HAVE_FADVISE
posix_fadvise(dest_file.handle(), 0, 0, POSIX_FADV_SEQUENTIAL);
#endif
#if HAVE_POSIX_ACL
acl = acl_get_fd(src_file.handle());
if (acl && !isExtendedACL(acl)) {
// qDebug() << _dest.data() << " doesn't have extended ACL";
acl_free(acl);
acl = nullptr;
}
#endif
totalSize(buff_src.st_size);
#ifdef FICLONE
// Share data blocks ("reflink") on supporting filesystems, like brfs and XFS
int ret = ::ioctl(dest_file.handle(), FICLONE, src_file.handle());
if (ret != -1) {
processedSize(src_file.size());
} else {
// if fs does not support reflinking, files are on different devices...
#endif
KIO::filesize_t processed_size = 0;
char buffer[s_maxIPCSize];
ssize_t n = 0;
#ifdef USE_SENDFILE
bool use_sendfile = true;
#endif
bool existing_dest_delete_attempted = false;
while (!wasKilled()) {
if (testMode && dest_file.fileName().contains(QLatin1String("slow"))) {
QThread::msleep(50);
}
#ifdef USE_SENDFILE
if (use_sendfile) {
off_t sf = processed_size;
n = ::sendfile(dest_file.handle(), src_file.handle(), &sf, s_maxIPCSize);
processed_size = sf;
if (n == -1 && (errno == EINVAL || errno == ENOSYS)) { // not all filesystems support sendfile()
// qDebug() << "sendfile() not supported, falling back ";
use_sendfile = false;
}
}
if (!use_sendfile)
#endif
n = ::read(src_file.handle(), buffer, s_maxIPCSize);
if (n == -1) {
if (errno == EINTR) {
continue;
}
#ifdef USE_SENDFILE
if (use_sendfile) {
// qDebug() << "sendfile() error:" << strerror(errno);
if (errno == ENOSPC) { // disk full
if (!_dest_backup.isEmpty() && !existing_dest_delete_attempted) {
::unlink(_dest_backup.constData());
existing_dest_delete_attempted = true;
continue;
}
error(KIO::ERR_DISK_FULL, dest);
} else {
error(KIO::ERR_SLAVE_DEFINED, i18n("Cannot copy file from %1 to %2. (Errno: %3)", src, dest, errno));
}
} else
#endif
error(KIO::ERR_CANNOT_READ, src);
src_file.close();
dest_file.close();
#if HAVE_POSIX_ACL
if (acl) {
acl_free(acl);
}
#endif
if (!QFile::remove(dest)) { // don't keep partly copied file
execWithElevatedPrivilege(DEL, {_dest}, errno);
}
return;
}
if (n == 0) {
break; // Finished
}
#ifdef USE_SENDFILE
if (!use_sendfile) {
#endif
if (dest_file.write(buffer, n) != n) {
if (dest_file.error() == QFileDevice::ResourceError) { // disk full
if (!_dest_backup.isEmpty() && !existing_dest_delete_attempted) {
::unlink(_dest_backup.constData());
existing_dest_delete_attempted = true;
continue;
}
error(KIO::ERR_DISK_FULL, dest);
} else {
qCWarning(KIO_FILE) << "Couldn't write[2]. Error:" << dest_file.errorString();
error(KIO::ERR_CANNOT_WRITE, dest);
}
#if HAVE_POSIX_ACL
if (acl) {
acl_free(acl);
}
#endif
if (!QFile::remove(dest)) { // don't keep partly copied file
execWithElevatedPrivilege(DEL, {_dest}, errno);
}
return;
}
processed_size += n;
#ifdef USE_SENDFILE
}
#endif
processedSize(processed_size);
}
#ifdef FICLONE
}
#endif
// Copy Extended attributes
#if HAVE_SYS_XATTR_H || HAVE_SYS_EXTATTR_H
if (!copyXattrs(src_file.handle(), dest_file.handle())) {
qCDebug(KIO_FILE) << "cant copy Extended attributes";
}
#endif
src_file.close();
dest_file.flush(); // so the write() happens before futimes()
// copy access and modification time
if (!wasKilled()) {
#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)
// with nano secs precision
struct timespec ut[2];
ut[0] = buff_src.st_atim;
ut[1] = buff_src.st_mtim;
// need to do this with the dest file still opened, or this fails
if (::futimens(dest_file.handle(), ut) != 0) {
#else
struct timeval ut[2];
ut[0].tv_sec = buff_src.st_atime;
ut[0].tv_usec = 0;
ut[1].tv_sec = buff_src.st_mtime;
ut[1].tv_usec = 0;
if (::futimes(dest_file.handle(), ut) != 0) {
#endif
if (tryChangeFileAttr(UTIME, {_dest, qint64(buff_src.st_atime), qint64(buff_src.st_mtime)}, errno)) {
qCWarning(KIO_FILE) << "Couldn't preserve access and modification time for" << dest;
}
}
}
dest_file.close();
if (wasKilled()) {
qCDebug(KIO_FILE) << "Clean dest file after ioslave was killed:" << dest;
if (!QFile::remove(dest)) { // don't keep partly copied file
execWithElevatedPrivilege(DEL, {_dest}, errno);
}
error(KIO::ERR_USER_CANCELED, dest);
return;
}
if (dest_file.error() != QFile::NoError) {
qCWarning(KIO_FILE) << "Error when closing file descriptor[2]:" << dest_file.errorString();
error(KIO::ERR_CANNOT_WRITE, dest);
#if HAVE_POSIX_ACL
if (acl) {
acl_free(acl);
}
#endif
if (!QFile::remove(dest)) { // don't keep partly copied file
execWithElevatedPrivilege(DEL, {_dest}, errno);
}
return;
}
// set final permissions
// if no special mode given, preserve the mode from the sourcefile
if (_mode == -1) {
_mode = buff_src.st_mode;