Device.cpp 8.92 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * 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; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * 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, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
23
#include "Device.h"
24
25
26
#include "Directory.h"
#include "utils/Filename.h"
#include "logging/Logger.h"
27

28
#include <algorithm>
29
#include <cstring>
30
31
32
33
34
35
#include <cstdio>
#include <dirent.h>
#include <limits.h>
#include <mntent.h>
#include <unistd.h>
#include <sys/types.h>
36
37
38
39

namespace
{
    // Allow private ctors to be used from make_shared
40
    struct DeviceBuilder : public fs::Device
41
    {
42
43
        template <typename... Args>
        DeviceBuilder( Args&&... args ) : Device( std::forward<Args>( args )... ) {}
44
45
46
47
48
49
    };
}

namespace fs
{

50
51
52
Device::DeviceMap Device::Devices;
Device::MountpointMap Device::Mountpoints;
Device::DeviceCacheMap Device::DeviceCache;
53

54
55
56
Device::Device( const std::string& uuid, const std::string& mountpoint, bool isRemovable )
    : m_uuid( uuid )
    , m_mountpoint( mountpoint )
57
    , m_present( true )
58
    , m_removable( isRemovable )
59
60
61
{
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
62
const std::string& Device::uuid() const
63
64
65
66
{
    return m_uuid;
}

67
bool Device::isRemovable() const
68
{
69
    return m_removable;
70
71
}

72
73
74
75
76
bool Device::isPresent() const
{
    return m_present;
}

77
const std::string&Device::mountpoint() const
78
{
79
    return m_mountpoint;
80
81
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
82
std::shared_ptr<IDevice> Device::fromPath( const std::string& path )
83
{
84
85
    std::shared_ptr<IDevice> res;
    for ( const auto& p : DeviceCache )
86
    {
87
88
89
90
91
        if ( path.find( p.second->mountpoint() ) == 0 )
        {
            if ( res == nullptr || res->mountpoint().length() < p.second->mountpoint().length() )
                res = p.second;
        }
92
    }
93
    return res;
94
95
}

96
97
std::shared_ptr<IDevice> Device::fromUuid( const std::string& uuid )
{
98
99
100
    auto it = DeviceCache.find( uuid );
    if ( it != end( DeviceCache ) )
        return it->second;
101
102
103
    return nullptr;
}

104
105
106
107
108
109
110
111
bool Device::populateCache()
{
    Devices = listDevices();
    Mountpoints = listMountpoints();
    DeviceCache = populateDeviceCache();
    return true;
}

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
112
Device::DeviceMap Device::listDevices()
113
{
114
115
116
117
118
119
120
121
122
123
124
125

    static const std::vector<std::string> deviceBlacklist = { "loop", "dm-" };
    const std::string devPath = "/dev/disk/by-uuid/";
    // Don't use fs::Directory to iterate, as it resolves the symbolic links automatically.
    // We need the link name & what it points to.
    std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( devPath.c_str() ), &closedir );
    if ( dir == nullptr )
    {
        std::stringstream err;
        err << "Failed to open /dev/disk/by-uuid: " << strerror(errno);
        throw std::runtime_error( err.str() );
    }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
126
    DeviceMap res;
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
    dirent* result = nullptr;

    while ( ( result = readdir( dir.get() ) ) != nullptr )
    {
        if ( strcmp( result->d_name, "." ) == 0 ||
             strcmp( result->d_name, ".." ) == 0 )
        {
            continue;
        }
        std::string path = devPath + result->d_name;
        char linkPath[PATH_MAX] = {};
        if ( readlink( path.c_str(), linkPath, PATH_MAX ) < 0 )
        {
            std::stringstream err;
            err << "Failed to resolve uuid -> device link: "
                << result->d_name << " (" << strerror(errno) << ')';
            throw std::runtime_error( err.str() );
        }
        auto deviceName = utils::file::fileName( linkPath );
        if ( std::find_if( begin( deviceBlacklist ), end( deviceBlacklist ), [&deviceName]( const std::string& pattern ) {
                return deviceName.length() >= pattern.length() && deviceName.find( pattern ) == 0;
            }) != end( deviceBlacklist ) )
            continue;
        auto uuid = result->d_name;
        LOG_INFO( "Discovered device ", deviceName, " -> {", uuid, '}' );
        res[deviceName] = uuid;
    }
    return res;
}

Device::MountpointMap Device::listMountpoints()
{
    static const std::vector<std::string> allowedFsType = { "vfat", "exfat", "sdcardfs", "fuse",
                                                            "ntfs", "fat32", "ext3", "ext4", "esdfs" };
    MountpointMap res;
162
163
164
    FILE* f = setmntent("/etc/mtab", "r");
    if ( f == nullptr )
        throw std::runtime_error( "Failed to read /etc/mtab" );
165
    std::unique_ptr<FILE, int(*)(FILE*)> fPtr( f, &endmntent );
166
167
    char buff[512];
    mntent s;
168
    errno = 0;
169
170
    while ( getmntent_r( f, &s, buff, sizeof(buff) ) != nullptr )
    {
171
        if ( std::find( begin( allowedFsType ), end( allowedFsType ), s.mnt_type ) == end( allowedFsType ) )
172
            continue;
173
        auto deviceName = s.mnt_fsname;
174
        LOG_INFO( "Discovered mountpoint ", deviceName, " mounted on ", s.mnt_dir, " (", s.mnt_type, ')' );
175
176
        res[deviceName] = s.mnt_dir;
        errno = 0;
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
    if ( errno != 0 )
    {
        LOG_ERROR( "Failed to read mountpoints: ", strerror( errno ) );
    }
    return res;
}

Device::DeviceCacheMap Device::populateDeviceCache()
{
    Device::DeviceCacheMap res;
    for ( const auto& p : Mountpoints )
    {
        const auto& devicePath = p.first;
        auto deviceName = utils::file::fileName( devicePath );
        const auto& mountpoint = p.second;
        auto it = Devices.find( deviceName );
        std::string uuid;
        if ( it != end( Devices ) )
            uuid = it->second;
        else
        {
            deviceName = deviceFromDeviceMapper( devicePath );
            it = Devices.find( deviceName );
            if ( it != end( Devices ) )
                uuid = it->second;
            else
            {
                LOG_ERROR( "Failed to resolve mountpoint ", mountpoint, " to any known device" );
                continue;
            }
        }
209
        auto removable = isRemovable( deviceName, mountpoint );
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
        LOG_INFO( "Adding device to cache: {", uuid, "} mounted on ", mountpoint, " Removable: ", removable );
        res[uuid] = std::make_shared<DeviceBuilder>( uuid, mountpoint, removable );
    }
    return res;
}

std::string Device::deviceFromDeviceMapper( const std::string& devicePath )
{
    if ( devicePath.find( "/dev/mapper" ) != 0 )
        return {};
    char linkPath[PATH_MAX];
    if ( readlink( devicePath.c_str(), linkPath, PATH_MAX ) < 0 )
    {
        std::stringstream err;
        err << "Failed to resolve device -> mapper link: "
            << devicePath << " (" << strerror(errno) << ')';
        throw std::runtime_error( err.str() );
    }
    const auto dmName = utils::file::fileName( linkPath );
    std::string dmSlavePath = "/sys/block/" + dmName + "/slaves";
    std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( dmSlavePath.c_str() ), &closedir );
    std::string res;
    if ( dir == nullptr )
        return {};
    dirent* result;
    while ( ( result = readdir( dir.get() ) ) != nullptr )
    {
        if ( strcmp( result->d_name, "." ) == 0 ||
             strcmp( result->d_name, ".." ) == 0 )
        {
            continue;
        }
        if ( res.empty() == true )
            res = result->d_name;
        else
            LOG_WARN( "More than one slave for device mapper ", linkPath );
    }
    LOG_INFO( "Device mapper ", dmName, " maps to ", res );
248
249
250
    return res;
}

251
bool Device::isRemovable( const std::string& deviceName, const std::string& mountpoint )
252
{
253
254
#ifndef TIZEN
    (void)mountpoint;
255
256
257
258
259
260
261
262
263
264
    std::stringstream removableFilePath;
    removableFilePath << "/sys/block/" << deviceName << "/removable";
    std::unique_ptr<FILE, int(*)(FILE*)> removableFile( fopen( removableFilePath.str().c_str(), "r" ), &fclose );
    // Assume the file isn't removable by default
    if ( removableFile != nullptr )
    {
        char buff;
        fread(&buff, sizeof(buff), 1, removableFile.get() );
        return buff == '1';
    }
265
266
267
268
269
270
271
272
273
274
275
276
#else
    (void)deviceName;
    static const std::vector<std::string> SDMountpoints = { "/opt/storage/sdcard" };
    auto it = std::find_if( begin( SDMountpoints ), end( SDMountpoints ), [mountpoint]( const std::string& pattern ) {
        return mountpoint.length() >= pattern.length() && mountpoint.find( pattern ) == 0;
    });
    if ( it != end( SDMountpoints ) )
    {
        LOG_INFO( "Considering mountpoint ", mountpoint, " a removable SDCard" );
        return true;
    }
#endif
277
278
279
    return false;
}

280
}