summaryrefslogtreecommitdiffstats
path: root/dirtree.c
blob: 5582b43525fcfc3841f3afee40bd694fcee70a3b (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
367
368
369
370
371
372
373
374
375
#ident "$Id$"
/* ----------------------------------------------------------------------- *
 *   
 *   Copyright 2001-2003 H. Peter Anvin - All Rights Reserved
 *
 *   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, Inc., 675 Mass Ave, Cambridge MA 02139,
 *   USA; either version 2 of the License, or (at your option) any later
 *   version; incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * dirtree.c
 *
 * Scan the input directory and create the appropriate structure
 */

#include <inttypes.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <iconv.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include "dirtree.h"
#include "xmalloc.h"

#define VFAT_MAX_LEN	64
#define VFAT_MAX_SLOTS  ((VFAT_MAX_LEN+12)/13)

extern const char *program;
struct uni2cp {
  uint16_t uni;
  uint8_t cp;
  uint8_t upper;
};
extern struct uni2cp cp437;

static iconv_t iconv_utf16;

static void 
fat_mangle_setup(void)
{
  iconv_utf16 = iconv_open("UTF-16LE", "");
  if ( iconv_utf16 == (iconv_t)-1 ) {
    fprintf("%s: failed to iconv_open UTF-16LE: %s\n",
            program, strerror(errno));
    exit(1);
  }
}

#define VFAT_LOSSY_CONVERSION	0x01 /* Unrepresentable character */
#define VFAT_UPPER_CASE		0x02 /* A..Z */
#define VFAT_BAD_CHAR		0x04 /* Forbidden character */
#define VFAT_EXTENDED_CHAR	0x08 /* char >= 0x80 */

static unsigned int
fat_uni_to_cp(char *cp, uint16_t *uni, int uni_len)
{
  /* NUL is implied; space is technically legal but rarely used in practice */
  static const char dosforbidden[] =
    "\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017"
    "\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
    " \"\'\\/[]|<>,*$+\177\377";
  static const char cp437toupper[256] =
    "\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017"
    "\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
    " !\"#$%&\'()*+,-./0123456789:;<=>?"
    "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
    "`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\177"
    "\200\232\220A\216A\217\200EEEIII\216\217"
    "\220\222\222O\231OUUY\231\232\233\234\235\236\237"
    "\240\241\242\243\245\245\246\247\250\251\252\253\254\255\256\257"
    "\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277"
    "\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317"
    "\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337"
    "\340\341\342\343\344\344\346\347\350\351\352\353\354\355\356\357"
    "\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377";
  uint16_t uc, uref;
  int ui, ul, uh;
  struct uni2cp *ux;
  uint8_t cpc;
  int name_flags = 0;
  int ext_flags = 0;
  int found_dot = 0;

  while ( uni_len-- ) {
    uc = read16((le16_t *)(uni++));
    
    ui = 128; ul = 0; uh = 255;
    while ( uc != (uref = cp437[ui].uni) && ul < uh ) {
      if ( uc < uref ) {
	ul = ui+1;
      } else if ( uc > uref ) {
	uh = ui-1;
      }
      ui = (ul+uh)/2;
    }
    if ( uc != uref ) {
      cpc = '_';
      ext_flags |= VFAT_LOSSY_CONVERSION;
    } else {
      cpc = cp437[uni].cp;
      if ( strchr(dosforbidden, cpc) ) {
	cpc = '_';
	ext_flags |= VFAT_BAD_CHAR;
      } else if ( cpc >= 'A' && cpc <= 'Z' ) {
	ext_flags |= VFAT_UPPER_CASE;
      } else if ( cpc >= 0x80 ) {
	ext_flags |= VFAT_EXTENDED_CHAR;
      }
    }
    if ( cpc == '.' ) {
      name_flags |= ext_flags;
      ext_flags = 0;
      found_dot = 1;
    }

    *cp++ = cp437toupper[cpc];
  }
  *cp = '\0';

  return found_dot ? (name_flags | (ext_flags << 4)) : ext_flags;
}

static int
fat_mangle_name(const char *name, char *buf)
{
  const char *dot;
  char *cp, *endp;
  char xc;
  const char numtail_str[9];
  char *cpname;
  char *inb, *outb;
  int inbl, outbl;

  if ( !iconv_cp437 )
    fat_mangle_setup();

  cpname = xmalloc((inbl = outbl = strlen(name))+1);

  inb = name;
  outb = cpname;
  iconv(iconv_cp437, NULL, NULL, NULL, NULL); /* Reset input state */
  iconv(iconv_cp437, &inb, &inbl, &outb, &outbl);
  *outb = '\0';

  dot = strrchr(cpname, '.');	/* Find last dot */
  if ( dot == name )
    dot = NULL;			/* Leading dot? */

  cp = buf;  endp = buf+11;
  memset(buf, ' ', 11);
  *endp = '\0';

  for ( ; *cpname ; cpname++ ) {
    xc = *cpname;
    if ( xc == '.' ) {
      if ( cpname == dot ) {
	/* Last dot */
	cp = buf+8;
	cp[0] = ' ';
	cp[1] = ' ';
	cp[2] = ' ';
	continue;
      } else {
	xc = '_';
      }
    }

    if ( islower(xc) ) {
      xc = toupper(xc);
    }

    if ( strchr(dosforbidden, xc) ) {
      xc = '_';
    }

    if ( (unsigned char)xc == 0xe5 && cp == buf ) {
      xc = 0x05;		/* Only applies to the first character... */
    }

    if ( cp < endp )
      *cp++ = xc;
  }
  return 0;
}

/* Add a numeric tail to an already mangled iname */
static void
fat_set_numtail(char *oname, char *iname, int numtail)
{
  int nc, char *cp;
  char numtail_str[9];

  memcpy(oname, iname, 11);

  if ( numtail ) {
    nc = snprintf(numtail_str, 9, "~%u", numtail);
    cp = oname+8-nc;
    while ( cp > buf && cp[-1] == ' ' ) cp--;
    memcpy(cp, numtail_str, nc);
  }
}

static void
dos_mangle_name(struct direntry *dirent,
		struct direntry *prev,
		int prev_cnt)
{
  (void)prev;  (void)prev_cnt;

  dirent->nfatents = 1;		/* Only 1 entry/file required */
  dirent->fatents = xmalloc(sizeof(struct fat_dirent));
  fat_mangle_name(dirent->name, dirent->fatents->name, 0);
}

static void
int vfat_mangle_name(struct direntry *dirent,
		     struct direntry *prev,
		     int prev_cnt)
{
  uint16_t buffer[VFAT_MAX_LEN];
  uint16_t *xb;
  char *inb, *outb;
  int inbl, outbl, xl, nx;
  int seq = 1;
  int i;
  uint16_t cv;
  static const char *vfat_bad_long =
    "\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17"
    "\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37"
    "\"*/:<>?\\|\177";
  
  inb = str;
  inbl = strlen(inb);
  outb = (char *)buffer;
  outbl = VFAT_MAX_LEN << 1; 
  
  iconv(iconv_utf16, NULL, NULL, NULL, NULL); /* Reset input state */
  iconv(iconv_utf16, &inb, &inbl, &outb, &outbl);
  
  xl = VFAT_MAX_LEN - (outbl >> 1);
  xb = buffer;

  /* The VFAT spec says trailing periods and leading and trailing spaces
     are ignored.  However, it doesn't specify if those should actually
     be stripped.  Ignore that for now and let the filesystem worry about it. */

  for ( i = 0 ; i < xl ; i++ ) {
    cv = read16((le16_t *)&buffer[i]);
    if ( cv <= 127 && strchr(vfat_bad_long, cv) )
      write16((le16_t *)&buffer[i], '_'); /* Bad character, replace with _ */
  }

  while ( xl ) {
    memset(slots, 0, sizeof(*slots));
    slots->id = seq++;
    slots->attribute = 0x0f;	/* Part of a long name */
    slots->alias_csum = csum;
    
    nx = min(xl,5);
    memcpy(slots->name0, xb, nx<<1);
    xl -= nx;

    nx = min(xl,6);
    memcpy(slots->name5, xb, nx<<1);
    xl -= nx;

    nx = min(xl,2);
    memcpy(slots->name11, xb, nx<<1);
    xl -= nx;

    if ( !xl )
      slots->id |= 0x40;	/* Last slot */

    slots++;
  }

  return seq-1;
}


struct direntry *
make_dir_tree(const char *root, int *dirsizeptr, struct direntry *parent)
{
  DIR *dirp;
  struct dirent *de;
  struct direntry *thisent;
  struct direntry *tree = NULL;
  struct direntry **link = &tree;
  int rootlen = strlen(root);
  int namelen;
  int dirsize;

  dirsize = 0;

  dirp = opendir(root);
  if ( !dirp )
    return NULL;

  while ( (de = readdir(dirp)) != NULL ) {
    if ( !strcmp(de->d_name, ".") || !strcmp(de->d_name, "..") )
      continue;			/* Ignore . and .. */

    thisent = xmalloc(sizeof(struct direntry));
    memset(thisent, 0, sizeof(struct direntry));

    thisent->name = xstrdup(de->d_name);
    namelen = strlen(thisent->name);

    thisent->path = xmalloc(rootlen+namelen+3);
    memcpy(thisent->path, root, rootlen);
    thisent->path[rootlen] = '/';
    memcpy(thisent->path+rootlen+1, thisent->name, namelen+1);

    thisent->parent = parent;

    if ( stat(thisent->path, &thisent->st) ) {
      fprintf(stderr, "%s: Cannot stat file: %s\n", program,
	      thisent->path);
      free(thisent->name);
      free(thisent->path);
      free(thisent);
      continue;
    }

    if ( S_ISDIR(thisent->st.st_mode) ) {
      /* Recursion: see recursion */
      thisent->dir = make_dir_tree(thisent->path, &thisent->dirsize, thisent);
      thisent->attribute = 0x10; /* Directory */
    } else if ( !S_ISREG(thisent->st.st_mode) ) {
      /* Some kind of special file (not symbolic link, we used stat,
	 not lstat.)  This isn't representable, so just ignore it. */
      fprintf(stderr, "%s: Ignoring special file: %s\n", program,
	      thisent->path);
      free(thisent->name);
      free(thisent->path);
      free(thisent);
      continue;
    } else {
      thisent->dir = NULL;
      thisent->attribute = 0x00; /* File */
    }

    if ( !(thisent->st.st_mode & (S_IWUSR|S_IWGRP|S_IWOTH)) ) {
      thisent->attribute |= 0x01; /* Readonly */
    }

    thisent->next = NULL;

    /* Generate mangled DOS filename (eventually) */
    /* FIX: Handle VFAT */
    dos_mangle_name(thisent);

    /* Add to linked list */
    *link = thisent;
    link = &thisent->next;
    dirsize++;
  }

  closedir(dirp);

  if (dirsizeptr)
    *dirsizeptr = dirsize;

  return tree;
}