aboutsummaryrefslogtreecommitdiff
path: root/src/filesystem/AFPDirectory.cpp
blob: df88ace16444e82b5d21e4ca7e16da0296a1eaeb (plain)
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
/*
 *      Copyright (C) 2011-2013 Team XBMC
 *      http://xbmc.org
 *
 *  This Program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with XBMC; see the file COPYING.  If not, see
 *  <http://www.gnu.org/licenses/>.
 *
 */

#include "system.h"

#if defined(HAS_FILESYSTEM_AFP)
#include "AFPDirectory.h"
#include "AFPFile.h"
#include "Util.h"
#include "guilib/LocalizeStrings.h"
#include "Application.h"
#include "FileItem.h"
#include "settings/AdvancedSettings.h"
#include "utils/StringUtils.h"
#include "utils/log.h"
#include "utils/URIUtils.h"
#include "threads/SingleLock.h"
#include "PasswordManager.h"
#include "DllLibAfp.h"

struct CachedDirEntry
{
  unsigned int type;
  std::string name;
};

using namespace XFILE;
using namespace std;

CAFPDirectory::CAFPDirectory(void)
{
  gAfpConnection.AddActiveConnection();
}

CAFPDirectory::~CAFPDirectory(void)
{
  gAfpConnection.AddIdleConnection();
}

bool CAFPDirectory::ResolveSymlink( const std::string &dirName, const std::string &fileName,
                                    struct stat *stat, CURL &resolvedUrl)
{
  CSingleLock lock(gAfpConnection); 
  int ret = 0;  
  bool retVal = true;
  char resolvedLink[MAX_PATH];
  std::string fullpath = dirName;
  URIUtils::AddSlashAtEnd(fullpath);
  fullpath += fileName;
  
  CPasswordManager::GetInstance().AuthenticateURL(resolvedUrl);
  resolvedUrl.SetProtocol("afp");
  resolvedUrl.SetHostName(gAfpConnection.GetConnectedIp());   
  
  ret = gAfpConnection.GetImpl()->afp_wrap_readlink(gAfpConnection.GetVolume(), fullpath.c_str(), resolvedLink, MAX_PATH);    
  
  if(ret == 0)
  {
    fullpath = dirName;
    URIUtils::AddSlashAtEnd(fullpath);
    fullpath.append(resolvedLink);
 
    if(resolvedLink[0] == '/')
    {
      //use the special stat function for using an extra context
      //because we are inside of a dir traversation
      //and just can't change the global nfs context here
      //without destroying something...    
      fullpath = resolvedLink;
      fullpath.erase(0, 1);
      resolvedUrl.SetFileName(fullpath);     
      ret = gAfpConnection.stat(resolvedUrl, stat);
      if(ret < 0)
      {
        URIUtils::AddSlashAtEnd(fullpath);
        resolvedUrl.SetFileName(fullpath);     
        ret = gAfpConnection.stat(resolvedUrl, stat);
      }
    }
    else
    {
      ret = gAfpConnection.GetImpl()->afp_wrap_getattr(gAfpConnection.GetVolume(), fullpath.c_str(), stat);
      resolvedUrl.SetFileName(gAfpConnection.GetUrl()->volumename + fullpath);            
    }

    if (ret != 0) 
    {
      CLog::Log(LOGERROR, "AFP: Failed to stat(%s) on link resolve %s\n", fullpath.c_str(), strerror(errno));
      retVal = false;;
    }
  }
  else
  {
    CLog::Log(LOGERROR, "Failed to readlink(%s) %s\n", fullpath.c_str(), strerror(errno));
    retVal = false;
  }
  return retVal;
}


