Welcome to mirror list, hosted at ThFree Co, Russian Federation.

NesMiniFileSystemHandler.cs « FtpServer - github.com/ClusterM/hakchi2.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c505cb382478a3656b7aa9cef4accbef6930d9b4 (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
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
using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using com.clusterrr.clovershell;
using System.Globalization;

namespace mooftpserv
{
    public class NesMiniFileSystemHandler : IFileSystemHandler
    {
        // list of supported operating systems
        private enum OS { WinNT, WinCE, Unix };

        // currently used operating system
        private OS os;
        // current path as TVFS or unix-like
        private string currentPath;
        // clovershell
        private ClovershellConnection clovershell;

        public NesMiniFileSystemHandler(ClovershellConnection clovershell, string startPath)
        {
            os = OS.Unix;
            this.currentPath = startPath;
            this.clovershell = clovershell;
        }

        public NesMiniFileSystemHandler(ClovershellConnection clovershell)
            : this(clovershell, "/")
        {
        }

        private NesMiniFileSystemHandler(string path, OS os, ClovershellConnection clovershell)
        {
            this.currentPath = path;
            this.os = os;
            this.clovershell = clovershell;
        }

        public IFileSystemHandler Clone(IPEndPoint peer)
        {
            return new NesMiniFileSystemHandler(currentPath, os, clovershell);
        }

        public ResultOrError<string> GetCurrentDirectory()
        {
            return MakeResult<string>(currentPath);
        }

        public ResultOrError<string> ChangeDirectory(string path)
        {
            string newPath = ResolvePath(path);
            try
            {
                clovershell.ExecuteSimple("cd \""+newPath+"\"", 1000 ,true);
                currentPath = newPath;
            }
            catch (Exception ex)
            {
                return MakeError<string>(ex.Message);
            }
            return MakeResult<string>(newPath);
        }

        public ResultOrError<string> ChangeToParentDirectory()
        {
            return ChangeDirectory("..");
        }

        public ResultOrError<string> CreateDirectory(string path)
        {
            string newPath = ResolvePath(path);
            try
            {
                foreach (var c in newPath)
                    if ((int)c > 255) throw new Exception("Invalid characters in directory name");
                var newpath = DecodePath(newPath);
                clovershell.ExecuteSimple("mkdir \"" + newpath + "\"");
            }
            catch (Exception ex)
            {
                return MakeError<string>(ex.Message);
            }

            return MakeResult<string>(newPath);
        }

        public ResultOrError<bool> RemoveDirectory(string path)
        {
            string newPath = ResolvePath(path);

            try
            {
                var rpath = DecodePath(newPath);
                clovershell.ExecuteSimple("rm -rf \"" + rpath + "\"");
            }
            catch (Exception ex)
            {
                return MakeError<bool>(ex.Message);
            }

            return MakeResult<bool>(true);
        }

        public ResultOrError<Stream> ReadFile(string path)
        {
            string newPath = ResolvePath(path);
            try
            {
                var data = new MemoryStream();
                clovershell.Execute("cat \"" + newPath + "\"", null, data, null, 1000, true);
                data.Seek(0, SeekOrigin.Begin);
                return MakeResult<Stream>(data);
            }
            catch (Exception ex)
            {
                return MakeError<Stream>(ex.Message);
            }
        }

        public ResultOrError<Stream> WriteFile(string path)
        {
            string newPath = ResolvePath(path);
            try
            {
                foreach (var c in newPath)
                    if ((int)c > 255) throw new Exception("Invalid characters in directory name");
                return MakeResult<Stream>(new MemoryStream());
            }
            catch (Exception ex)
            {
                return MakeError<Stream>(ex.Message);
            }
        }

        public ResultOrError<bool> WriteFileFinalize(string path, Stream str)
        {
            string newPath = ResolvePath(path);
            try
            {
                str.Seek(0, SeekOrigin.Begin);
                string directory = "/";
                int p = newPath.LastIndexOf("/");
                if (p > 0)
                    directory = newPath.Substring(0, p);
                clovershell.Execute("mkdir -p \"" + directory + "\" && cat > \"" + newPath + "\"", str, null, null, 1000, true);
                str.Dispose();
                return MakeResult<bool>(true);
            }
            catch (Exception ex)
            {
                return MakeError<bool>(ex.Message);
            }
        }

        public ResultOrError<bool> RemoveFile(string path)
        {
            string newPath = ResolvePath(path);

            try
            {
                clovershell.ExecuteSimple("rm -rf \"" + newPath + "\"", 1000, true);
            }
            catch (Exception ex)
            {
                return MakeError<bool>(ex.Message);
            }

            return MakeResult<bool>(true);
        }

        public ResultOrError<bool> RenameFile(string fromPath, string toPath)
        {
            fromPath = ResolvePath(fromPath);
            toPath = ResolvePath(toPath);
            try
            {
                clovershell.ExecuteSimple("mv \"" + fromPath + "\" \"" + toPath + "\"", 1000, true);
            }
            catch (Exception ex)
            {
                return MakeError<bool>(ex.Message);
            }

            return MakeResult<bool>(true);
        }

        public ResultOrError<FileSystemEntry[]> ListEntries(string path)
        {
            string newPath = ResolvePath(path);
            List<FileSystemEntry> result = new List<FileSystemEntry>();
            try
            {
                var lines = clovershell.ExecuteSimple("ls -lAp \"" + newPath + "\"", 1000, true)
                    .Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var line in lines)
                {
                    if (line.StartsWith("total")) continue;
                    FileSystemEntry entry = new FileSystemEntry();
                    entry.Mode = line.Substring(0, 13).Trim();
                    entry.Name = line.Substring(57).Trim();
                    entry.IsDirectory = entry.Name.EndsWith("/");
                    if (entry.IsDirectory) entry.Name = entry.Name.Substring(0, entry.Name.Length - 1);
                    entry.Size = long.Parse(line.Substring(34, 9).Trim());
                    var dt = line.Substring(44, 12).Trim();
                    try
                    {
                        entry.LastModifiedTimeUtc = DateTime.ParseExact(dt, "MMM  d HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowInnerWhite);
                    }
                    catch (FormatException)
                    {
                        entry.LastModifiedTimeUtc = DateTime.ParseExact(dt, "MMM  d yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowInnerWhite);
                    }
                    result.Add(entry);
                }
            }
            catch (Exception ex)
            {
                return MakeError<FileSystemEntry[]>(ex.Message);
            }
            return MakeResult<FileSystemEntry[]>(result.ToArray());
        }

        public ResultOrError<string> ListEntriesRaw(string path)
        {
            if (path == null)
                path = "/";
            if (path.StartsWith("-"))
                path = ". " + path;
            string newPath = ResolvePath(path);
            List<string> result = new List<string>();
            try
            {
                var lines = clovershell.ExecuteSimple("ls " + newPath, 1000, true);
                return MakeResult<string>(lines);
            }
            catch (Exception ex)
            {
                return MakeError<string>(ex.Message);
            }
        }

        public ResultOrError<long> GetFileSize(string path)
        {
            string newPath = ResolvePath(path);
            try
            {
                var size = clovershell.ExecuteSimple("stat -c%s \"" + newPath + "\"", 1000, true);
                return MakeResult<long>(long.Parse(size));
            }
            catch (Exception ex)
            {
                return MakeError<long>(ex.Message);
            }
        }

        public ResultOrError<DateTime> GetLastModifiedTimeUtc(string path)
        {
            string newPath = ResolvePath(path);
            try
            {
                var time = clovershell.ExecuteSimple("stat -c%Z \"" + newPath + "\"", 1000, true);
                return MakeResult<DateTime>(DateTime.FromFileTime(long.Parse(time)));
            }
            catch (Exception ex)
            {
                return MakeError<DateTime>(ex.Message);
            }
        }

        private string ResolvePath(string path)
        {
            if (path == null) return currentPath;
            if (path.Contains(" -> "))
                path = path.Substring(path.IndexOf(" -> ") + 4);
            return FileSystemHelper.ResolvePath(currentPath, path);
        }

        private string EncodePath(string path)
        {
            if (os == OS.WinNT)
                return "/" + path[0] + (path.Length > 2 ? path.Substring(2).Replace(@"\", "/") : "");
            else if (os == OS.WinCE)
                return path.Replace(@"\", "/");
            else
                return path;
        }

        private string DecodePath(string path)
        {
            if (path == null || path == "" || path[0] != '/')
                return null;

            if (os == OS.WinNT)
            {
                // some error checking for the drive layer
                if (path == "/")
                    return null; // should have been caught elsewhere

                if (path.Length > 1 && path[1] == '/')
                    return null;

                if (path.Length > 2 && path[2] != '/')
                    return null;

                if (path.Length < 4) // e.g. "/C/"
                    return path[1] + @":\";
                else
                    return path[1] + @":\" + path.Substring(3).Replace("/", @"\");
            }
            else if (os == OS.WinCE)
            {
                return path.Replace("/", @"\");
            }
            else
            {
                return path;
            }
        }

        /// <summary>
        /// Shortcut for ResultOrError<T>.MakeResult()
        /// </summary>
        private ResultOrError<T> MakeResult<T>(T result)
        {
            return ResultOrError<T>.MakeResult(result);
        }

        /// <summary>
        /// Shortcut for ResultOrError<T>.MakeError()
        /// </summary>
        private ResultOrError<T> MakeError<T>(string error)
        {
            return ResultOrError<T>.MakeError(error);
        }

        public ResultOrError<bool> ChmodFile(string mode, string path)
        {
            string newPath = ResolvePath(path);
            try
            {
                clovershell.ExecuteSimple(string.Format("chmod {0} {1}", mode, newPath), 1000, true);
                return ResultOrError<bool>.MakeResult(true);
            }
            catch (Exception ex)
            {
                return MakeError<bool>(ex.Message);
            }
        }

        public ResultOrError<bool> SetLastModifiedTimeUtc(string path, DateTime time)
        {
            string newPath = ResolvePath(path);
            try
            {
                clovershell.ExecuteSimple(string.Format("touch -ct {0:yyyyMMddHHmm.ss} \"{1}\"", time, newPath), 1000, true);
                return ResultOrError<bool>.MakeResult(true);
            }
            catch (Exception ex)
            {
                return MakeError<bool>(ex.Message);
            }
        }
    }
}