url: Allow various `safe' characters unquoted in URL strings.
[mLib] / url.c
diff --git a/url.c b/url.c
index 75b6ff9..f7e11b3 100644 (file)
--- a/url.c
+++ b/url.c
@@ -1,6 +1,6 @@
 /* -*-c-*-
  *
- * $Id: url.c,v 1.2 1999/09/03 08:02:05 mdw Exp $
+ * $Id: url.c,v 1.5 2004/04/08 01:36:13 mdw Exp $
  *
  * Parsing and construction of url-encoded name/value pairs
  *
  * MA 02111-1307, USA.
  */
 
-/*----- Revision history --------------------------------------------------* 
- *
- * $Log: url.c,v $
- * Revision 1.2  1999/09/03 08:02:05  mdw
- * Make `#' a special character which needs escaping.
- *
- * Revision 1.1  1999/06/01 09:49:48  mdw
- * New files for url-encoding and decoding.
- *
- */
-
 /*----- Header files ------------------------------------------------------*/
 
+#include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
  * Use:                Initializes a URL encoding context.
  */
 
-void url_initenc(url_ectx *ctx)
-{
-  ctx->f = 0;
-}
+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:    ---
@@ -73,7 +61,7 @@ void url_initenc(url_ectx *ctx)
  * 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) {
@@ -81,16 +69,28 @@ static void encode(dstr *d, const char *p)
        DPUTC(d, '+');
         break;
       default:
-        if (*p >= 33 && *p < 127)
-         DPUTC(d, *p);
-        else
-      case '&':
+        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 '=':
+      case '&':
+      case ';':
        dstr_putf(d, "%%%02x", *p);
-        break;
+       break;
     }
     p++;
   }
@@ -113,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;
 }
@@ -130,10 +130,7 @@ void url_enc(url_ectx *ctx, dstr *d, const char *name, const char *value)
  * Use:                Initializes a URL decoding context.
  */
 
-void url_initdec(url_dctx *ctx, const char *p)
-{
-  ctx->p = p;
-}
+void url_initdec(url_dctx *ctx, const char *p) { ctx->p = p; }
 
 /* --- @decode@ --- *
  *