1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <objmng/drm_file.h>
18
19#include <unistd.h>
20#include <sys/param.h>
21#include <sys/stat.h>
22#include <stdio.h>
23#include <fcntl.h>
24#include <dirent.h>
25#include <errno.h>
26#include <string.h>
27
28/**
29 * Fails on zaurus?
30 #define DEVICE_FILESYSTEM
31*/
32#define DEFAULT_TOTAL_SPACE (4L * 1024L * 1024L) /* 4 Meg. */
33
34#ifndef DEVICE_FILESYSTEM
35/* Store the total space on FS VM can use. */
36static int32_t totalSpace;
37/* how many remain space can VM use. */
38static int32_t availableSize;
39#endif
40
41extern char* getStorageRoot(void);
42
43static char tmpPathBuf1[MAX_FILENAME_LEN];
44static char tmpPathBuf2[MAX_FILENAME_LEN];
45
46static int32_t
47convertFilename(const uint16_t *strData, int32_t strLength, char *buffer);
48
49static int calcDirSize(char *path, int len, uint8_t includeSubdirs);
50
51#ifndef DEVICE_FILESYSTEM
52static void initFsVariables(void);
53#endif
54
55/**
56 * Convert a Java string into a nul terminated ascii string to pass to posix
57 * @param strData    first character of name
58 * @param strLength  number of characters in name
59 * @param buffer Buffer to store terminated string in (at least MAXPATHLEN)
60 * @return Length of filename in characters (excl. nul), or -1 on failure.
61 */
62static int32_t
63convertFilename(const uint16_t *strData, int32_t strLength, char *buffer)
64{
65    int idx;
66
67    if (strLength >= (MAXPATHLEN-1))
68    {
69        Trace("convertFilename '%.*S' too long", strLength, strData);
70        return -1;
71    }
72
73    for (idx = 0; idx < strLength; ++idx)
74        *buffer++ = (char)*strData++;
75
76    *buffer = 0;
77    return strLength;
78}
79
80
81/**
82 * Perform a stat() call on the given filename.
83 * Helper for getFileLength and exists
84 * @param name unicode name
85 * @param nameLen number of unicode characters in name
86 * @param sbuf stat buffer
87 * @return TRUE on success, FALSE on failure
88 */
89static int32_t
90getFileStat(const uint16_t *name, int32_t nameLen, struct stat *sbuf)
91{
92    Trace("getFileStat: %.*S", nameLen, name);
93
94    if (convertFilename(name, nameLen, tmpPathBuf1) <= 0)
95    {
96        Trace("getFileStat: bad filename");
97    }
98    else if (stat(tmpPathBuf1, sbuf) != 0)
99    {
100        Trace("getFileStat %s: stat() errno=%d", tmpPathBuf1, errno);
101    }
102    else /* Successful */
103    {
104        return TRUE;
105    }
106
107    return FALSE;
108}
109
110#ifndef DEVICE_FILESYSTEM
111/**
112 * initial the variables like totalSpace, availableSize...
113 */
114static void initFsVariables(void)
115{
116    totalSpace = DEFAULT_TOTAL_SPACE;
117
118    availableSize = totalSpace;
119}
120#endif /* DEVICE_FILESYSTEM */
121
122/**
123 * calculate the size of everything inside path pointed directory
124 * this function will use path pointed buffer to store some extra info
125 * so param len is needed.
126 * @param path    the directory path need to calculate
127 * @param len   length of the path buffer, not the path string length
128 * @param includeSubdirs  also calculate all the subdirs in path holds?
129 * @return the calculated size, DRM_FILE_FAILURE on failure.
130 */
131static int calcDirSize(char *path, int len, uint8_t includeSubdirs)
132{
133    struct dirent *ent;
134    struct stat stat_buf;
135
136    DIR *dir = NULL;
137    int size = 0;
138    int exists = -1;
139    int dirPathLen = strlen(path);
140
141    /* Ensure space for wildcard */
142    if((dirPathLen + 2) >= MAXPATHLEN || (dirPathLen + 2) >= len)
143    {
144        return DRM_FILE_FAILURE;
145    }
146
147    if(path[dirPathLen - 1] != '/')
148    {
149        path[dirPathLen++] = '/';
150        path[dirPathLen] = '\0';
151    }
152
153    dir = opendir(path);
154    if (dir == NULL)
155    {
156        return DRM_FILE_FAILURE;
157    }
158
159    while ((ent = readdir(dir)) != NULL )
160    {
161        if (strcmp(ent->d_name, ".") == 0 ||
162                strcmp(ent->d_name, "..") == 0)
163        {
164            continue;
165        }
166
167        path[dirPathLen] = '\0';
168        if ((int)(strlen(ent->d_name) + dirPathLen + 1) < len)
169        {
170            strcat(path, ent->d_name);
171        }
172        else
173        {
174            continue;
175        }
176
177        exists = stat(path, &stat_buf);
178        if (exists != -1)
179        {
180            /* exclude the storage occupied by directory itself */
181            if (stat_buf.st_mode & S_IFDIR)
182            {
183                if(includeSubdirs)
184                {
185                    /* calculate the size recursively */
186                    int ret;
187                    ret = calcDirSize(path, len, includeSubdirs);
188                    /* ignore failure in subdirs */
189                    if( DRM_FILE_FAILURE != ret )
190                    {
191                        size += ret;
192                    }
193                }
194            }
195            else
196            {
197                size += stat_buf.st_size;
198            }
199        }
200    }
201
202    closedir(dir);
203    return size;
204}
205
206/* see drm_file.h */
207int32_t DRM_file_startup(void)
208{
209    Trace("DRM_file_startup");
210
211#ifndef DEVICE_FILESYSTEM
212    availableSize = -1;
213
214    initFsVariables();
215#endif
216
217    return DRM_FILE_SUCCESS;    /* Nothing to do */
218}
219
220/* see drm_file.h */
221int32_t
222DRM_file_listOpen(const uint16_t *prefix,
223                    int32_t prefixLen,
224                    int32_t* session,
225                    int32_t* iteration)
226{
227    Trace("DRM_file_listOpen: %.*S", prefixLen, prefix);
228
229    if (convertFilename(prefix, prefixLen, tmpPathBuf1) <= 0)
230    {
231        Trace("DRM_file_listOpen: bad filename");
232    }
233    else
234    {
235        DIR *dir;
236
237        /* find the last /, and store the offset to the leaf prefix in
238         * *iteration
239         */
240
241        char *sep = strrchr(tmpPathBuf1, '/');
242        /* Root "/" is a leaf */
243        if (sep == NULL || ((sep != NULL) && (sep == tmpPathBuf1)))
244        {
245            *iteration = prefixLen;
246
247#ifdef TRACE_ON
248            sep = " <empty>"; /* trace will show sep+1 */
249#endif
250        }
251        else
252        {
253            *iteration = sep - tmpPathBuf1 + 1;
254            *sep = 0;
255        }
256
257        dir = opendir(tmpPathBuf1);
258
259        if (dir == NULL)
260        {
261            Trace("DRM_file_listOpen: opendir %s: errno=%d", tmpPathBuf1, errno);
262        }
263        else
264        {
265            Trace("DRM_file_listOpen: dir %s, filter %s", tmpPathBuf1, sep+1);
266            *session = (int32_t)dir;
267            return DRM_FILE_SUCCESS;
268        }
269    }
270
271    return DRM_FILE_FAILURE;
272}
273
274/* see drm_file.h */
275int32_t
276DRM_file_listNextEntry(const uint16_t *prefix, int32_t prefixLen,
277                       uint16_t* entry, int32_t entrySize,
278                       int32_t *session, int32_t* iteration)
279{
280    struct dirent *ent;
281
282    /* We stored the offset of the leaf part of the prefix (if any)
283     * in *iteration
284     */
285    const uint16_t* strData   = prefix + *iteration;
286    int32_t   strLength = prefixLen - *iteration;
287
288    /* entrySize is bytes for some reason. Convert to ucs chars */
289    entrySize /= 2;
290
291    /* Now we want to filter for files which start with the (possibly empty)
292     * sequence at strData. We have to return fully-qualified filenames,
293     * which means *iteration characters from prefix, plus the
294     * leaf name.
295     */
296
297    while ( (ent = readdir((DIR *)*session)) != NULL)
298    {
299        int len = strlen(ent->d_name);
300
301        if ( (len + *iteration) > entrySize)
302        {
303            Trace("DRM_file_listNextEntry: %s too long", ent->d_name);
304        }
305        else if (strcmp(ent->d_name, ".") != 0 &&
306                 strcmp(ent->d_name, "..") != 0)
307        {
308            int idx;
309            struct stat sinfo;
310
311            /* check against the filter */
312
313            for (idx = 0; idx < strLength; ++idx)
314            {
315                if (ent->d_name[idx] != strData[idx])
316                    goto next_name;
317            }
318
319            Trace("DRM_file_listNextEntry: matched %s", ent->d_name);
320
321            /* Now generate the fully-qualified name */
322
323            for (idx = 0; idx < *iteration; ++idx)
324                entry[idx] = prefix[idx];
325
326            for (idx = 0; idx < len; ++idx)
327                entry[*iteration + idx] = (unsigned char)ent->d_name[idx];
328
329            /*add "/" at the end of a DIR file entry*/
330            if (getFileStat(entry, idx + *iteration, &sinfo)){
331                if (S_ISDIR(sinfo.st_mode) &&
332                        (idx + 1 + *iteration) < entrySize) {
333                    entry[*iteration + idx] = '/';
334                    ++idx;
335                }
336            }
337            else
338            {
339                Trace("DRM_file_listNextEntry: stat FAILURE on %.*S",
340                      idx + *iteration, entry);
341            }
342            Trace("DRM_file_listNextEntry: got %.*S", idx + *iteration, entry);
343
344            return idx + *iteration;
345        }
346
347    next_name:
348        Trace("DRM_file_listNextEntry: rejected %s", ent->d_name);
349    }
350
351    Trace("DRM_file_listNextEntry: end of list");
352    return 0;
353}
354
355/* see drm_file.h */
356int32_t
357DRM_file_listClose(int32_t session, int32_t iteration)
358{
359    closedir( (DIR *)session);
360    return DRM_FILE_SUCCESS;
361}
362
363/* see drm_file.h */
364int32_t
365DRM_file_getFileLength(const uint16_t *name, int32_t nameLen)
366{
367    struct stat sbuf;
368
369    if (getFileStat(name, nameLen, &sbuf))
370    {
371        if (sbuf.st_size >= INT32_MAX)
372        {
373            Trace("DRM_file_getFileLength: file too big");
374        }
375        else /* Successful */
376        {
377            Trace("DRM_file_getFileLength: %.*S -> %d",
378                                         nameLen, name, (int32_t)sbuf.st_size);
379            return (int32_t)sbuf.st_size;
380        }
381    }
382
383    return DRM_FILE_FAILURE;
384}
385
386/* see drm_file.h */
387int32_t
388DRM_file_delete(const uint16_t *name, int32_t nameLen)
389{
390    Trace("DRM_file_delete: %.*S", nameLen, name);
391
392    if (convertFilename(name, nameLen, tmpPathBuf1) <= 0)
393    {
394        Trace("DRM_file_delete: bad filename");
395        return DRM_FILE_FAILURE;
396    }
397    else
398    {
399       struct stat sinfo;
400       if (stat(tmpPathBuf1, &sinfo) != 0){
401           Trace("DRM_file_delete: stat failed, errno=%d", errno);
402           return DRM_FILE_FAILURE;
403       }
404#ifndef DEVICE_FILESYSTEM
405       if (S_ISDIR(sinfo.st_mode)){
406            /* it's a dir */
407            if (rmdir(tmpPathBuf1) != 0){
408                Trace("DRM_file_delete: dir remove failed, errno=%d", errno);
409                return DRM_FILE_FAILURE;
410            }
411            else
412            {
413                return DRM_FILE_SUCCESS;
414            }
415        }
416#endif
417        /* it's a file */
418        if (unlink(tmpPathBuf1) != 0)
419        {
420            Trace("DRM_file_delete: file remove failed, errno=%d", errno);
421            return DRM_FILE_FAILURE;
422        }
423        else
424        {
425#ifndef DEVICE_FILESYSTEM
426            availableSize += sinfo.st_size;
427#endif
428            return DRM_FILE_SUCCESS;
429        }
430    }
431    return DRM_FILE_FAILURE;
432}
433
434/* see drm_file.h */
435int32_t
436DRM_file_rename(const uint16_t *oldName, int32_t oldNameLen,
437                const uint16_t *newName, int32_t newNameLen)
438{
439    Trace("DRM_file_rename %.*S -> %.*S",
440                                    oldNameLen, oldName, newNameLen, newName);
441    if (DRM_file_exists(newName, newNameLen) != DRM_FILE_FAILURE)
442    {
443        Trace("DRM_file_rename: filename:%s exist",newName);
444        return DRM_FILE_FAILURE;
445    }
446
447    if (convertFilename(oldName, oldNameLen, tmpPathBuf1) <= 0 ||
448        convertFilename(newName, newNameLen, tmpPathBuf2) <= 0)
449    {
450        Trace("DRM_file_rename: bad filename");
451    }
452    else if (rename(tmpPathBuf1, tmpPathBuf2) != 0)
453    {
454         Trace("DRM_file_rename: failed errno=%d", errno);
455    }
456    else /* Success */
457    {
458        return DRM_FILE_SUCCESS;
459    }
460
461    return DRM_FILE_FAILURE;
462}
463
464/* see drm_file.h */
465int32_t
466DRM_file_exists(const uint16_t *name, int32_t nameLen)
467{
468    struct stat sbuf;
469
470    Trace("DRM_file_exists: %.*S", nameLen, name);
471
472    /*remove trailing "/" separators, except the first "/" standing for root*/
473    while ((nameLen > 1) && (name[nameLen -1] == '/'))
474       --nameLen;
475
476    if (getFileStat(name, nameLen, &sbuf))
477    {
478        Trace("DRM_file_exists: stat returns mode 0x%x", sbuf.st_mode);
479
480        if (S_ISDIR(sbuf.st_mode))
481            return DRM_FILE_ISDIR;
482        if (S_ISREG(sbuf.st_mode))
483            return DRM_FILE_ISREG;
484    }
485
486    return DRM_FILE_FAILURE;
487}
488
489/* see drm_file.h */
490int32_t
491DRM_file_open(const uint16_t *name, int32_t nameLen, int32_t mode,
492                      int32_t* handle)
493{
494    int res;
495
496#if DRM_FILE_MODE_READ != 1 || DRM_FILE_MODE_WRITE != 2
497#error constants changed
498#endif
499
500    /* Convert DRM file modes to posix modes */
501    static const int modes[4] =
502    { 0,
503      O_RDONLY,
504      O_WRONLY | O_CREAT,
505      O_RDWR | O_CREAT
506    };
507
508    Trace("DRM_file_open %.*S mode 0x%x", nameLen, name, mode);
509
510    assert((mode & ~(DRM_FILE_MODE_READ|DRM_FILE_MODE_WRITE)) == 0);
511
512    if (convertFilename(name, nameLen, tmpPathBuf1) <= 0)
513    {
514        Trace("DRM_file_open: bad filename");
515        return DRM_FILE_FAILURE;
516    }
517
518    if ((res = open(tmpPathBuf1, modes[mode], 0777)) == -1)
519    {
520        Trace("DRM_file_open: open failed errno=%d", errno);
521        return DRM_FILE_FAILURE;
522    }
523
524    Trace("DRM_file_open: open '%s; returned %d", tmpPathBuf1, res);
525    *handle = res;
526
527    return DRM_FILE_SUCCESS;
528}
529
530/* see drm_file.h */
531int32_t
532DRM_file_read(int32_t handle, uint8_t* dst, int32_t length)
533{
534    int n;
535
536    assert(length > 0);
537
538    /* TODO: Make dst a void *? */
539
540    n = read((int)handle, dst, (size_t)length);
541    if (n > 0)
542    {
543        Trace("DRM_file_read handle=%d read %d bytes", handle, n);
544        return n;
545    }
546    else if (n == 0)
547    {
548        Trace("DRM_file_read read EOF: handle=%d", handle);
549        return DRM_FILE_EOF;
550    }
551    else
552    {
553        Trace("DRM_file_read failed handle=%d, errno=%d", handle, errno);
554        return DRM_FILE_FAILURE;
555    }
556}
557
558/* see drm_file.h */
559int32_t
560DRM_file_write(int32_t handle, const uint8_t* src, int32_t length)
561{
562    /* TODO: Make dst a void *? */
563    int n;
564#ifndef DEVICE_FILESYSTEM
565    int delta;
566    off_t prevPos;
567    struct stat sbuf;
568    int prevFileSize;
569#endif
570
571    assert(length >= 0);
572
573#ifndef DEVICE_FILESYSTEM
574    if ( -1 == fstat((int)handle, &sbuf) )
575    {
576        Trace("DRM_file_write: fstat error %d", errno);
577        return DRM_FILE_FAILURE;
578    }
579    prevFileSize = (int)(sbuf.st_size);
580    prevPos = lseek( (int)handle, 0, SEEK_CUR);
581    if ( (off_t)-1 == prevPos )
582    {
583        Trace("DRM_file_write: get current pos error %d", errno);
584        return DRM_FILE_FAILURE;
585    }
586    delta = (int)prevPos + length - prevFileSize;
587    if (delta > availableSize)
588    {
589        Trace("DRM_file_write: not enough size!");
590        return DRM_FILE_FAILURE;
591    }
592#endif
593    n = write((int)handle, src, (size_t)length);
594    if (n < 0)
595    {
596        Trace("DRM_file_write failed errno=%d", errno);
597        return DRM_FILE_FAILURE;
598    }
599#ifndef DEVICE_FILESYSTEM
600    delta = prevPos + n - prevFileSize;
601
602    if ( delta > 0 )
603    {
604        availableSize -= delta;
605    }
606#endif
607    Trace("DRM_file_write handle=%d wrote %d/%d bytes", handle, n, length);
608
609    return n;
610}
611
612/* see drm_file.h */
613int32_t DRM_file_close(int32_t handle)
614{
615    if (close((int)handle) == 0)
616    {
617        Trace("DRM_file_close handle=%d success", handle);
618        return DRM_FILE_SUCCESS;
619    }
620
621    Trace("DRM_file_close handle=%d failed", handle);
622    return DRM_FILE_FAILURE;
623}
624
625/* see drm_file.h */
626int32_t
627DRM_file_setPosition(int32_t handle, int32_t value)
628{
629#ifndef DEVICE_FILESYSTEM
630    struct stat sbuf;
631#endif
632    off_t newPos;
633
634    if (value < 0)
635    {
636        Trace("DRM_file_setPosition: handle=%d negative value (%d)",
637            handle, value);
638        return DRM_FILE_FAILURE;
639    }
640
641#ifndef DEVICE_FILESYSTEM
642    if ( fstat((int)handle, &sbuf) == -1 )
643    {
644        Trace("DRM_file_setPosition: fstat fail errno=%d", errno);
645        return DRM_FILE_FAILURE;
646    }
647
648    if ( ((off_t)value > sbuf.st_size) &&
649         (availableSize < (value - (int)(sbuf.st_size))) )
650    {
651        Trace("DRM_file_setPosition: not enough space");
652        return DRM_FILE_FAILURE;
653    }
654#endif
655
656    newPos = lseek( (int)handle, (off_t)value, SEEK_SET);
657    if ( newPos == (off_t)-1 )
658    {
659        Trace("DRM_file_setPosition: seek failed: errno=%d", errno);
660    }
661    else
662    {
663#ifndef DEVICE_FILESYSTEM
664        if ( newPos > sbuf.st_size )
665        {
666            availableSize -= (int)(newPos - sbuf.st_size);
667        }
668#endif
669        return DRM_FILE_SUCCESS;
670    }
671
672    return DRM_FILE_FAILURE;
673}
674
675/* see drm_file.h */
676int32_t
677DRM_file_mkdir(const uint16_t* name, int32_t nameChars)
678{
679    Trace("DRM_file_mkdir started!..");
680
681    if (convertFilename(name, nameChars, tmpPathBuf1) <= 0)
682    {
683        Trace("DRM_file_mkdir: bad filename");
684        return DRM_FILE_FAILURE;
685    }
686
687    if (mkdir(tmpPathBuf1,0777) != 0)
688    {
689        Trace("DRM_file_mkdir failed!errno=%d",errno);
690        return DRM_FILE_FAILURE;
691    }
692
693    return DRM_FILE_SUCCESS;
694}
695