Advertisement
Guest User

Untitled

a guest
Dec 14th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.28 KB | None | 0 0
  1. /*
  2.     Normalize a URI path to remove "./",  "../" and redundant separators. Note: this does not make an abs path and
  3.     does not map separators nor change case.
  4.  */
  5. PUBLIC char *websNormalizeUriPath(char *pathArg)
  6. {
  7.     char    *dupPath, *path, *sp, *dp, *mark, **segments;
  8.     int     firstc, j, i, nseg, len;
  9.  
  10.     if (pathArg == 0 || *pathArg == '\0') {
  11.         return sclone("");
  12.     }
  13.     len = (int) slen(pathArg);
  14.     if ((dupPath = walloc(len + 2)) == 0) {
  15.         return NULL;
  16.     }
  17.     strcpy(dupPath, pathArg);
  18.  
  19.     if ((segments = walloc(sizeof(char*) * (len + 1))) == 0) {
  20.         return NULL;
  21.     }
  22.     nseg = len = 0;
  23.     firstc = *dupPath;
  24.     for (mark = sp = dupPath; *sp; sp++) {
  25.         if (*sp == '/') {
  26.             *sp = '\0';
  27.             while (sp[1] == '/') {
  28.                 sp++;
  29.             }
  30.             segments[nseg++] = mark;
  31.             len += (int) (sp - mark);
  32.             mark = sp + 1;
  33.         }
  34.     }
  35.     segments[nseg++] = mark;
  36.     len += (int) (sp - mark);
  37.     for (j = i = 0; i < nseg; i++, j++) {
  38.         sp = segments[i];
  39.         if (sp[0] == '.') {
  40.             if (sp[1] == '\0')  {
  41.                 if ((i+1) == nseg) {
  42.                     segments[j] = "";
  43.                 } else {
  44.                     j--;
  45.                 }
  46.             } else if (sp[1] == '.' && sp[2] == '\0')  {
  47.                 if (i == 1 && *segments[0] == '\0') {
  48.                     j = 0;
  49.                 } else if ((i+1) == nseg) {
  50.                     if (--j >= 0) {
  51.                         segments[j] = "";
  52.                     }
  53.                 } else {
  54.                     j = max(j - 2, -1);
  55.                 }
  56.             }
  57.         } else {
  58.             segments[j] = segments[i];
  59.         }
  60.     }
  61.     nseg = j;
  62.     assert(nseg >= 0);
  63.     if ((path = walloc(len + nseg + 1)) != 0) {
  64.         for (i = 0, dp = path; i < nseg; ) {
  65.             strcpy(dp, segments[i]);
  66.             len = (int) slen(segments[i]);
  67.             dp += len;
  68.             if (++i < nseg || (nseg == 1 && *segments[0] == '\0' && firstc == '/')) {
  69.                 *dp++ = '/';
  70.             }
  71.         }
  72.         *dp = '\0';
  73.     }
  74.     wfree(dupPath);
  75.     wfree(segments);
  76.     if ((path[0] != '/') || strchr(path, '\\')) {
  77.         return 0;
  78.     }
  79.     return path;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement