gophra

gopher client for plan9
git clone git://nsmpr.xyz/gophra.git
Log | Files | Refs

uri.c (1284B)


      1 #include <u.h>
      2 #include <libc.h>
      3 #include <regexp.h>
      4 
      5 #include "uri.h"
      6 
      7 char*
      8 match2str(Resub *m)
      9 {
     10 	long n;
     11 	char *r;
     12 	if (m->sp == 0) return 0;
     13 	n = m->ep - m->sp + 1;
     14 	r = mallocz(n, 1);
     15 	strncpy(r, m->sp, n - 1);
     16 	return r;
     17 }
     18 
     19 URI*
     20 chewuri(char *s)
     21 {
     22 	URI *r;
     23 	Reprog *uriprog, *authprog;
     24 	Resub *m, *n;
     25 	char *auth;
     26 	auth = 0;
     27 	r = mallocz(sizeof(URI), 1);
     28 	m = mallocz(sizeof(Resub) * 16, 1);
     29 	n = mallocz(sizeof(Resub) * 8, 1);
     30 	/* scheme://user@host:port/path?query#fragment */
     31 
     32 	uriprog = regcomp(
     33 		"(([^:]+):)"
     34 		"(//([^/?#]+))?"
     35 		"(/?[^?#]*)?"
     36 		"(\\?([^#]+))?"
     37 		"(#(.*))?"
     38 		);
     39 	authprog = regcomp(
     40 		"(([^@]+)@)?"
     41 		"([^:]+)"
     42 		"(:([0-9]+))?"
     43 		);
     44 	if (regexec(uriprog, s, m, 16) == 1){
     45 		r->scheme = match2str(&m[2]);
     46 		auth = match2str(&m[4]);
     47 		r->path = match2str(&m[5]);
     48 		r->query = match2str(&m[7]);
     49 		r->fragment = match2str(&m[9]);
     50 	}
     51 	if ((auth != nil) && (regexec(authprog, auth, n, 8) == 1)) {
     52 		r->user = match2str(&n[2]);
     53 		r->host = match2str(&n[3]);
     54 		r->port = match2str(&n[5]);
     55 	}
     56 	free(uriprog);
     57 	free(authprog);
     58 	free(m);
     59 	free(n);
     60 	return r;
     61 }
     62 
     63 void
     64 freeuri(URI *uri)
     65 {
     66 	realloc(uri->scheme, 0);
     67 	realloc(uri->user, 0);
     68 	realloc(uri->host, 0);
     69 	realloc(uri->port, 0);
     70 	realloc(uri->path, 0);
     71 	realloc(uri->query, 0);
     72 	realloc(uri->fragment, 0);
     73 }