Subversion Repositories Kolibri OS

Rev

Rev 9840 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. #include <sys/stat.h>
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <stdlib.h>
  5. #include <limits.h>
  6. #include <errno.h>
  7. #include <assert.h>
  8. #include <string.h>
  9. #include <dirent.h>
  10. #include <ctype.h>
  11. #ifndef __MINGW32__
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <pwd.h>
  15. #include <unistd.h>
  16. #ifdef HAVE_GLOB_H
  17. #include <glob.h>
  18. #endif
  19. #else
  20. #include <io.h>
  21. #include <shlobj.h>
  22. #endif
  23. #ifdef WITH_LIBARCHIVE
  24. #include <archive.h>
  25. /* For backward compatibility. */
  26. #if ARCHIVE_VERSION_NUMBER < 3001000
  27. #define archive_read_free(...) \
  28.         archive_read_finish(__VA_ARGS__)
  29. #define archive_read_support_filter_all(...) \
  30.         archive_read_support_compression_all(__VA_ARGS__)
  31. #endif
  32. #endif
  33. #include "system.h"
  34.  
  35. #ifdef __MINGW32__
  36. #define mkdir(a, b) mkdir(a)
  37. #if MAX_PATH < PATH_MAX
  38. #error MAX_PATH < PATH_MAX. You should use MAX_PATH.
  39. #endif
  40. #endif
  41.  
  42. #ifdef _KOLIBRI
  43. char* dgen_conf_dir = "/tmp0/1";
  44. #endif
  45.  
  46. static const char *fopen_mode(unsigned int mode)
  47. {
  48.         static const char *modes[4][2] = {
  49.                 { "ab", "a" },
  50.                 { "w+b", "w+" },
  51.                 { "rb", "r" },
  52.                 { NULL, NULL }
  53.         };
  54.         const char *(*cmode)[2] = &modes[0];
  55.  
  56.         if (!(mode & DGEN_APPEND)) {
  57.                 ++cmode;
  58.                 if (!(mode & DGEN_WRITE)) {
  59.                         ++cmode;
  60.                         if (!(mode & DGEN_READ))
  61.                                 ++cmode;
  62.                 }
  63.         }
  64.         return (*cmode)[(!!(mode & DGEN_TEXT))];
  65. }
  66.  
  67. enum path_type {
  68.         PATH_TYPE_UNSPECIFIED,
  69.         PATH_TYPE_RELATIVE,
  70.         PATH_TYPE_ABSOLUTE
  71. };
  72.  
  73. #ifdef __MINGW32__
  74.  
  75. /**
  76.  * Check whether a path is absolute or relative.
  77.  *
  78.  * Examples:
  79.  * /foo/bar, \\foo\\bar, c:/foo/bar are absolute,
  80.  * ./foo/bar, ., .., are relative.
  81.  *
  82.  * @param[in] path Path to parse.
  83.  * @param len Length of path.
  84.  * @return Path type (PATH_TYPE_ABSOLUTE, PATH_TYPE_RELATIVE or
  85.  * PATH_TYPE_UNSPECIFIED).
  86.  */
  87. enum path_type path_type(const char *path, size_t len)
  88. {
  89.         if ((len == 0) || (path[0] == '\0'))
  90.                 return PATH_TYPE_UNSPECIFIED;
  91.         if ((path[0] == '\\') || (path[0] == '/'))
  92.                 return PATH_TYPE_ABSOLUTE;
  93.         if ((path[0] == '.') &&
  94.             (((len == 1) ||
  95.               (path[1] == '\0') || (path[1] == '\\') || (path[1] == '/')) ||
  96.              ((path[1] == '.') &&
  97.               ((len == 2) ||
  98.                (path[2] == '\0') || (path[2] == '\\') || (path[2] == '/')))))
  99.                 return PATH_TYPE_RELATIVE;
  100.         do {
  101.                 if (*(++path) == ':')
  102.                         return PATH_TYPE_ABSOLUTE;
  103.                 --len;
  104.         }
  105.         while ((len) && (*path != '\0') && (*path != '\\') && (*path != '/'));
  106.         return PATH_TYPE_UNSPECIFIED;
  107. }
  108.  
  109. #else /* __MINGW32__ */
  110.  
  111. /**
  112.  * Check whether a path is absolute or relative.
  113.  *
  114.  * Examples:
  115.  * /foo/bar, \\foo\\bar are absolute,
  116.  * ./foo/bar, ., .., are relative.
  117.  *
  118.  * @param[in] path Path to parse.
  119.  * @param len Length of path.
  120.  * @return Path type (PATH_TYPE_ABSOLUTE, PATH_TYPE_RELATIVE or
  121.  * PATH_TYPE_UNSPECIFIED).
  122.  */
  123. enum path_type path_type(const char *path, size_t len)
  124. {
  125.         if ((len == 0) || (path[0] == '\0'))
  126.                 return PATH_TYPE_UNSPECIFIED;
  127.         if (path[0] == '/')
  128.                 return PATH_TYPE_ABSOLUTE;
  129.         if ((path[0] == '.') &&
  130.             (((len == 1) || (path[1] == '\0') || (path[1] == '/')) ||
  131.              ((path[1] == '.') &&
  132.               ((len == 2) || (path[2] == '\0') || (path[2] == '/')))))
  133.                 return PATH_TYPE_RELATIVE;
  134.         return PATH_TYPE_UNSPECIFIED;
  135. }
  136.  
  137. #endif /* __MINGW32__ */
  138.  
  139. /**
  140.  * Return user's home directory.
  141.  * The returned string doesn't have a trailing '/' and must be freed using
  142.  * free() (unless "buf" is provided).
  143.  *
  144.  * @param[in,out] buf Used to store path in. If NULL, memory is allocated.
  145.  * @param[in,out] size Size of "buf" when provided, then the returned path
  146.  * size.
  147.  * @return User's home directory (either as "buf" or a new buffer),
  148.  * NULL in case of error.
  149.  */
  150. char *dgen_userdir(char *buf, size_t *size)
  151. {
  152.         char *path;
  153.         size_t sz_dir;
  154.         size_t sz;
  155. #if !defined __MINGW32__ && !defined _KOLIBRI
  156.         struct passwd *pwd = getpwuid(geteuid());
  157.  
  158.         if ((pwd == NULL) || (pwd->pw_dir == NULL))
  159.                 return NULL;
  160.         sz_dir = strlen(pwd->pw_dir);
  161. #endif
  162.         if (buf != NULL) {
  163.                 sz = *size;
  164. #if     defined __MINGW32__ || defined _KOLIBRI
  165.                 if (sz < PATH_MAX)
  166.                         return NULL;
  167. #else
  168.                 if (sz < (sz_dir + 1))
  169.                         return NULL;
  170. #endif
  171.                 path = buf;
  172.         }
  173.         else {
  174. #if defined __MINGW32__ || defined _KOLIBRI
  175.                 sz = PATH_MAX;
  176. #else
  177.                 sz = (sz_dir + 1);
  178. #endif
  179.                 if ((path = malloc(sz)) == NULL)
  180.                         return NULL;
  181.         }
  182. #ifndef __MINGW32__
  183.         #ifdef _KOLIBRI
  184.         strncpy(path, dgen_conf_dir, sz_dir);
  185.         #else
  186.         strncpy(path, pwd->pw_dir, sz_dir);
  187.         #endif
  188. #else
  189.         if (SHGetFolderPath(NULL, (CSIDL_PROFILE | CSIDL_FLAG_CREATE),
  190.                             0, 0, path) != S_OK) {
  191.                 if (buf == NULL)
  192.                         free(path);
  193.                 return NULL;
  194.         }
  195.         sz_dir = strlen(path);
  196.         if (sz < (sz_dir + 1)) {
  197.                 if (buf == NULL)
  198.                         free(path);
  199.                 return NULL;
  200.         }
  201. #endif
  202.         path[sz_dir] = '\0';
  203.         if (size != NULL)
  204.                 *size = sz_dir;
  205.         return path;
  206. }
  207.  
  208. /**
  209.  * Return DGen's home directory with an optional subdirectory (or file).
  210.  * The returned string doesn't have a trailing '/' and must be freed using
  211.  * free() (unless "buf" is provided).
  212.  *
  213.  * @param[in,out] buf Buffer to store result in. If NULL, memory is allocated.
  214.  * @param[in,out] size Size of "buf" when provided, then the returned path
  215.  * size.
  216.  * @param[in] sub NUL-terminated string to append to the path.
  217.  * @return DGen's home directory (either as "buf" or a new buffer),
  218.  * NULL in case of error.
  219.  */
  220. char *dgen_dir(char *buf, size_t *size, const char *sub)
  221. {
  222.         char *path;
  223.         size_t sz_dir;
  224.         size_t sz_sub;
  225.         const size_t sz_bd = strlen(DGEN_BASEDIR);
  226.         size_t sz;
  227. #ifndef __MINGW32__
  228.         #ifndef _KOLIBRI
  229.         struct passwd *pwd = getpwuid(geteuid());
  230.         if ((pwd == NULL) || (pwd->pw_dir == NULL))
  231.                 return NULL;
  232.         sz_dir = strlen(pwd->pw_dir);
  233.         #else
  234.         sz_dir = strlen(dgen_conf_dir);
  235.         #endif
  236. #endif
  237.  
  238.         if (sub != NULL)
  239.                 sz_sub = strlen(sub);
  240.         else
  241.                 sz_sub = 0;
  242.         if (buf != NULL) {
  243.                 sz = *size;
  244. #if defined(__MINGW32__) || defined(_KOLIBRI)
  245.                 if (sz < PATH_MAX)
  246.                         return NULL;
  247. #else
  248.                 if (sz < (sz_dir + 1 + sz_bd + !!sz_sub + sz_sub + 1))
  249.                         return NULL;
  250. #endif
  251.                 path = buf;
  252.         }
  253.         else {
  254. #if defined(__MINGW32__) || defined(_KOLIBRI)
  255.                 sz = PATH_MAX;
  256. #else
  257.                 sz = (sz_dir + 1 + sz_bd + !!sz_sub + sz_sub + 1);
  258. #endif
  259.                 if ((path = malloc(sz)) == NULL)
  260.                         return NULL;
  261.         }
  262. #ifndef __MINGW32__
  263.         #ifndef _KOLIBRI
  264.         strncpy(path, pwd->pw_dir, sz_dir);
  265.         #else
  266.         strncpy(path, dgen_conf_dir, sz_dir);
  267.         #endif
  268. #else
  269.         if (SHGetFolderPath(NULL, (CSIDL_APPDATA | CSIDL_FLAG_CREATE),
  270.                             0, 0, path) != S_OK) {
  271.                 if (buf == NULL)
  272.                         free(path);
  273.                 return NULL;
  274.         }
  275.         sz_dir = strlen(path);
  276.         if (sz < (sz_dir + 1 + sz_bd + !!sz_sub + sz_sub + 1)) {
  277.                 if (buf == NULL)
  278.                         free(path);
  279.                 return NULL;
  280.         }
  281. #endif
  282.         path[(sz_dir++)] = DGEN_DIRSEP[0];
  283.         memcpy(&path[sz_dir], DGEN_BASEDIR, sz_bd);
  284.         sz_dir += sz_bd;
  285.         if (sz_sub) {
  286.                 path[(sz_dir++)] = DGEN_DIRSEP[0];
  287.                 memcpy(&path[sz_dir], sub, sz_sub);
  288.                 sz_dir += sz_sub;
  289.         }
  290.         path[sz_dir] = '\0';
  291.         if (size != NULL)
  292.                 *size = sz_dir;
  293.         return path;
  294. }
  295.  
  296. /**
  297.  * Open a file relative to DGen's home directory (when "relative" is NULL or
  298.  * path_type(relative) returns PATH_TYPE_UNSPECIFIED) and create the directory
  299.  * hierarchy if necessary, unless the file name is already relative to
  300.  * something or found in the current directory if mode contains DGEN_CURRENT.
  301.  *
  302.  * @param[in] relative Subdirectory to look in.
  303.  * @param[in] file File name to open.
  304.  * @param mode Mode flags to use (DGEN_READ, DGEN_WRITE and others).
  305.  * @return File pointer, or NULL in case of error.
  306.  * @see dgen_freopen()
  307.  * @see system.h
  308.  */
  309. FILE *dgen_fopen(const char *relative, const char *file, unsigned int mode)
  310. {
  311.         return dgen_freopen(relative, file, mode, NULL);
  312. }
  313.  
  314. /**
  315.  * @see dgen_fopen()
  316.  */
  317. FILE *dgen_freopen(const char *relative, const char *file, unsigned int mode,
  318.                    FILE *f)
  319. {
  320.         size_t size;
  321.         size_t file_size;
  322.         char *tmp;
  323.         int e = errno;
  324.         const char *fmode = fopen_mode(mode);
  325.         char *path = NULL;
  326.  
  327.         if ((file == NULL) || (file[0] == '\0') || (fmode == NULL))
  328.                 goto error;
  329.         /*
  330.           Try to open the file in the current directory if DGEN_CURRENT
  331.           is specified.
  332.         */
  333.         if (mode & DGEN_CURRENT) {
  334.                 FILE *fd;
  335.  
  336.                 if (f == NULL)
  337.                         fd = fopen(file, fmode);
  338.                 else
  339.                         fd = freopen(file, fmode, f);
  340.                 if (fd != NULL)
  341.                         return fd;
  342.         }
  343.         if (path_type(file, ~0u) != PATH_TYPE_UNSPECIFIED)
  344.                 size = 0;
  345.         else if ((relative == NULL) ||
  346.                  (path_type(relative, ~0u) == PATH_TYPE_UNSPECIFIED)) {
  347.                 if ((path = dgen_dir(NULL, &size, relative)) == NULL)
  348.                         goto error;
  349.         }
  350.         else {
  351.                 if ((path = strdup(relative)) == NULL)
  352.                         goto error;
  353.                 size = strlen(path);
  354.         }
  355.         printf("HOME=%s\n", path);
  356.         if ((mode & (DGEN_WRITE | DGEN_APPEND)) && (path != NULL))
  357.                 mkdir(path, 0777); /* XXX make that recursive */
  358.         file_size = strlen(file);
  359.         if ((tmp = realloc(path, (size + !!size + file_size + 1))) == NULL)
  360.                 goto error;
  361.         path = tmp;
  362.         if (size)
  363.                 path[(size++)] = DGEN_DIRSEP[0];
  364.         memcpy(&path[size], file, file_size);
  365.         size += file_size;
  366.         path[size] = '\0';
  367.         errno = e;
  368.         if (f == NULL)
  369.                 f = fopen(path, fmode);
  370.         else
  371.                 f = freopen(path, fmode, f);
  372.         e = errno;
  373.         free(path);
  374.         errno = e;
  375.         return f;
  376. error:
  377.         puts("ERROR");
  378.         free(path);
  379.         errno = EACCES;
  380.         return NULL;
  381. }
  382.  
  383. /**
  384.  * Return the base name in path, like basename() but without allocating
  385.  * anything nor modifying the "path" argument.
  386.  *
  387.  * @param[in] path Path to extract the last component from.
  388.  * @return Last component from "path".
  389.  */
  390. const char *dgen_basename(const char *path)
  391. {
  392.         char *tmp;
  393.  
  394.         while ((tmp = strpbrk(path, DGEN_DIRSEP)) != NULL)
  395.                 path = (tmp + 1);
  396.         return path;
  397. }
  398.  
  399. #define CHUNK_SIZE BUFSIZ
  400.  
  401. struct chunk {
  402.         size_t size;
  403.         struct chunk *next;
  404.         struct chunk *prev;
  405.         uint8_t data[];
  406. };
  407.  
  408. /**
  409.  * Unload pointer returned by load().
  410.  *
  411.  * @param[in] data Pointer to unload.
  412.  */
  413. void unload(uint8_t *data)
  414. {
  415.         struct chunk *chunk = ((struct chunk *)data - 1);
  416.  
  417.         assert(chunk->next == chunk);
  418.         assert(chunk->prev == chunk);
  419.         free(chunk);
  420. }
  421.  
  422. #ifdef HAVE_FTELLO
  423. #define FTELL(f) ftello(f)
  424. #define FSEEK(f, o, w) fseeko((f), (o), (w))
  425. #define FOFFT off_t
  426. #else
  427. #define FTELL(f) ftell(f)
  428. #define FSEEK(f, o, w) fseek((f), (o), (w))
  429. #define FOFFT long
  430. #endif
  431.  
  432. /**
  433.  * Call this when you're done with your file.
  434.  *
  435.  * @param[in,out] context Context returned by load().
  436.  */
  437. void load_finish(void **context)
  438. {
  439. #ifdef WITH_LIBARCHIVE
  440.         struct archive *archive = *context;
  441.  
  442.         if (archive != NULL)
  443.                 archive_read_free(archive);
  444. #endif
  445.         *context = NULL;
  446. }
  447.  
  448. /**
  449.  * Return the remaining file size from the current file offset.
  450.  *
  451.  * @param[in] file File pointer.
  452.  */
  453. static size_t load_size(FILE *file)
  454. {
  455.         FOFFT old = FTELL(file);
  456.         FOFFT pos;
  457.         size_t ret = 0;
  458.  
  459.         if ((old == (FOFFT)-1) ||
  460.             (FSEEK(file, 0, SEEK_END) == -1))
  461.                 return 0;
  462.         if (((pos = FTELL(file)) != (FOFFT)-1) && (pos >= old))
  463.                 ret = (size_t)(pos - old);
  464.         FSEEK(file, old, SEEK_SET);
  465.         return ret;
  466. }
  467.  
  468. /**
  469.  * Allocate a buffer and stuff the file inside using transparent decompression
  470.  * if libarchive is available. If file_size is non-NULL, store the final size
  471.  * there. If max_size is nonzero, refuse to load anything larger.
  472.  * In case the returned value is NULL, errno should contain the error.
  473.  *
  474.  * If an error is returned but errno is 0, EOF has been reached.
  475.  *
  476.  * @param[in,out] context On first call of load() this should point to NULL.
  477.  * @param[out] file_size Final size.
  478.  * @param[in] file File pointer to load data from.
  479.  * @param max_size If nonzero, refuse to load anything larger.
  480.  * @return Buffer containing loaded data.
  481.  */
  482. uint8_t *load(void **context,
  483.               size_t *file_size, FILE *file, size_t max_size)
  484. {
  485.         size_t pos;
  486.         size_t size = 0;
  487.         struct chunk *chunk;
  488.         struct chunk head = { 0, &head, &head };
  489.         size_t chunk_size = load_size(file);
  490.         int error = 0;
  491. #ifdef WITH_LIBARCHIVE
  492.         struct archive *archive = *context;
  493.         struct archive_entry *archive_entry;
  494.  
  495.         if (archive != NULL)
  496.                 goto init_ok;
  497.         archive = archive_read_new();
  498.         *context = archive;
  499.         if (archive == NULL) {
  500.                 error = ENOMEM;
  501.                 goto error;
  502.         }
  503.         archive_read_support_filter_all(archive);
  504.         archive_read_support_format_all(archive);
  505.         archive_read_support_format_raw(archive);
  506.         if (archive_read_open_FILE(archive, file) != ARCHIVE_OK) {
  507.                 error = EIO;
  508.                 goto error;
  509.         }
  510. init_ok:
  511.         switch (archive_read_next_header(archive, &archive_entry)) {
  512.         case ARCHIVE_OK:
  513.                 break;
  514.         case ARCHIVE_EOF:
  515.                 error = 0;
  516.                 goto error;
  517.         default:
  518.                 error = EIO;
  519.                 goto error;
  520.         }
  521. #else
  522.         *context = (void *)0xffff;
  523. #endif
  524.         if (chunk_size == 0)
  525.                 chunk_size = CHUNK_SIZE;
  526.         else if ((max_size != 0) && (chunk_size > max_size))
  527.                 chunk_size = max_size;
  528.         while (1) {
  529.                 pos = 0;
  530.                 chunk = malloc(sizeof(*chunk) + chunk_size);
  531.                 if (chunk == NULL) {
  532.                         error = errno;
  533.                         goto error;
  534.                 }
  535.                 chunk->size = chunk_size;
  536.                 chunk->next = &head;
  537.                 chunk->prev = head.prev;
  538.                 chunk->prev->next = chunk;
  539.                 head.prev = chunk;
  540.                 do {
  541.                         size_t i;
  542. #ifdef WITH_LIBARCHIVE
  543.                         ssize_t j;
  544.  
  545.                         j = archive_read_data(archive, &chunk->data[pos],
  546.                                               (chunk->size - pos));
  547.                         /*
  548.                           Don't bother with ARCHIVE_WARN and ARCHIVE_RETRY,
  549.                           consider any negative value an error.
  550.                         */
  551.                         if (j < 0) {
  552.                                 error = EIO;
  553.                                 goto error;
  554.                         }
  555.                         i = (size_t)j;
  556. #else
  557.                         i = fread(&chunk->data[pos], 1, (chunk->size - pos),
  558.                                   file);
  559. #endif
  560.                         if (i == 0) {
  561.                                 chunk->size = pos;
  562. #ifndef WITH_LIBARCHIVE
  563.                                 if (ferror(file)) {
  564.                                         error = EIO;
  565.                                         goto error;
  566.                                 }
  567.                                 assert(feof(file));
  568. #endif
  569.                                 goto process;
  570.                         }
  571.                         pos += i;
  572.                         size += i;
  573.                         if ((max_size != 0) && (size > max_size)) {
  574.                                 error = EFBIG;
  575.                                 goto error;
  576.                         }
  577.                 }
  578.                 while (pos != chunk->size);
  579.                 chunk_size = CHUNK_SIZE;
  580.         }
  581. process:
  582.         chunk = realloc(head.next, (sizeof(*chunk) + size));
  583.         if (chunk == NULL) {
  584.                 error = errno;
  585.                 goto error;
  586.         }
  587.         chunk->next->prev = chunk;
  588.         head.next = chunk;
  589.         pos = chunk->size;
  590.         chunk->size = size;
  591.         chunk = chunk->next;
  592.         while (chunk != &head) {
  593.                 struct chunk *next = chunk->next;
  594.  
  595.                 memcpy(&head.next->data[pos], chunk->data, chunk->size);
  596.                 pos += chunk->size;
  597.                 chunk->next->prev = chunk->prev;
  598.                 chunk->prev->next = chunk->next;
  599.                 free(chunk);
  600.                 chunk = next;
  601.         }
  602.         chunk = head.next;
  603.         chunk->prev = chunk;
  604.         chunk->next = chunk;
  605.         if (file_size != NULL)
  606.                 *file_size = chunk->size;
  607.         return chunk->data;
  608. error:
  609. #ifdef WITH_LIBARCHIVE
  610.         load_finish(context);
  611. #endif
  612.         chunk = head.next;
  613.         while (chunk != &head) {
  614.                 struct chunk *next = chunk->next;
  615.  
  616.                 free(chunk);
  617.                 chunk = next;
  618.         }
  619.         errno = error;
  620.         return NULL;
  621. }
  622.  
  623. /**
  624.  * Free NULL-terminated list of strings and set source pointer to NULL.
  625.  * This function can skip a given number of indices (starting from 0)
  626.  * which won't be freed.
  627.  *
  628.  * @param[in,out] pppc Pointer to an array of strings.
  629.  * @param skip Number of indices to skip in *pppc[].
  630.  */
  631. static void free_pppc(char ***pppc, size_t skip)
  632. {
  633.         char **p = *pppc;
  634.         size_t i;
  635.  
  636.         if (p == NULL)
  637.                 return;
  638.         *pppc = NULL;
  639.         for (i = 0; (p[i] != NULL); ++i) {
  640.                 if (skip == 0)
  641.                         free(p[i]);
  642.                 else
  643.                         --skip;
  644.         }
  645.         free(p);
  646. }
  647.  
  648. /**
  649.  * Return a list of path names that match "len" characters of "path" on the
  650.  * file system, or NULL if none was found or if an error occured.
  651.  *
  652.  * @param[in] path Path name to match.
  653.  * @param len Number of characters in "path" to match.
  654.  * @return List of matching path names or NULL.
  655.  */
  656. static char **complete_path_simple(const char *path, size_t len)
  657. {
  658.         size_t rlen;
  659.         const char *cpl;
  660.         char *root;
  661.         struct dirent *dent;
  662.         DIR *dir;
  663.         char **ret = NULL;
  664.         size_t ret_size = 256;
  665.         size_t ret_used = 0;
  666.         struct stat st;
  667.  
  668.         if ((rlen = strlen(path)) < len)
  669.                 len = rlen;
  670.         cpl = path;
  671.         while (((root = strpbrk(cpl, DGEN_DIRSEP)) != NULL) &&
  672.                (root < (path + len)))
  673.                 cpl = (root + 1);
  674.         rlen = (cpl - path);
  675.         len -= rlen;
  676.         if (rlen == 0) {
  677.                 path = "." DGEN_DIRSEP;
  678.                 rlen = 2;
  679.         }
  680.         if ((root = malloc(rlen + 1)) == NULL)
  681.                 return NULL;
  682.         memcpy(root, path, rlen);
  683.         root[rlen] = '\0';
  684.         if (((dir = opendir(root)) == NULL) ||
  685.             ((ret = malloc(sizeof(*ret) * ret_size)) == NULL))
  686.                 goto error;
  687.         ret[(ret_used++)] = NULL;
  688.         while ((dent = readdir(dir)) != NULL) {
  689.                 size_t i;
  690.                 char *t;
  691.  
  692.                 if ((cpl[0] != '\0') && (strncmp(cpl, dent->d_name, len)))
  693.                         continue;
  694.                 /* Remove "." and ".." entries. */
  695.                 if ((dent->d_name[0] == '.') &&
  696.                     ((dent->d_name[1] == '\0') ||
  697.                      ((dent->d_name[1] == '.') && (dent->d_name[2] == '\0'))))
  698.                         continue;
  699.                 if (ret_used == ret_size) {
  700.                         char **rt;
  701.  
  702.                         ret_size *= 2;
  703.                         if ((rt = realloc(ret,
  704.                                           (sizeof(*rt) * ret_size))) == NULL)
  705.                                 break;
  706.                         ret = rt;
  707.                 }
  708.                 i = strlen(dent->d_name);
  709.                 /* Allocate one extra char in case it's a directory. */
  710.                 if ((t = malloc(rlen + i + 1 + 1)) == NULL)
  711.                         break;
  712.                 memcpy(t, root, rlen);
  713.                 memcpy(&t[rlen], dent->d_name, i);
  714.                 t[(rlen + i)] = '\0';
  715.                 if ((stat(t, &st) != -1) && (S_ISDIR(st.st_mode))) {
  716.                         t[(rlen + (i++))] = DGEN_DIRSEP[0];
  717.                         t[(rlen + i)] = '\0';
  718.                 }
  719.                 for (i = 0; (ret[i] != NULL); ++i)
  720.                         if (strcmp(dent->d_name, &ret[i][rlen]) < 0)
  721.                                 break;
  722.                 memmove(&ret[(i + 1)], &ret[i],
  723.                         (sizeof(*ret) * (ret_used - i)));
  724.                 ret[i] = t;
  725.                 ++ret_used;
  726.         }
  727.         closedir(dir);
  728.         free(root);
  729.         if (ret[0] != NULL)
  730.                 return ret;
  731.         free(ret);
  732.         return NULL;
  733. error:
  734.         if (dir != NULL)
  735.                 closedir(dir);
  736.         free(root);
  737.         if (ret != NULL) {
  738.                 while (*ret != NULL)
  739.                         free(*(ret++));
  740.                 free(ret);
  741.         }
  742.         return NULL;
  743. }
  744.  
  745. #if defined(HAVE_GLOB_H) && !defined(__MINGW32__) && !defined(_KOLIBRI)
  746.  
  747. #define COMPLETE_USERDIR_TILDE 0x01
  748. #define COMPLETE_USERDIR_EXACT 0x02
  749. #define COMPLETE_USERDIR_ALL 0x04
  750.  
  751. /**
  752.  * Return the list of home directories that match "len" characters of a
  753.  * user's name ("prefix").
  754.  * COMPLETE_USERDIR_TILDE - Instead of directories, the returned strings are
  755.  * tilde-prefixed user names.
  756.  * COMPLETE_USERDIR_EXACT - Prefix must exactly match a user name.
  757.  * COMPLETE_USERDIR_ALL - When prefix length is 0, return all user names
  758.  * instead of the current user only.
  759.  *
  760.  * @param[in] prefix Path name to match.
  761.  * @param len Number of characters to match in "path".
  762.  * @return List of home directories that match "len" characters of "prefix".
  763.  */
  764. static char **complete_userdir(const char *prefix, size_t len, int flags)
  765. {
  766.         char **ret = NULL;
  767.         char *s;
  768.         struct passwd *pwd;
  769.         size_t n;
  770.         size_t i;
  771.         int tilde = !!(flags & COMPLETE_USERDIR_TILDE);
  772.         int exact = !!(flags & COMPLETE_USERDIR_EXACT);
  773.         int all = !!(flags & COMPLETE_USERDIR_ALL);
  774.  
  775.         setpwent();
  776.         if ((!all) && (len == 0)) {
  777.                 if (((pwd = getpwuid(geteuid())) == NULL) ||
  778.                     ((ret = calloc(2, sizeof(ret[0]))) == NULL))
  779.                         goto err;
  780.                 if (tilde)
  781.                         s = pwd->pw_name;
  782.                 else
  783.                         s = pwd->pw_dir;
  784.                 i = strlen(s);
  785.                 if ((ret[0] = calloc((tilde + i + 1),
  786.                                      sizeof(*ret[0]))) == NULL)
  787.                         goto err;
  788.                 if (tilde)
  789.                         ret[0][0] = '~';
  790.                 memcpy(&ret[0][tilde], s, i);
  791.                 ret[0][(tilde + i)] = '\0';
  792.                 goto end;
  793.         }
  794.         n = 64;
  795.         if ((ret = calloc(n, sizeof(ret[0]))) == NULL)
  796.                 goto err;
  797.         i = 0;
  798.         while ((pwd = getpwent()) != NULL) {
  799.                 size_t j;
  800.  
  801.                 if (exact) {
  802.                         if (strncmp(pwd->pw_name, prefix,
  803.                                     strlen(pwd->pw_name)))
  804.                                 continue;
  805.                 }
  806.                 else if (strncmp(pwd->pw_name, prefix, len))
  807.                         continue;
  808.                 if (i == (n - 1)) {
  809.                         char **tmp;
  810.  
  811.                         n += 64;
  812.                         if ((tmp = realloc(ret, (sizeof(ret[0]) * n))) == NULL)
  813.                                 goto end;
  814.                         ret = tmp;
  815.                 }
  816.                 if (tilde)
  817.                         s = pwd->pw_name;
  818.                 else
  819.                         s = pwd->pw_dir;
  820.                 j = strlen(s);
  821.                 if ((ret[i] = calloc((tilde + j + 1),
  822.                                      sizeof(*ret[0]))) == NULL)
  823.                         break;
  824.                 if (tilde)
  825.                         ret[i][0] = '~';
  826.                 memcpy(&ret[i][tilde], s, j);
  827.                 ret[i][(tilde + j)] = '\0';
  828.                 ++i;
  829.         }
  830.         if (i == 0) {
  831.                 free(ret);
  832.                 ret = NULL;
  833.         }
  834. end:
  835.         endpwent();
  836.         return ret;
  837. err:
  838.         endpwent();
  839.         free_pppc(&ret, 0);
  840.         return NULL;
  841. }
  842.  
  843. /**
  844.  * Return a list of pathnames that match "len" characters of "prefix" on the
  845.  * file system, or NULL if none was found or if an error occured. This is done
  846.  * using glob() in order to handle wildcard characters in "prefix".
  847.  *
  848.  * When "prefix" isn't explicitly relative nor absolute, if "relative" is
  849.  * non-NULL, then the path will be completed as if "prefix" was a subdirectory
  850.  * of "relative". If "relative" is NULL, DGen's home directory will be used.
  851.  *
  852.  * If "relative" isn't explicitly relative nor absolute, it will be considered
  853.  * a subdirectory of DGen's home directory.
  854.  *
  855.  * @param[in] prefix Path name to match.
  856.  * @param len Number of characters to match in "path".
  857.  * @param[in] relative If non-NULL, consider path relative to this.
  858.  * @return List of path names that match "len" characters of "prefix".
  859.  */
  860. char **complete_path(const char *prefix, size_t len, const char *relative)
  861. {
  862.         char *s;
  863.         char **ret;
  864.         size_t i;
  865.         glob_t g;
  866.         size_t strip;
  867.  
  868.         (void)complete_path_simple; /* unused */
  869.         if ((i = strlen(prefix)) < len)
  870.                 len = i;
  871.         else
  872.                 i = len;
  873.         if (((s = strchr(prefix, '/')) != NULL) && ((i = (s - prefix)) > len))
  874.                 i = len;
  875.         if ((len == 0) ||
  876.             ((prefix[0] != '~') &&
  877.              (strncmp(prefix, ".", i)) &&
  878.              (strncmp(prefix, "..", i)))) {
  879.                 size_t n;
  880.  
  881.                 if ((relative == NULL) ||
  882.                     (path_type(relative, ~0u) == PATH_TYPE_UNSPECIFIED)) {
  883.                         char *x = dgen_dir(NULL, &n, relative);
  884.  
  885.                         if ((x == NULL) ||
  886.                             ((s = realloc(x, (n + 1 + len + 2))) == NULL)) {
  887.                                 free(x);
  888.                                 return NULL;
  889.                         }
  890.                 }
  891.                 else {
  892.                         n = strlen(relative);
  893.                         if ((s = malloc(n + 1 + len + 2)) == NULL)
  894.                                 return NULL;
  895.                         memcpy(s, relative, n);
  896.                 }
  897.                 s[(n++)] = '/';
  898.                 strip = n;
  899.                 memcpy(&s[n], prefix, len);
  900.                 len += n;
  901.                 s[(len++)] = '*';
  902.                 s[len] = '\0';
  903.         }
  904.         else if (prefix[0] == '~') {
  905.                 char **ud;
  906.                 size_t n;
  907.  
  908.                 if (s == NULL)
  909.                         return complete_userdir(&prefix[1], (i - 1),
  910.                                                 (COMPLETE_USERDIR_TILDE |
  911.                                                  COMPLETE_USERDIR_ALL));
  912.                 ud = complete_userdir(&prefix[1], (i - 1),
  913.                                       COMPLETE_USERDIR_EXACT);
  914.                 if (ud == NULL)
  915.                         goto no_userdir;
  916.                 n = strlen(ud[0]);
  917.                 if ((s = realloc(ud[0], (n + (len - i) + 2))) == NULL) {
  918.                         free_pppc(&ud, 0);
  919.                         goto no_userdir;
  920.                 }
  921.                 free_pppc(&ud, 1);
  922.                 len -= i;
  923.                 strip = 0;
  924.                 memcpy(&s[n], &prefix[i], len);
  925.                 len += n;
  926.                 s[(len++)] = '*';
  927.                 s[len] = '\0';
  928.         }
  929.         else {
  930.         no_userdir:
  931.                 if ((s = malloc(len + 2)) == NULL)
  932.                         return NULL;
  933.                 memcpy(s, prefix, len);
  934.                 s[(len++)] = '*';
  935.                 s[len] = '\0';
  936.                 strip = 0;
  937.         }
  938.         switch (glob(s, (GLOB_MARK | GLOB_NOESCAPE), NULL, &g)) {
  939.         case 0:
  940.                 break;
  941.         case GLOB_NOSPACE:
  942.         case GLOB_ABORTED:
  943.         case GLOB_NOMATCH:
  944.         default:
  945.                 free(s);
  946.                 return NULL;
  947.         }
  948.         free(s);
  949.         if ((ret = calloc((g.gl_pathc + 1), sizeof(ret[0]))) == NULL)
  950.                 goto err;
  951.         for (i = 0; (g.gl_pathv[i] != NULL); ++i) {
  952.                 size_t j;
  953.  
  954.                 len = strlen(g.gl_pathv[i]);
  955.                 if (strip > len)
  956.                         break;
  957.                 j = (len - strip);
  958.                 if ((ret[i] = calloc((j + 1), sizeof(ret[i][0]))) == NULL)
  959.                         break;
  960.                 memcpy(ret[i], &(g.gl_pathv[i][strip]), j);
  961.                 ret[i][j] = '\0';
  962.         }
  963.         if (i == 0)
  964.                 goto err;
  965.         globfree(&g);
  966.         return ret;
  967. err:
  968.         globfree(&g);
  969.         free_pppc(&ret, 0);
  970.         return NULL;
  971. }
  972.  
  973. #else /* defined(HAVE_GLOB_H) && !defined(__MINGW32__) */
  974.  
  975. /**
  976.  * Return a list of pathnames that match "len" characters of "prefix" on the
  977.  * file system, or NULL if none was found or if an error occured.
  978.  *
  979.  * When "prefix" isn't explicitly relative nor absolute, if "relative" is
  980.  * non-NULL, then the path will be completed as if "prefix" was a subdirectory
  981.  * of "relative". If "relative" is NULL, DGen's home directory will be used.
  982.  *
  983.  * If "relative" isn't explicitly relative nor absolute, it will be considered
  984.  * a subdirectory of DGen's home directory.
  985.  *
  986.  * @param[in] prefix Path name to match.
  987.  * @param len Number of characters to match in "path".
  988.  * @param[in] relative If non-NULL, consider path relative to this.
  989.  * @return List of path names that match "len" characters of "prefix".
  990.  */
  991. char **complete_path(const char *prefix, size_t len, const char *relative)
  992. {
  993.         char *s;
  994.         char **ret;
  995.         size_t i;
  996.         size_t n;
  997.         size_t strip;
  998.         enum path_type pt;
  999.  
  1000.         if ((i = strlen(prefix)) < len)
  1001.                 len = i;
  1002.         if (((pt = path_type(prefix, len)) == PATH_TYPE_ABSOLUTE) ||
  1003.             (pt == PATH_TYPE_RELATIVE))
  1004.                 return complete_path_simple(prefix, len);
  1005.         if ((len != 0) && (prefix[0] == '~') &&
  1006.             ((len == 1) ||
  1007.              (prefix[1] == '\0') ||
  1008.              (strpbrk(prefix, DGEN_DIRSEP) == &prefix[1]))) {
  1009.                 char *x = dgen_userdir(NULL, &n);
  1010.  
  1011.                 if ((x == NULL) ||
  1012.                     ((s = realloc(x, (n + 1 + 2 + len + 1))) == NULL)) {
  1013.                         free(x);
  1014.                         return NULL;
  1015.                 }
  1016.                 ++prefix;
  1017.                 --len;
  1018.                 strip = 0;
  1019.         }
  1020.         else if ((relative == NULL) ||
  1021.                  (path_type(relative, ~0u) == PATH_TYPE_UNSPECIFIED)) {
  1022.                 char *x = dgen_dir(NULL, &n, relative);
  1023.  
  1024.                 if ((x == NULL) ||
  1025.                     ((s = realloc(x, (n + 1 + len + 1))) == NULL)) {
  1026.                         free(x);
  1027.                         return NULL;
  1028.                 }
  1029.                 strip = (n + 1);
  1030.         }
  1031.         else {
  1032.                 n = strlen(relative);
  1033.                 if ((s = malloc(n + 1 + len + 1)) == NULL)
  1034.                         return NULL;
  1035.                 memcpy(s, relative, n);
  1036.                 strip = (n + 1);
  1037.         }
  1038.         s[(n++)] = DGEN_DIRSEP[0];
  1039.         memcpy(&s[n], prefix, len);
  1040.         len += n;
  1041.         s[len] = '\0';
  1042.         ret = complete_path_simple(s, len);
  1043.         free(s);
  1044.         if (ret == NULL)
  1045.                 return NULL;
  1046.         if (strip == 0)
  1047.                 return ret;
  1048.         for (i = 0; (ret[i] != NULL); ++i)
  1049.                 memmove(ret[i], &ret[i][strip],
  1050.                         ((strlen(ret[i]) - strip) + 1));
  1051.         return ret;
  1052. }
  1053.  
  1054. #endif /* defined(HAVE_GLOB_H) && !defined(__MINGW32__) */
  1055.  
  1056. /**
  1057.  * Free return value of complete*() functions.
  1058.  *
  1059.  * @param[in, out] cp Buffer to pass to free_pppc().
  1060.  */
  1061. void complete_path_free(char **cp)
  1062. {
  1063.         free_pppc(&cp, 0);
  1064. }
  1065.  
  1066. /**
  1067.  * Create an escaped version of a string.
  1068.  * When not NULL, "pos" refers to an offset in string "src". It is updated
  1069.  * with its new offset value in the escaped string.
  1070.  *
  1071.  * @param[in] src String to escape.
  1072.  * @param size Number of characters from "src" to process.
  1073.  * @param flags BACKSLASHIFY_* flags.
  1074.  * @param[in, out] pos Offset in string "src" to update.
  1075.  * @return Escaped version of "src", NULL on error.
  1076.  */
  1077. char *backslashify(const uint8_t *src, size_t size, unsigned int flags,
  1078.                    size_t *pos)
  1079. {
  1080.         char *dst = NULL;
  1081.         char *tmp;
  1082.         size_t i;
  1083.         size_t j;
  1084.         char buf[5];
  1085.  
  1086. again:
  1087.         for (i = 0, j = 0; (i < size); ++i) {
  1088.                 switch (src[i]) {
  1089.                 case '\a':
  1090.                         tmp = "\\a";
  1091.                         break;
  1092.                 case '\b':
  1093.                         tmp = "\\b";
  1094.                         break;
  1095.                 case '\f':
  1096.                         tmp = "\\f";
  1097.                         break;
  1098.                 case '\n':
  1099.                         tmp = "\\n";
  1100.                         break;
  1101.                 case '\r':
  1102.                         tmp = "\\r";
  1103.                         break;
  1104.                 case '\t':
  1105.                         tmp = "\\t";
  1106.                         break;
  1107.                 case '\v':
  1108.                         tmp = "\\v";
  1109.                         break;
  1110.                 case '\'':
  1111.                         if (flags & BACKSLASHIFY_NOQUOTES)
  1112.                                 goto noquotes;
  1113.                         tmp = "\\'";
  1114.                         break;
  1115.                 case '"':
  1116.                         if (flags & BACKSLASHIFY_NOQUOTES)
  1117.                                 goto noquotes;
  1118.                         tmp = "\\\"";
  1119.                         break;
  1120.                 case ' ':
  1121.                         if (flags & BACKSLASHIFY_NOQUOTES)
  1122.                                 tmp = " ";
  1123.                         else
  1124.                                 tmp = "\\ ";
  1125.                         break;
  1126.                 case '\0':
  1127.                         tmp = "\\0";
  1128.                         break;
  1129.                 case '\\':
  1130.                         if (flags & BACKSLASHIFY_NOQUOTES)
  1131.                                 goto noquotes;
  1132.                         tmp = "\\\\";
  1133.                         break;
  1134.                 default:
  1135.                 noquotes:
  1136.                         tmp = buf;
  1137.                         if (isgraph(src[i])) {
  1138.                                 tmp[0] = src[i];
  1139.                                 tmp[1] = '\0';
  1140.                                 break;
  1141.                         }
  1142.                         tmp[0] = '\\';
  1143.                         tmp[1] = 'x';
  1144.                         snprintf(&tmp[2], 3, "%02x", src[i]);
  1145.                         break;
  1146.                 }
  1147.                 if (dst != NULL)
  1148.                         strncpy(&dst[j], tmp, strlen(tmp));
  1149.                 if ((pos != NULL) && (i == *pos)) {
  1150.                         *pos = j;
  1151.                         pos = NULL;
  1152.                 }
  1153.                 j += strlen(tmp);
  1154.         }
  1155.         if ((pos != NULL) && (i == *pos)) {
  1156.                 *pos = j;
  1157.                 pos = NULL;
  1158.         }
  1159.         if (dst == NULL) {
  1160.                 dst = malloc(j + 1);
  1161.                 if (dst == NULL)
  1162.                         return NULL;
  1163.                 dst[j] = '\0';
  1164.                 goto again;
  1165.         }
  1166.         return dst;
  1167. }
  1168.  
  1169. /**
  1170.  * Convert a UTF-8 character to its 32 bit representation.
  1171.  * Return the number of valid bytes for this character.
  1172.  * On error, u32 is set to (uint32_t)-1.
  1173.  *
  1174.  * @param[out] u32 Converted character, (uint32_t)-1 on error.
  1175.  * @param[in] u8 Multibyte character to convert.
  1176.  * @return Number of bytes read.
  1177.  */
  1178. size_t utf8u32(uint32_t *u32, const uint8_t *u8)
  1179. {
  1180.         static const uint8_t fb[] = {
  1181.                 /* first byte: mask, expected value, size */
  1182.                 0x80, 0x00, 1,
  1183.                 0xe0, 0xc0, 2,
  1184.                 0xf0, 0xe0, 3,
  1185.                 0xf8, 0xf0, 4,
  1186.                 0xfc, 0xf8, 5,
  1187.                 0xfe, 0xfc, 6,
  1188.                 0xff, 0x00, 0
  1189.         };
  1190.         const uint8_t *s = fb;
  1191.         size_t i = 0;
  1192.         size_t rem;
  1193.         uint32_t ret;
  1194.  
  1195.         while ((*u8 & s[0]) != s[1])
  1196.                 s += 3;
  1197.         rem = s[2];
  1198.         if (!rem)
  1199.                 goto error;
  1200.         ret = (*u8 & ~s[0]);
  1201.         while (++i != rem) {
  1202.                 ++u8;
  1203.                 if ((*u8 & 0xc0) != 0x80)
  1204.                         goto error;
  1205.                 ret <<= 6;
  1206.                 ret |= (*u8 & ~0xc0);
  1207.         }
  1208.         if (((ret & ~0x07ff) == 0xd800) ||
  1209.             ((ret & ~0x0001) == 0xfffe))
  1210.                 goto error;
  1211.         *u32 = ret;
  1212.         return i;
  1213. error:
  1214.         *u32 = (uint32_t)-1;
  1215.         return i;
  1216. }
  1217.  
  1218. /**
  1219.  * The opposite of utf8u32().
  1220.  *
  1221.  * @param[out] u8 Converted character.
  1222.  * @param u32 Character to convert.
  1223.  * @return Number of characters written to "u8", 0 on error.
  1224.  */
  1225. size_t utf32u8(uint8_t *u8, uint32_t u32)
  1226. {
  1227.         size_t l;
  1228.         size_t i;
  1229.         uint8_t fb;
  1230.         uint32_t u;
  1231.  
  1232.         if ((u32 & 0x80000000) ||
  1233.             ((u32 & ~0x07ff) == 0xd800) ||
  1234.             ((u32 & ~0x0001) == 0xfffe))
  1235.                 return 0;
  1236.         if (u32 < 0x80) {
  1237.                 if (u8 != NULL)
  1238.                         *u8 = u32;
  1239.                 return 1;
  1240.         }
  1241.         for (l = 0, u = u32; (u & ~0x3c); ++l)
  1242.                 u >>= 6;
  1243.         if (u8 == NULL)
  1244.                 return l;
  1245.         for (i = l, fb = 0; (--i); u32 >>= 6, fb >>= 1, fb |= 0xc0)
  1246.                 u8[i] = (0x80 | (u32 & 0x3f));
  1247.         u8[0] = (fb | u32);
  1248.         return l;
  1249. }
  1250.  
  1251. /**
  1252.  * Look for the longest common prefix between a string and an array
  1253.  * of strings while ignoring case.
  1254.  *
  1255.  * @param[in] str String to compare argv entries to.
  1256.  * @param[in] argv NULL-terminated array of prefixes to match.
  1257.  * @return Index in argv or -1 if nothing matches.
  1258.  */
  1259. int prefix_casematch(const char *str, const char *argv[])
  1260. {
  1261.         unsigned int i;
  1262.         size_t ret_len = 0;
  1263.         int ret = -1;
  1264.  
  1265.         for (i = 0; (argv[i] != NULL); ++i) {
  1266.                 size_t len = strlen(argv[i]);
  1267.  
  1268.                 if ((len < ret_len) ||
  1269.                     (strncasecmp(str, argv[i], len)))
  1270.                         continue;
  1271.                 ret_len = len;
  1272.                 ret = i;
  1273.         }
  1274.         return ret;
  1275. }
  1276.  
  1277. /**
  1278.  * Read number from initial portion of a string and convert it.
  1279.  *
  1280.  * @param[in] str String to read from.
  1281.  * @param[out] num If not NULL, stores the converted number.
  1282.  * @return Length of the number in str, 0 on error.
  1283.  */
  1284. size_t prefix_getuint(const char *str, unsigned int *num)
  1285. {
  1286.         size_t len = 0;
  1287.         unsigned int ret = 0;
  1288.  
  1289.         while (isdigit(str[len])) {
  1290.                 ret *= 10;
  1291.                 ret += (str[len] - '0');
  1292.                 ++len;
  1293.         }
  1294.         if (len == 0)
  1295.                 return 0;
  1296.         if (num != NULL)
  1297.                 *num = ret;
  1298.         return len;
  1299. }
  1300.