bool CAFPDirectory::GetDirectory(const CURL& url, CFileItemList &items)
{
  // We accept afp://[[user[:password@]]server[/share[/path[/file]]]]
  // silence gdb breaking on signal SIGUSR2 with "handle SIGUSR2 nostop noprint"
  bool bListVolumes = false;
  FILETIME fileTime, localTime;

  CSingleLock lock(gAfpConnection);
  CAfpConnection::afpConnnectError afpError = gAfpConnection.Connect(url);

  if (afpError != CAfpConnection::AfpOk || (!url.GetShareName().empty() && !gAfpConnection.GetVolume()))
  {
    if (afpError == CAfpConnection::AfpAuth)
    {
       if (m_flags & DIR_FLAG_ALLOW_PROMPT)
       {
         RequireAuthentication(url);
       }
    }
    return false;
  }
  std::string strDirName = gAfpConnection.GetPath(url);

  vector<CachedDirEntry> vecEntries;
  struct afp_file_info *dirEnt = NULL;
  struct afp_file_info *curDirPtr = NULL;

  // if no share name in url - try to fetch the volumes on the server and treat them like folders
  if (url.GetShareName().empty())
  {
    bListVolumes = true;
    struct afp_server *serv = gAfpConnection.GetServer();
    for (int i = 0; i < serv->num_volumes; i++)
    {
      CachedDirEntry aDir;
      aDir.type = 1;
      aDir.name = serv->volumes[i].volume_name;
      vecEntries.push_back(aDir);
    }
  }

  // if we not only list volumes - read the dir
  if (!bListVolumes)
  {
    if (gAfpConnection.GetImpl()->afp_wrap_readdir(gAfpConnection.GetVolume(), strDirName.c_str(), &dirEnt))
      return false;
    lock.Leave();

    for (curDirPtr = dirEnt; curDirPtr; curDirPtr = curDirPtr->next)
    {
      CachedDirEntry aDir;
      aDir.type = curDirPtr->isdir;
#ifdef USE_CVS_AFPFS
      aDir.name = curDirPtr->basic.name;
#else
      aDir.name = curDirPtr->name;
#endif
      vecEntries.push_back(aDir);
    }
    gAfpConnection.GetImpl()->afp_ml_filebase_free(&dirEnt);
  }

  std::string myStrPath(url.Get());
  URIUtils::AddSlashAtEnd(myStrPath); //be sure the dir ends with a slash
  for (size_t i = 0; i < vecEntries.size(); i++)
  {
    CachedDirEntry aDir = vecEntries[i];
    // We use UTF-8 internally, as does AFP
    std::string strFile = aDir.name;
    std::string path(myStrPath + strFile);

    if (strFile != "." && strFile != ".." && strFile != "lost+found")
    {
      int64_t iSize = 0;
      bool bIsDir = aDir.type;
      int64_t lTimeDate = 0;

      // if we not only list volumes - stat the files in folder
      if (!bListVolumes)
      {
        struct stat info = {0};

        if ((m_flags & DIR_FLAG_NO_FILE_INFO)==0 && g_advancedSettings.m_sambastatfiles)
        {
          // make sure we use the authenticated path wich contains any default username
          std::string strFullName = strDirName + strFile;

          lock.Enter();

          if (gAfpConnection.GetImpl()->afp_wrap_getattr(gAfpConnection.GetVolume(), strFullName.c_str(), &info) == 0)
          {                       
            //resolve symlinks
            if(S_ISLNK(info.st_mode))
            {
              CURL linkUrl(url);
              if(!ResolveSymlink(strDirName, strFile, &info, linkUrl))
              {
                lock.Leave();              
                continue;
              }
              path = linkUrl.Get();
              bIsDir = S_ISDIR(info.st_mode);            
            }
            lTimeDate = info.st_mtime;
            if (lTimeDate == 0) // if modification date is missing, use create date
              lTimeDate = info.st_ctime;
            iSize = info.st_size;
          }
          else
          {
            CLog::Log(LOGERROR, "%s - Failed to stat file %s (%s)", __FUNCTION__, strFullName.c_str(),strerror(errno));
          }

          lock.Leave();
        }
        LONGLONG ll = Int32x32To64(lTimeDate & 0xffffffff, 10000000) + 116444736000000000ll;
        fileTime.dwLowDateTime  = (DWORD)(ll & 0xffffffff);
        fileTime.dwHighDateTime = (DWORD)(ll >> 32);
        FileTimeToLocalFileTime(&fileTime, &localTime);
      }
      else
      {
        bIsDir = true;
        localTime.dwHighDateTime = 0;
        localTime.dwLowDateTime = 0;
      }
      
      CFileItemPtr pItem(new CFileItem(strFile));      
      pItem->m_dateTime  = localTime;    
      pItem->m_dwSize    = iSize;
      
      if (bIsDir)
      {
        URIUtils::AddSlashAtEnd(path);
        pItem->m_bIsFolder = true;
      }
      else
      {
        pItem->m_bIsFolder = false;
      }
 
      if (!aDir.name.empty() && aDir.name[0] == '.')
      {
        pItem->SetProperty("file:hidden", true);
      }

      pItem->SetPath(path);      
      items.Add(pItem);      
    }
  }

  return true;
}

bool CAFPDirectory::Create(const CURL& url)
{
  CSingleLock lock(gAfpConnection);

  if (gAfpConnection.Connect(url) != CAfpConnection::AfpOk || !gAfpConnection.GetVolume())
    return false;

  std::string strFilename = gAfpConnection.GetPath(url);

  int result = gAfpConnection.GetImpl()->afp_wrap_mkdir(gAfpConnection.GetVolume(), strFilename.c_str(), 0);

  if (result != 0)
    CLog::Log(LOGERROR, "%s - Error( %s )", __FUNCTION__, strerror(errno));

  return (result == 0 || EEXIST == result);
}

bool CAFPDirectory::Remove(const CURL& url)
{
  CSingleLock lock(gAfpConnection);

  if (gAfpConnection.Connect(url) != CAfpConnection::AfpOk || !gAfpConnection.GetVolume())
    return false;

  std::string strFileName = gAfpConnection.GetPath(url);

  int result = gAfpConnection.GetImpl()->afp_wrap_rmdir(gAfpConnection.GetVolume(), strFileName.c_str());

  if (result != 0 && errno != ENOENT)
  {
    CLog::Log(LOGERROR, "%s - Error( %s )", __FUNCTION__, strerror(errno));
    return false;
  }

  return true;
}

bool CAFPDirectory::Exists(const CURL& url)
{
  CSingleLock lock(gAfpConnection);

  if (gAfpConnection.Connect(url) != CAfpConnection::AfpOk || !gAfpConnection.GetVolume())
    return false;

  std::string strFileName(gAfpConnection.GetPath(url));

  struct stat info;
  if (gAfpConnection.GetImpl()->afp_wrap_getattr(gAfpConnection.GetVolume(), strFileName.c_str(), &info) != 0)
    return false;

  return S_ISDIR(info.st_mode);
}
#endif