chiark / gitweb /
url: Allow various `safe' characters unquoted in URL strings.
[mLib] / url.c
diff --git a/url.c b/url.c
index d859bfa922087a6bea68b8a7211cdec2ef2c88bf..f7e11b3c28616c6cb5a79acbc44b3879a7cef74b 100644 (file)
--- a/url.c
+++ b/url.c
@@ -52,7 +52,8 @@ void url_initenc(url_ectx *ctx) { ctx->f = 0; }
 
 /* --- @encode@ --- *
  *
- * Arguments:  @dstr *d@ = pointer to output string
+ * Arguments:  @url_ectx *ctx@ = encoding context
+ *             @dstr *d@ = pointer to output string
  *             @const char *p@ = pointer to thing to encode
  *
  * Returns:    ---
@@ -60,7 +61,7 @@ void url_initenc(url_ectx *ctx) { ctx->f = 0; }
  * Use:                Encodes the input string into the output string.
  */
 
-static void encode(dstr *d, const char *p)
+static void encode(url_ectx *ctx, dstr *d, const char *p)
 {
   while (*p) {
     switch (*p) {
@@ -68,11 +69,28 @@ static void encode(dstr *d, const char *p)
        DPUTC(d, '+');
         break;
       default:
-        if (isalnum((unsigned char)*p))
-         DPUTC(d, *p);
-        else
-         dstr_putf(d, "%%%02x", *p);
-        break;
+        if ((ctx->f & URLF_LAX) || isalnum((unsigned char)*p))
+         goto safe;
+       else
+         goto unsafe;
+      case '/':
+      case '~':
+       if (ctx->f & URLF_STRICT)
+         goto unsafe;
+      case '-':
+      case '.':
+      case '_':
+      safe:
+       DPUTC(d, *p);
+       break;
+      unsafe:
+      case '+':
+      case '%':
+      case '=':
+      case '&':
+      case ';':
+       dstr_putf(d, "%%%02x", *p);
+       break;
     }
     p++;
   }
@@ -95,9 +113,9 @@ void url_enc(url_ectx *ctx, dstr *d, const char *name, const char *value)
 {
   if (ctx->f & URLF_SEP)
     DPUTC(d, '&');
-  encode(d, name);
+  encode(ctx, d, name);
   DPUTC(d, '=');
-  encode(d, value);
+  encode(ctx, d, value);
   DPUTZ(d);
   ctx->f |= URLF_SEP;
 }