~carlos-mazieri/ubuntu-filemanager-app/model

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
/**************************************************************************
 *
 * Copyright 2014 Canonical Ltd.
 * Copyright 2014 Carlos J Mazieri <carlos.mazieri@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * File: QTrashDir.cpp
 * Date: 06/02/2014
 */

#include "qtrashdir.h"
#include "qtrashutilinfo.h"

#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QStandardPaths>

#if defined(Q_OS_UNIX)
# include <sys/statvfs.h>
# include <unistd.h>
# include <sys/types.h>
# include <sys/stat.h>
#endif


QTrashDir::QTrashDir() : m_userId(::getuid())
{

}


bool QTrashDir::validate(const QString &trashDir, bool create) const
{
   bool ret = false;
   QFileInfo info(trashDir);
   if (!info.exists() && create)
   {
       createUserDir(info.absoluteFilePath());
   }
   if (checkUserDirPermissions(trashDir))
   {
       QString  files(QTrashUtilInfo::filesTrashDir(trashDir));
       QString  info(QTrashUtilInfo::infoTrashDir(trashDir));
       if ( (checkUserDirPermissions(files) || (create && createUserDir(files)))  &&
            (checkUserDirPermissions(info)  || (create && createUserDir(info)))
          )
       {
         ret = true;
       }
   }
   return ret;
}


bool QTrashDir::checkUserDirPermissions(const QString &dir) const
{
    QFileInfo f(dir);
    bool ret = false;   
    if ( f.isDir() && !f.isSymLink() )
    {
       QFile::Permissions permissions = f.permissions();
       bool owner   = permissions & (QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
       bool group   = permissions & (QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup);
       bool others  = permissions & (QFile::ReadOther | QFile::WriteOther | QFile::ExeOther);
       if (owner && !group && !others)
       {
           ret = true;
       }
    }
    return ret;
}


bool QTrashDir::createUserDir(const QString &dir) const
{  
    QFileInfo d(dir);
    bool ret = false;
    if ((d.exists() && d.isDir()) || QDir().mkpath(dir))
    {

        ret = QFile(dir).setPermissions(QFile::ReadOwner  |
                                        QFile::WriteOwner |
                                        QFile::ExeOwner);
    }
    return ret;
}


QString QTrashDir::homeTrash() const
{
   QString homeTrash;
   // If $XDG_DATA_HOME is either not set or empty, a default equal to
   //$HOME/.local/share should be used.
   QString xdg_home =   QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
   if (!xdg_home.isEmpty())
   {
       QString tmp(xdg_home+ QDir::separator() + QLatin1String("Trash"));
       if (validate(tmp,true))
       {
          homeTrash = tmp;
       }
   }
   return homeTrash;
}


/*!
 * \brief QTrashDir::isSharedTopDirWithStickBit
 * \param mountPoint this is the root (mount point directory)
 * \return true it the mount point has a .Trash folder with stick bit set
 */
bool QTrashDir::isMountPointSharedWithStickBit(const QString &mountPoint) const
{
   bool ret = false;;
   QFileInfo trashDir(mountPoint + QDir::separator() + ".Trash");
#if DEBUG_MESSAGES
          qDebug() << Q_FUNC_INFO << trashDir.absoluteFilePath() ;
#endif
   if (trashDir.isDir() && !trashDir.isSymLink() && trashDir.isWritable())
   {
        //QFileInfo does not work for stick bit, using stat() instead
        struct stat  vfs;
        if (::stat(QFile::encodeName(trashDir.absoluteFilePath()).constData(), &vfs) == 0)
        {
          ret =  vfs.st_mode  & S_ISVTX;
#if DEBUG_MESSAGES
          qDebug() << Q_FUNC_INFO << trashDir.absoluteFilePath()
                   << QString::number(vfs.st_mode, 8)
                   << QString::number(vfs.st_mode, 16) << "ret" << ret;
#endif
       }
   }
   return ret;
}


QString QTrashDir::getMountPoint(const QString &fileOrDir) const
{
   unsigned long   fileOrDirFsId = 0xffff;
   unsigned long   parentFsId    = 0xffff;
   struct statvfs  vfs;
   QString         ret;
   QFileInfo       finfo(fileOrDir);

   if ( finfo.exists() &&
        ::statvfs( QFile::encodeName(finfo.canonicalFilePath()).constData(), &vfs) == 0 )
   {
       parentFsId =  fileOrDirFsId =  vfs.f_fsid;
       while (!finfo.isRoot() && fileOrDirFsId == parentFsId)
       {
           finfo.setFile(finfo.canonicalPath());
           if ( ::statvfs( QFile::encodeName(finfo.canonicalPath()).constData(), &vfs) == 0 )
           {
               parentFsId =  vfs.f_fsid;
           }
       }
       ret = finfo.canonicalFilePath();
   }
   return ret;
}




/*!
 * \brief QTrashDir::mountedPoints()
 * \return a list of mounted directories from /etc/mtab
 *
 * \note
 */
QStringList QTrashDir::mountedPoints() const
{
    QStringList mountPoints;
    QFile  mtab(QLatin1String("/etc/mtab"));
    if (mtab.open(QFile::ReadOnly))
    {
        QString line = mtab.readLine();
        while (!line.isEmpty())
        {
            QStringList items = line.split(QLatin1Char(' '));
            if (items.count() > 2)
            {
               if (items.first() != (QLatin1String("proc")) &&
                   items.first() != (QLatin1String("sysfs")) &&
                   items.first() != (QLatin1String("none")) &&
                   items.first() != (QLatin1String("udev")) &&
                   items.first() != (QLatin1String("devpts")) &&
                   items.first() != (QLatin1String("tmpfs")) &&
                   items.first() != (QLatin1String("systemd"))
                  )
               {
                   mountPoints.append(items.at(1));
               }
            }
            line = mtab.readLine();
        }
        mtab.close();
        ::qSort(mountPoints);
    }
#if DEBUG_MESSAGES
          qDebug() << Q_FUNC_INFO << "mount points:" << mountPoints;
#endif
    return mountPoints;
}


QStringList QTrashDir::allTrashes() const
{
    QStringList trashes;
    QString    trashDir(homeTrash());
    if (!trashDir.isEmpty())
    {
        trashes.append(trashDir);
    }
    QStringList mounted = mountedPoints();
    foreach(const QString& mp, mounted)
    {
       trashDir = getSharedTopTrashDir(mp);
       if (!trashDir.isEmpty())
       {
           trashes.append(trashDir);
       }
       trashDir = getSingleTopTrashDir(mp);
       if (!trashDir.isEmpty())
       {
           trashes.append(trashDir);
       }
    }
#if DEBUG_MESSAGES
          qDebug() << Q_FUNC_INFO << "trashes:" << trashes;
#endif
    return trashes;
}


QString QTrashDir::getSuitableTopTrashDir(const QString &mountPoint) const
{
    QString trashDir(getSharedTopTrashDir(mountPoint));
    //if previous shared mountPoint/Trash/$uid failed
    //try  mountPoint/Trash-$uid
    if (trashDir.isEmpty())
    {
        trashDir = getSingleTopTrashDir(mountPoint, true);
    }
    return trashDir;
}


QString QTrashDir::getSharedTopTrashDir(const QString &mountPoint) const
{
    QString trashDir;
    QString userTrash(mountPoint + QDir::separator() +
                      QLatin1Literal(".Trash"));
    if (isMountPointSharedWithStickBit(mountPoint))
    {
        QString userInsideSharedTrash(userTrash +
                                     QDir::separator() +
                                     QString::number(m_userId)
                                     );
        if (validate(userInsideSharedTrash, true))
        {
            trashDir = userInsideSharedTrash;
        }
    }
    return trashDir;
}


QString QTrashDir::getSingleTopTrashDir(const QString &mountPoint, bool create ) const
{
    QString trashDir;
    QString userTrash(mountPoint + QDir::separator() +
                      QLatin1Literal(".Trash"));
    userTrash += QLatin1Char('-') + QString::number(m_userId);
    if (validate(userTrash, create))
    {
           trashDir = userTrash;
    }
    return trashDir;
}


QString QTrashDir::suitableTrash(const QString &fullPathName) const
{
    QFileInfo fi(fullPathName);
    QString trashDir;
    QString homeTrashDir(homeTrash());
    if (fi.exists())
    {
         //first case file/dir is under other directory than Home
         if (!fi.canonicalPath().startsWith(QDir::homePath()))
         {
             QString topDir = getMountPoint(fi.canonicalFilePath());
             trashDir  = getSuitableTopTrashDir(topDir);
             //check if the file/dir intended to be moved into Trash does belong to Trash Dir itself
             if (!trashDir.isEmpty() &&
                  fi.canonicalFilePath().startsWith(trashDir)
                )
             {
                 trashDir.clear();
             }
         }
         //check AGAIN if the file/dir intended to be moved into Trash does belong to Trash Dir itself
         if ( trashDir.isEmpty() &&
              fi.canonicalFilePath() != QDir::homePath() &&
              !fi.canonicalFilePath().startsWith(homeTrashDir)
              )
         {
             trashDir = homeTrashDir;
         }
    }
    return trashDir;
}


bool QTrashDir::suitableTrash(const QString &fullPathName, QTrashUtilInfo &fullInfo) const
{
    fullInfo.setInfo(suitableTrash(fullPathName), fullPathName);
    return fullInfo.isValid();
}