2
0

urlapi.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #include "urldata.h"
  26. #include "urlapi-int.h"
  27. #include "strcase.h"
  28. #include "url.h"
  29. #include "escape.h"
  30. #include "curl_ctype.h"
  31. #include "inet_pton.h"
  32. #include "inet_ntop.h"
  33. #include "strdup.h"
  34. #include "idn.h"
  35. #include "curl_memrchr.h"
  36. /* The last 3 #include files should be in this order */
  37. #include "curl_printf.h"
  38. #include "curl_memory.h"
  39. #include "memdebug.h"
  40. /* MSDOS/Windows style drive prefix, eg c: in c:foo */
  41. #define STARTS_WITH_DRIVE_PREFIX(str) \
  42. ((('a' <= str[0] && str[0] <= 'z') || \
  43. ('A' <= str[0] && str[0] <= 'Z')) && \
  44. (str[1] == ':'))
  45. /* MSDOS/Windows style drive prefix, optionally with
  46. * a '|' instead of ':', followed by a slash or NUL */
  47. #define STARTS_WITH_URL_DRIVE_PREFIX(str) \
  48. ((('a' <= (str)[0] && (str)[0] <= 'z') || \
  49. ('A' <= (str)[0] && (str)[0] <= 'Z')) && \
  50. ((str)[1] == ':' || (str)[1] == '|') && \
  51. ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
  52. /* scheme is not URL encoded, the longest libcurl supported ones are... */
  53. #define MAX_SCHEME_LEN 40
  54. /*
  55. * If ENABLE_IPV6 is disabled, we still want to parse IPv6 addresses, so make
  56. * sure we have _some_ value for AF_INET6 without polluting our fake value
  57. * everywhere.
  58. */
  59. #if !defined(ENABLE_IPV6) && !defined(AF_INET6)
  60. #define AF_INET6 (AF_INET + 1)
  61. #endif
  62. /* Internal representation of CURLU. Point to URL-encoded strings. */
  63. struct Curl_URL {
  64. char *scheme;
  65. char *user;
  66. char *password;
  67. char *options; /* IMAP only? */
  68. char *host;
  69. char *zoneid; /* for numerical IPv6 addresses */
  70. char *port;
  71. char *path;
  72. char *query;
  73. char *fragment;
  74. long portnum; /* the numerical version */
  75. };
  76. #define DEFAULT_SCHEME "https"
  77. static void free_urlhandle(struct Curl_URL *u)
  78. {
  79. free(u->scheme);
  80. free(u->user);
  81. free(u->password);
  82. free(u->options);
  83. free(u->host);
  84. free(u->zoneid);
  85. free(u->port);
  86. free(u->path);
  87. free(u->query);
  88. free(u->fragment);
  89. }
  90. /*
  91. * Find the separator at the end of the host name, or the '?' in cases like
  92. * http://www.url.com?id=2380
  93. */
  94. static const char *find_host_sep(const char *url)
  95. {
  96. const char *sep;
  97. const char *query;
  98. /* Find the start of the hostname */
  99. sep = strstr(url, "//");
  100. if(!sep)
  101. sep = url;
  102. else
  103. sep += 2;
  104. query = strchr(sep, '?');
  105. sep = strchr(sep, '/');
  106. if(!sep)
  107. sep = url + strlen(url);
  108. if(!query)
  109. query = url + strlen(url);
  110. return sep < query ? sep : query;
  111. }
  112. /*
  113. * Decide whether a character in a URL must be escaped.
  114. */
  115. #define urlchar_needs_escaping(c) (!(ISCNTRL(c) || ISSPACE(c) || ISGRAPH(c)))
  116. static const char hexdigits[] = "0123456789abcdef";
  117. /* urlencode_str() writes data into an output dynbuf and URL-encodes the
  118. * spaces in the source URL accordingly.
  119. *
  120. * URL encoding should be skipped for host names, otherwise IDN resolution
  121. * will fail.
  122. */
  123. static CURLUcode urlencode_str(struct dynbuf *o, const char *url,
  124. size_t len, bool relative,
  125. bool query)
  126. {
  127. /* we must add this with whitespace-replacing */
  128. bool left = !query;
  129. const unsigned char *iptr;
  130. const unsigned char *host_sep = (const unsigned char *) url;
  131. if(!relative)
  132. host_sep = (const unsigned char *) find_host_sep(url);
  133. for(iptr = (unsigned char *)url; /* read from here */
  134. len; iptr++, len--) {
  135. if(iptr < host_sep) {
  136. if(Curl_dyn_addn(o, iptr, 1))
  137. return CURLUE_OUT_OF_MEMORY;
  138. continue;
  139. }
  140. if(*iptr == ' ') {
  141. if(left) {
  142. if(Curl_dyn_addn(o, "%20", 3))
  143. return CURLUE_OUT_OF_MEMORY;
  144. }
  145. else {
  146. if(Curl_dyn_addn(o, "+", 1))
  147. return CURLUE_OUT_OF_MEMORY;
  148. }
  149. continue;
  150. }
  151. if(*iptr == '?')
  152. left = FALSE;
  153. if(urlchar_needs_escaping(*iptr)) {
  154. char out[3]={'%'};
  155. out[1] = hexdigits[*iptr>>4];
  156. out[2] = hexdigits[*iptr & 0xf];
  157. if(Curl_dyn_addn(o, out, 3))
  158. return CURLUE_OUT_OF_MEMORY;
  159. }
  160. else {
  161. if(Curl_dyn_addn(o, iptr, 1))
  162. return CURLUE_OUT_OF_MEMORY;
  163. }
  164. }
  165. return CURLUE_OK;
  166. }
  167. /*
  168. * Returns the length of the scheme if the given URL is absolute (as opposed
  169. * to relative). Stores the scheme in the buffer if TRUE and 'buf' is
  170. * non-NULL. The buflen must be larger than MAX_SCHEME_LEN if buf is set.
  171. *
  172. * If 'guess_scheme' is TRUE, it means the URL might be provided without
  173. * scheme.
  174. */
  175. size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen,
  176. bool guess_scheme)
  177. {
  178. int i = 0;
  179. DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN));
  180. (void)buflen; /* only used in debug-builds */
  181. if(buf)
  182. buf[0] = 0; /* always leave a defined value in buf */
  183. #ifdef WIN32
  184. if(guess_scheme && STARTS_WITH_DRIVE_PREFIX(url))
  185. return 0;
  186. #endif
  187. if(ISALPHA(url[0]))
  188. for(i = 1; i < MAX_SCHEME_LEN; ++i) {
  189. char s = url[i];
  190. if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.') )) {
  191. /* RFC 3986 3.1 explains:
  192. scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  193. */
  194. }
  195. else {
  196. break;
  197. }
  198. }
  199. if(i && (url[i] == ':') && ((url[i + 1] == '/') || !guess_scheme)) {
  200. /* If this does not guess scheme, the scheme always ends with the colon so
  201. that this also detects data: URLs etc. In guessing mode, data: could
  202. be the host name "data" with a specified port number. */
  203. /* the length of the scheme is the name part only */
  204. size_t len = i;
  205. if(buf) {
  206. buf[i] = 0;
  207. while(i--) {
  208. buf[i] = Curl_raw_tolower(url[i]);
  209. }
  210. }
  211. return len;
  212. }
  213. return 0;
  214. }
  215. /*
  216. * Concatenate a relative URL to a base URL making it absolute.
  217. * URL-encodes any spaces.
  218. * The returned pointer must be freed by the caller unless NULL
  219. * (returns NULL on out of memory).
  220. *
  221. * Note that this function destroys the 'base' string.
  222. */
  223. static char *concat_url(char *base, const char *relurl)
  224. {
  225. /***
  226. TRY to append this new path to the old URL
  227. to the right of the host part. Oh crap, this is doomed to cause
  228. problems in the future...
  229. */
  230. struct dynbuf newest;
  231. char *protsep;
  232. char *pathsep;
  233. bool host_changed = FALSE;
  234. const char *useurl = relurl;
  235. /* protsep points to the start of the host name */
  236. protsep = strstr(base, "//");
  237. if(!protsep)
  238. protsep = base;
  239. else
  240. protsep += 2; /* pass the slashes */
  241. if('/' != relurl[0]) {
  242. int level = 0;
  243. /* First we need to find out if there's a ?-letter in the URL,
  244. and cut it and the right-side of that off */
  245. pathsep = strchr(protsep, '?');
  246. if(pathsep)
  247. *pathsep = 0;
  248. /* we have a relative path to append to the last slash if there's one
  249. available, or if the new URL is just a query string (starts with a
  250. '?') we append the new one at the end of the entire currently worked
  251. out URL */
  252. if(useurl[0] != '?') {
  253. pathsep = strrchr(protsep, '/');
  254. if(pathsep)
  255. *pathsep = 0;
  256. }
  257. /* Check if there's any slash after the host name, and if so, remember
  258. that position instead */
  259. pathsep = strchr(protsep, '/');
  260. if(pathsep)
  261. protsep = pathsep + 1;
  262. else
  263. protsep = NULL;
  264. /* now deal with one "./" or any amount of "../" in the newurl
  265. and act accordingly */
  266. if((useurl[0] == '.') && (useurl[1] == '/'))
  267. useurl += 2; /* just skip the "./" */
  268. while((useurl[0] == '.') &&
  269. (useurl[1] == '.') &&
  270. (useurl[2] == '/')) {
  271. level++;
  272. useurl += 3; /* pass the "../" */
  273. }
  274. if(protsep) {
  275. while(level--) {
  276. /* cut off one more level from the right of the original URL */
  277. pathsep = strrchr(protsep, '/');
  278. if(pathsep)
  279. *pathsep = 0;
  280. else {
  281. *protsep = 0;
  282. break;
  283. }
  284. }
  285. }
  286. }
  287. else {
  288. /* We got a new absolute path for this server */
  289. if(relurl[1] == '/') {
  290. /* the new URL starts with //, just keep the protocol part from the
  291. original one */
  292. *protsep = 0;
  293. useurl = &relurl[2]; /* we keep the slashes from the original, so we
  294. skip the new ones */
  295. host_changed = TRUE;
  296. }
  297. else {
  298. /* cut off the original URL from the first slash, or deal with URLs
  299. without slash */
  300. pathsep = strchr(protsep, '/');
  301. if(pathsep) {
  302. /* When people use badly formatted URLs, such as
  303. "http://www.url.com?dir=/home/daniel" we must not use the first
  304. slash, if there's a ?-letter before it! */
  305. char *sep = strchr(protsep, '?');
  306. if(sep && (sep < pathsep))
  307. pathsep = sep;
  308. *pathsep = 0;
  309. }
  310. else {
  311. /* There was no slash. Now, since we might be operating on a badly
  312. formatted URL, such as "http://www.url.com?id=2380" which doesn't
  313. use a slash separator as it is supposed to, we need to check for a
  314. ?-letter as well! */
  315. pathsep = strchr(protsep, '?');
  316. if(pathsep)
  317. *pathsep = 0;
  318. }
  319. }
  320. }
  321. Curl_dyn_init(&newest, CURL_MAX_INPUT_LENGTH);
  322. /* copy over the root url part */
  323. if(Curl_dyn_add(&newest, base))
  324. return NULL;
  325. /* check if we need to append a slash */
  326. if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
  327. ;
  328. else {
  329. if(Curl_dyn_addn(&newest, "/", 1))
  330. return NULL;
  331. }
  332. /* then append the new piece on the right side */
  333. urlencode_str(&newest, useurl, strlen(useurl), !host_changed, FALSE);
  334. return Curl_dyn_ptr(&newest);
  335. }
  336. /* scan for byte values <= 31, 127 and sometimes space */
  337. static CURLUcode junkscan(const char *url, size_t *urllen, unsigned int flags)
  338. {
  339. static const char badbytes[]={
  340. /* */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  341. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  342. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  343. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  344. 0x7f, 0x00 /* null-terminate */
  345. };
  346. size_t n = strlen(url);
  347. size_t nfine;
  348. if(n > CURL_MAX_INPUT_LENGTH)
  349. /* excessive input length */
  350. return CURLUE_MALFORMED_INPUT;
  351. nfine = strcspn(url, badbytes);
  352. if((nfine != n) ||
  353. (!(flags & CURLU_ALLOW_SPACE) && strchr(url, ' ')))
  354. return CURLUE_MALFORMED_INPUT;
  355. *urllen = n;
  356. return CURLUE_OK;
  357. }
  358. /*
  359. * parse_hostname_login()
  360. *
  361. * Parse the login details (user name, password and options) from the URL and
  362. * strip them out of the host name
  363. *
  364. */
  365. static CURLUcode parse_hostname_login(struct Curl_URL *u,
  366. const char *login,
  367. size_t len,
  368. unsigned int flags,
  369. size_t *offset) /* to the host name */
  370. {
  371. CURLUcode result = CURLUE_OK;
  372. CURLcode ccode;
  373. char *userp = NULL;
  374. char *passwdp = NULL;
  375. char *optionsp = NULL;
  376. const struct Curl_handler *h = NULL;
  377. /* At this point, we assume all the other special cases have been taken
  378. * care of, so the host is at most
  379. *
  380. * [user[:password][;options]]@]hostname
  381. *
  382. * We need somewhere to put the embedded details, so do that first.
  383. */
  384. char *ptr;
  385. DEBUGASSERT(login);
  386. *offset = 0;
  387. ptr = memchr(login, '@', len);
  388. if(!ptr)
  389. goto out;
  390. /* We will now try to extract the
  391. * possible login information in a string like:
  392. * ftp://user:password@ftp.my.site:8021/README */
  393. ptr++;
  394. /* if this is a known scheme, get some details */
  395. if(u->scheme)
  396. h = Curl_builtin_scheme(u->scheme, CURL_ZERO_TERMINATED);
  397. /* We could use the login information in the URL so extract it. Only parse
  398. options if the handler says we should. Note that 'h' might be NULL! */
  399. ccode = Curl_parse_login_details(login, ptr - login - 1,
  400. &userp, &passwdp,
  401. (h && (h->flags & PROTOPT_URLOPTIONS)) ?
  402. &optionsp:NULL);
  403. if(ccode) {
  404. result = CURLUE_BAD_LOGIN;
  405. goto out;
  406. }
  407. if(userp) {
  408. if(flags & CURLU_DISALLOW_USER) {
  409. /* Option DISALLOW_USER is set and url contains username. */
  410. result = CURLUE_USER_NOT_ALLOWED;
  411. goto out;
  412. }
  413. free(u->user);
  414. u->user = userp;
  415. }
  416. if(passwdp) {
  417. free(u->password);
  418. u->password = passwdp;
  419. }
  420. if(optionsp) {
  421. free(u->options);
  422. u->options = optionsp;
  423. }
  424. /* the host name starts at this offset */
  425. *offset = ptr - login;
  426. return CURLUE_OK;
  427. out:
  428. free(userp);
  429. free(passwdp);
  430. free(optionsp);
  431. u->user = NULL;
  432. u->password = NULL;
  433. u->options = NULL;
  434. return result;
  435. }
  436. UNITTEST CURLUcode Curl_parse_port(struct Curl_URL *u, struct dynbuf *host,
  437. bool has_scheme)
  438. {
  439. char *portptr;
  440. char *hostname = Curl_dyn_ptr(host);
  441. /*
  442. * Find the end of an IPv6 address on the ']' ending bracket.
  443. */
  444. if(hostname[0] == '[') {
  445. portptr = strchr(hostname, ']');
  446. if(!portptr)
  447. return CURLUE_BAD_IPV6;
  448. portptr++;
  449. /* this is a RFC2732-style specified IP-address */
  450. if(*portptr) {
  451. if(*portptr != ':')
  452. return CURLUE_BAD_PORT_NUMBER;
  453. }
  454. else
  455. portptr = NULL;
  456. }
  457. else
  458. portptr = strchr(hostname, ':');
  459. if(portptr) {
  460. char *rest;
  461. long port;
  462. size_t keep = portptr - hostname;
  463. /* Browser behavior adaptation. If there's a colon with no digits after,
  464. just cut off the name there which makes us ignore the colon and just
  465. use the default port. Firefox, Chrome and Safari all do that.
  466. Don't do it if the URL has no scheme, to make something that looks like
  467. a scheme not work!
  468. */
  469. Curl_dyn_setlen(host, keep);
  470. portptr++;
  471. if(!*portptr)
  472. return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER;
  473. if(!ISDIGIT(*portptr))
  474. return CURLUE_BAD_PORT_NUMBER;
  475. port = strtol(portptr, &rest, 10); /* Port number must be decimal */
  476. if(port > 0xffff)
  477. return CURLUE_BAD_PORT_NUMBER;
  478. if(rest[0])
  479. return CURLUE_BAD_PORT_NUMBER;
  480. u->portnum = port;
  481. /* generate a new port number string to get rid of leading zeroes etc */
  482. free(u->port);
  483. u->port = aprintf("%ld", port);
  484. if(!u->port)
  485. return CURLUE_OUT_OF_MEMORY;
  486. }
  487. return CURLUE_OK;
  488. }
  489. /* this assumes 'hostname' now starts with [ */
  490. static CURLUcode ipv6_parse(struct Curl_URL *u, char *hostname,
  491. size_t hlen) /* length of hostname */
  492. {
  493. size_t len;
  494. DEBUGASSERT(*hostname == '[');
  495. if(hlen < 4) /* '[::]' is the shortest possible valid string */
  496. return CURLUE_BAD_IPV6;
  497. hostname++;
  498. hlen -= 2;
  499. /* only valid IPv6 letters are ok */
  500. len = strspn(hostname, "0123456789abcdefABCDEF:.");
  501. if(hlen != len) {
  502. hlen = len;
  503. if(hostname[len] == '%') {
  504. /* this could now be '%[zone id]' */
  505. char zoneid[16];
  506. int i = 0;
  507. char *h = &hostname[len + 1];
  508. /* pass '25' if present and is a url encoded percent sign */
  509. if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']'))
  510. h += 2;
  511. while(*h && (*h != ']') && (i < 15))
  512. zoneid[i++] = *h++;
  513. if(!i || (']' != *h))
  514. return CURLUE_BAD_IPV6;
  515. zoneid[i] = 0;
  516. u->zoneid = strdup(zoneid);
  517. if(!u->zoneid)
  518. return CURLUE_OUT_OF_MEMORY;
  519. hostname[len] = ']'; /* insert end bracket */
  520. hostname[len + 1] = 0; /* terminate the hostname */
  521. }
  522. else
  523. return CURLUE_BAD_IPV6;
  524. /* hostname is fine */
  525. }
  526. /* Check the IPv6 address. */
  527. {
  528. char dest[16]; /* fits a binary IPv6 address */
  529. char norm[MAX_IPADR_LEN];
  530. hostname[hlen] = 0; /* end the address there */
  531. if(1 != Curl_inet_pton(AF_INET6, hostname, dest))
  532. return CURLUE_BAD_IPV6;
  533. /* check if it can be done shorter */
  534. if(Curl_inet_ntop(AF_INET6, dest, norm, sizeof(norm)) &&
  535. (strlen(norm) < hlen)) {
  536. strcpy(hostname, norm);
  537. hlen = strlen(norm);
  538. hostname[hlen + 1] = 0;
  539. }
  540. hostname[hlen] = ']'; /* restore ending bracket */
  541. }
  542. return CURLUE_OK;
  543. }
  544. static CURLUcode hostname_check(struct Curl_URL *u, char *hostname,
  545. size_t hlen) /* length of hostname */
  546. {
  547. size_t len;
  548. DEBUGASSERT(hostname);
  549. if(!hlen)
  550. return CURLUE_NO_HOST;
  551. else if(hostname[0] == '[')
  552. return ipv6_parse(u, hostname, hlen);
  553. else {
  554. /* letters from the second string are not ok */
  555. len = strcspn(hostname, " \r\n\t/:#?!@{}[]\\$\'\"^`*<>=;,+&()%");
  556. if(hlen != len)
  557. /* hostname with bad content */
  558. return CURLUE_BAD_HOSTNAME;
  559. }
  560. return CURLUE_OK;
  561. }
  562. /*
  563. * Handle partial IPv4 numerical addresses and different bases, like
  564. * '16843009', '0x7f', '0x7f.1' '0177.1.1.1' etc.
  565. *
  566. * If the given input string is syntactically wrong IPv4 or any part for
  567. * example is too big, this function returns HOST_NAME.
  568. *
  569. * Output the "normalized" version of that input string in plain quad decimal
  570. * integers.
  571. *
  572. * Returns the host type.
  573. */
  574. #define HOST_ERROR -1 /* out of memory */
  575. #define HOST_BAD -2 /* bad IPv4 address */
  576. #define HOST_NAME 1
  577. #define HOST_IPV4 2
  578. #define HOST_IPV6 3
  579. static int ipv4_normalize(struct dynbuf *host)
  580. {
  581. bool done = FALSE;
  582. int n = 0;
  583. const char *c = Curl_dyn_ptr(host);
  584. unsigned long parts[4] = {0, 0, 0, 0};
  585. CURLcode result = CURLE_OK;
  586. if(*c == '[')
  587. return HOST_IPV6;
  588. while(!done) {
  589. char *endp;
  590. unsigned long l;
  591. if(!ISDIGIT(*c))
  592. /* most importantly this doesn't allow a leading plus or minus */
  593. return HOST_NAME;
  594. l = strtoul(c, &endp, 0);
  595. parts[n] = l;
  596. c = endp;
  597. switch(*c) {
  598. case '.':
  599. if(n == 3)
  600. return HOST_NAME;
  601. n++;
  602. c++;
  603. break;
  604. case '\0':
  605. done = TRUE;
  606. break;
  607. default:
  608. return HOST_NAME;
  609. }
  610. /* overflow */
  611. if((l == ULONG_MAX) && (errno == ERANGE))
  612. return HOST_NAME;
  613. #if SIZEOF_LONG > 4
  614. /* a value larger than 32 bits */
  615. if(l > UINT_MAX)
  616. return HOST_NAME;
  617. #endif
  618. }
  619. switch(n) {
  620. case 0: /* a -- 32 bits */
  621. Curl_dyn_reset(host);
  622. result = Curl_dyn_addf(host, "%u.%u.%u.%u",
  623. parts[0] >> 24, (parts[0] >> 16) & 0xff,
  624. (parts[0] >> 8) & 0xff, parts[0] & 0xff);
  625. break;
  626. case 1: /* a.b -- 8.24 bits */
  627. if((parts[0] > 0xff) || (parts[1] > 0xffffff))
  628. return HOST_NAME;
  629. Curl_dyn_reset(host);
  630. result = Curl_dyn_addf(host, "%u.%u.%u.%u",
  631. parts[0], (parts[1] >> 16) & 0xff,
  632. (parts[1] >> 8) & 0xff, parts[1] & 0xff);
  633. break;
  634. case 2: /* a.b.c -- 8.8.16 bits */
  635. if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff))
  636. return HOST_NAME;
  637. Curl_dyn_reset(host);
  638. result = Curl_dyn_addf(host, "%u.%u.%u.%u",
  639. parts[0], parts[1], (parts[2] >> 8) & 0xff,
  640. parts[2] & 0xff);
  641. break;
  642. case 3: /* a.b.c.d -- 8.8.8.8 bits */
  643. if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) ||
  644. (parts[3] > 0xff))
  645. return HOST_NAME;
  646. Curl_dyn_reset(host);
  647. result = Curl_dyn_addf(host, "%u.%u.%u.%u",
  648. parts[0], parts[1], parts[2], parts[3]);
  649. break;
  650. }
  651. if(result)
  652. return HOST_ERROR;
  653. return HOST_IPV4;
  654. }
  655. /* if necessary, replace the host content with a URL decoded version */
  656. static CURLUcode urldecode_host(struct dynbuf *host)
  657. {
  658. char *per = NULL;
  659. const char *hostname = Curl_dyn_ptr(host);
  660. per = strchr(hostname, '%');
  661. if(!per)
  662. /* nothing to decode */
  663. return CURLUE_OK;
  664. else {
  665. /* encoded */
  666. size_t dlen;
  667. char *decoded;
  668. CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen,
  669. REJECT_CTRL);
  670. if(result)
  671. return CURLUE_BAD_HOSTNAME;
  672. Curl_dyn_reset(host);
  673. result = Curl_dyn_addn(host, decoded, dlen);
  674. free(decoded);
  675. if(result)
  676. return CURLUE_OUT_OF_MEMORY;
  677. }
  678. return CURLUE_OK;
  679. }
  680. static CURLUcode parse_authority(struct Curl_URL *u,
  681. const char *auth, size_t authlen,
  682. unsigned int flags,
  683. struct dynbuf *host,
  684. bool has_scheme)
  685. {
  686. size_t offset;
  687. CURLUcode result;
  688. /*
  689. * Parse the login details and strip them out of the host name.
  690. */
  691. result = parse_hostname_login(u, auth, authlen, flags, &offset);
  692. if(result)
  693. goto out;
  694. if(Curl_dyn_addn(host, auth + offset, authlen - offset)) {
  695. result = CURLUE_OUT_OF_MEMORY;
  696. goto out;
  697. }
  698. result = Curl_parse_port(u, host, has_scheme);
  699. if(result)
  700. goto out;
  701. if(!Curl_dyn_len(host))
  702. return CURLUE_NO_HOST;
  703. switch(ipv4_normalize(host)) {
  704. case HOST_IPV4:
  705. break;
  706. case HOST_IPV6:
  707. result = ipv6_parse(u, Curl_dyn_ptr(host), Curl_dyn_len(host));
  708. break;
  709. case HOST_NAME:
  710. result = urldecode_host(host);
  711. if(!result)
  712. result = hostname_check(u, Curl_dyn_ptr(host), Curl_dyn_len(host));
  713. break;
  714. case HOST_ERROR:
  715. result = CURLUE_OUT_OF_MEMORY;
  716. break;
  717. case HOST_BAD:
  718. default:
  719. result = CURLUE_BAD_HOSTNAME; /* Bad IPv4 address even */
  720. break;
  721. }
  722. out:
  723. return result;
  724. }
  725. CURLUcode Curl_url_set_authority(CURLU *u, const char *authority,
  726. unsigned int flags)
  727. {
  728. CURLUcode result;
  729. struct dynbuf host;
  730. DEBUGASSERT(authority);
  731. Curl_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
  732. result = parse_authority(u, authority, strlen(authority), flags,
  733. &host, !!u->scheme);
  734. if(result)
  735. Curl_dyn_free(&host);
  736. else {
  737. free(u->host);
  738. u->host = Curl_dyn_ptr(&host);
  739. }
  740. return result;
  741. }
  742. /*
  743. * "Remove Dot Segments"
  744. * https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
  745. */
  746. /*
  747. * dedotdotify()
  748. * @unittest: 1395
  749. *
  750. * This function gets a null-terminated path with dot and dotdot sequences
  751. * passed in and strips them off according to the rules in RFC 3986 section
  752. * 5.2.4.
  753. *
  754. * The function handles a query part ('?' + stuff) appended but it expects
  755. * that fragments ('#' + stuff) have already been cut off.
  756. *
  757. * RETURNS
  758. *
  759. * Zero for success and 'out' set to an allocated dedotdotified string.
  760. */
  761. UNITTEST int dedotdotify(const char *input, size_t clen, char **outp);
  762. UNITTEST int dedotdotify(const char *input, size_t clen, char **outp)
  763. {
  764. char *outptr;
  765. const char *endp = &input[clen];
  766. char *out;
  767. *outp = NULL;
  768. /* the path always starts with a slash, and a slash has not dot */
  769. if((clen < 2) || !memchr(input, '.', clen))
  770. return 0;
  771. out = malloc(clen + 1);
  772. if(!out)
  773. return 1; /* out of memory */
  774. *out = 0; /* null-terminates, for inputs like "./" */
  775. outptr = out;
  776. do {
  777. bool dotdot = TRUE;
  778. if(*input == '.') {
  779. /* A. If the input buffer begins with a prefix of "../" or "./", then
  780. remove that prefix from the input buffer; otherwise, */
  781. if(!strncmp("./", input, 2)) {
  782. input += 2;
  783. clen -= 2;
  784. }
  785. else if(!strncmp("../", input, 3)) {
  786. input += 3;
  787. clen -= 3;
  788. }
  789. /* D. if the input buffer consists only of "." or "..", then remove
  790. that from the input buffer; otherwise, */
  791. else if(!strcmp(".", input) || !strcmp("..", input) ||
  792. !strncmp(".?", input, 2) || !strncmp("..?", input, 3)) {
  793. *out = 0;
  794. break;
  795. }
  796. else
  797. dotdot = FALSE;
  798. }
  799. else if(*input == '/') {
  800. /* B. if the input buffer begins with a prefix of "/./" or "/.", where
  801. "." is a complete path segment, then replace that prefix with "/" in
  802. the input buffer; otherwise, */
  803. if(!strncmp("/./", input, 3)) {
  804. input += 2;
  805. clen -= 2;
  806. }
  807. else if(!strcmp("/.", input) || !strncmp("/.?", input, 3)) {
  808. *outptr++ = '/';
  809. *outptr = 0;
  810. break;
  811. }
  812. /* C. if the input buffer begins with a prefix of "/../" or "/..",
  813. where ".." is a complete path segment, then replace that prefix with
  814. "/" in the input buffer and remove the last segment and its
  815. preceding "/" (if any) from the output buffer; otherwise, */
  816. else if(!strncmp("/../", input, 4)) {
  817. input += 3;
  818. clen -= 3;
  819. /* remove the last segment from the output buffer */
  820. while(outptr > out) {
  821. outptr--;
  822. if(*outptr == '/')
  823. break;
  824. }
  825. *outptr = 0; /* null-terminate where it stops */
  826. }
  827. else if(!strcmp("/..", input) || !strncmp("/..?", input, 4)) {
  828. /* remove the last segment from the output buffer */
  829. while(outptr > out) {
  830. outptr--;
  831. if(*outptr == '/')
  832. break;
  833. }
  834. *outptr++ = '/';
  835. *outptr = 0; /* null-terminate where it stops */
  836. break;
  837. }
  838. else
  839. dotdot = FALSE;
  840. }
  841. else
  842. dotdot = FALSE;
  843. if(!dotdot) {
  844. /* E. move the first path segment in the input buffer to the end of
  845. the output buffer, including the initial "/" character (if any) and
  846. any subsequent characters up to, but not including, the next "/"
  847. character or the end of the input buffer. */
  848. do {
  849. *outptr++ = *input++;
  850. clen--;
  851. } while(*input && (*input != '/') && (*input != '?'));
  852. *outptr = 0;
  853. }
  854. /* continue until end of path */
  855. } while(input < endp);
  856. *outp = out;
  857. return 0; /* success */
  858. }
  859. static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
  860. {
  861. const char *path;
  862. size_t pathlen;
  863. char *query = NULL;
  864. char *fragment = NULL;
  865. char schemebuf[MAX_SCHEME_LEN + 1];
  866. size_t schemelen = 0;
  867. size_t urllen;
  868. CURLUcode result = CURLUE_OK;
  869. size_t fraglen = 0;
  870. struct dynbuf host;
  871. DEBUGASSERT(url);
  872. Curl_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
  873. result = junkscan(url, &urllen, flags);
  874. if(result)
  875. goto fail;
  876. schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf),
  877. flags & (CURLU_GUESS_SCHEME|
  878. CURLU_DEFAULT_SCHEME));
  879. /* handle the file: scheme */
  880. if(schemelen && !strcmp(schemebuf, "file")) {
  881. bool uncpath = FALSE;
  882. if(urllen <= 6) {
  883. /* file:/ is not enough to actually be a complete file: URL */
  884. result = CURLUE_BAD_FILE_URL;
  885. goto fail;
  886. }
  887. /* path has been allocated large enough to hold this */
  888. path = (char *)&url[5];
  889. pathlen = urllen - 5;
  890. u->scheme = strdup("file");
  891. if(!u->scheme) {
  892. result = CURLUE_OUT_OF_MEMORY;
  893. goto fail;
  894. }
  895. /* Extra handling URLs with an authority component (i.e. that start with
  896. * "file://")
  897. *
  898. * We allow omitted hostname (e.g. file:/<path>) -- valid according to
  899. * RFC 8089, but not the (current) WHAT-WG URL spec.
  900. */
  901. if(path[0] == '/' && path[1] == '/') {
  902. /* swallow the two slashes */
  903. const char *ptr = &path[2];
  904. /*
  905. * According to RFC 8089, a file: URL can be reliably dereferenced if:
  906. *
  907. * o it has no/blank hostname, or
  908. *
  909. * o the hostname matches "localhost" (case-insensitively), or
  910. *
  911. * o the hostname is a FQDN that resolves to this machine, or
  912. *
  913. * o it is an UNC String transformed to an URI (Windows only, RFC 8089
  914. * Appendix E.3).
  915. *
  916. * For brevity, we only consider URLs with empty, "localhost", or
  917. * "127.0.0.1" hostnames as local, otherwise as an UNC String.
  918. *
  919. * Additionally, there is an exception for URLs with a Windows drive
  920. * letter in the authority (which was accidentally omitted from RFC 8089
  921. * Appendix E, but believe me, it was meant to be there. --MK)
  922. */
  923. if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
  924. /* the URL includes a host name, it must match "localhost" or
  925. "127.0.0.1" to be valid */
  926. if(checkprefix("localhost/", ptr) ||
  927. checkprefix("127.0.0.1/", ptr)) {
  928. ptr += 9; /* now points to the slash after the host */
  929. }
  930. else {
  931. #if defined(WIN32)
  932. size_t len;
  933. /* the host name, NetBIOS computer name, can not contain disallowed
  934. chars, and the delimiting slash character must be appended to the
  935. host name */
  936. path = strpbrk(ptr, "/\\:*?\"<>|");
  937. if(!path || *path != '/') {
  938. result = CURLUE_BAD_FILE_URL;
  939. goto fail;
  940. }
  941. len = path - ptr;
  942. if(len) {
  943. if(Curl_dyn_addn(&host, ptr, len)) {
  944. result = CURLUE_OUT_OF_MEMORY;
  945. goto fail;
  946. }
  947. uncpath = TRUE;
  948. }
  949. ptr -= 2; /* now points to the // before the host in UNC */
  950. #else
  951. /* Invalid file://hostname/, expected localhost or 127.0.0.1 or
  952. none */
  953. result = CURLUE_BAD_FILE_URL;
  954. goto fail;
  955. #endif
  956. }
  957. }
  958. path = ptr;
  959. pathlen = urllen - (ptr - url);
  960. }
  961. if(!uncpath)
  962. /* no host for file: URLs by default */
  963. Curl_dyn_reset(&host);
  964. #if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__)
  965. /* Don't allow Windows drive letters when not in Windows.
  966. * This catches both "file:/c:" and "file:c:" */
  967. if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
  968. STARTS_WITH_URL_DRIVE_PREFIX(path)) {
  969. /* File drive letters are only accepted in MSDOS/Windows */
  970. result = CURLUE_BAD_FILE_URL;
  971. goto fail;
  972. }
  973. #else
  974. /* If the path starts with a slash and a drive letter, ditch the slash */
  975. if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) {
  976. /* This cannot be done with strcpy, as the memory chunks overlap! */
  977. path++;
  978. }
  979. #endif
  980. }
  981. else {
  982. /* clear path */
  983. const char *schemep = NULL;
  984. const char *hostp;
  985. size_t hostlen;
  986. if(schemelen) {
  987. int i = 0;
  988. const char *p = &url[schemelen + 1];
  989. while((*p == '/') && (i < 4)) {
  990. p++;
  991. i++;
  992. }
  993. schemep = schemebuf;
  994. if(!Curl_builtin_scheme(schemep, CURL_ZERO_TERMINATED) &&
  995. !(flags & CURLU_NON_SUPPORT_SCHEME)) {
  996. result = CURLUE_UNSUPPORTED_SCHEME;
  997. goto fail;
  998. }
  999. if((i < 1) || (i > 3)) {
  1000. /* less than one or more than three slashes */
  1001. result = CURLUE_BAD_SLASHES;
  1002. goto fail;
  1003. }
  1004. hostp = p; /* host name starts here */
  1005. }
  1006. else {
  1007. /* no scheme! */
  1008. if(!(flags & (CURLU_DEFAULT_SCHEME|CURLU_GUESS_SCHEME))) {
  1009. result = CURLUE_BAD_SCHEME;
  1010. goto fail;
  1011. }
  1012. if(flags & CURLU_DEFAULT_SCHEME)
  1013. schemep = DEFAULT_SCHEME;
  1014. /*
  1015. * The URL was badly formatted, let's try without scheme specified.
  1016. */
  1017. hostp = url;
  1018. }
  1019. if(schemep) {
  1020. u->scheme = strdup(schemep);
  1021. if(!u->scheme) {
  1022. result = CURLUE_OUT_OF_MEMORY;
  1023. goto fail;
  1024. }
  1025. }
  1026. /* find the end of the host name + port number */
  1027. hostlen = strcspn(hostp, "/?#");
  1028. path = &hostp[hostlen];
  1029. /* this pathlen also contains the query and the fragment */
  1030. pathlen = urllen - (path - url);
  1031. if(hostlen) {
  1032. result = parse_authority(u, hostp, hostlen, flags, &host, schemelen);
  1033. if(result)
  1034. goto fail;
  1035. if((flags & CURLU_GUESS_SCHEME) && !schemep) {
  1036. const char *hostname = Curl_dyn_ptr(&host);
  1037. /* legacy curl-style guess based on host name */
  1038. if(checkprefix("ftp.", hostname))
  1039. schemep = "ftp";
  1040. else if(checkprefix("dict.", hostname))
  1041. schemep = "dict";
  1042. else if(checkprefix("ldap.", hostname))
  1043. schemep = "ldap";
  1044. else if(checkprefix("imap.", hostname))
  1045. schemep = "imap";
  1046. else if(checkprefix("smtp.", hostname))
  1047. schemep = "smtp";
  1048. else if(checkprefix("pop3.", hostname))
  1049. schemep = "pop3";
  1050. else
  1051. schemep = "http";
  1052. u->scheme = strdup(schemep);
  1053. if(!u->scheme) {
  1054. result = CURLUE_OUT_OF_MEMORY;
  1055. goto fail;
  1056. }
  1057. }
  1058. }
  1059. else if(flags & CURLU_NO_AUTHORITY) {
  1060. /* allowed to be empty. */
  1061. if(Curl_dyn_add(&host, "")) {
  1062. result = CURLUE_OUT_OF_MEMORY;
  1063. goto fail;
  1064. }
  1065. }
  1066. else {
  1067. result = CURLUE_NO_HOST;
  1068. goto fail;
  1069. }
  1070. }
  1071. fragment = strchr(path, '#');
  1072. if(fragment) {
  1073. fraglen = pathlen - (fragment - path);
  1074. if(fraglen > 1) {
  1075. /* skip the leading '#' in the copy but include the terminating null */
  1076. if(flags & CURLU_URLENCODE) {
  1077. struct dynbuf enc;
  1078. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1079. if(urlencode_str(&enc, fragment + 1, fraglen, TRUE, FALSE)) {
  1080. result = CURLUE_OUT_OF_MEMORY;
  1081. goto fail;
  1082. }
  1083. u->fragment = Curl_dyn_ptr(&enc);
  1084. }
  1085. else {
  1086. u->fragment = Curl_memdup(fragment + 1, fraglen);
  1087. if(!u->fragment) {
  1088. result = CURLUE_OUT_OF_MEMORY;
  1089. goto fail;
  1090. }
  1091. }
  1092. }
  1093. /* after this, pathlen still contains the query */
  1094. pathlen -= fraglen;
  1095. }
  1096. DEBUGASSERT(pathlen < urllen);
  1097. query = memchr(path, '?', pathlen);
  1098. if(query) {
  1099. size_t qlen = fragment ? (size_t)(fragment - query) :
  1100. pathlen - (query - path);
  1101. pathlen -= qlen;
  1102. if(qlen > 1) {
  1103. if(flags & CURLU_URLENCODE) {
  1104. struct dynbuf enc;
  1105. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1106. /* skip the leading question mark */
  1107. if(urlencode_str(&enc, query + 1, qlen - 1, TRUE, TRUE)) {
  1108. result = CURLUE_OUT_OF_MEMORY;
  1109. goto fail;
  1110. }
  1111. u->query = Curl_dyn_ptr(&enc);
  1112. }
  1113. else {
  1114. u->query = Curl_memdup(query + 1, qlen);
  1115. if(!u->query) {
  1116. result = CURLUE_OUT_OF_MEMORY;
  1117. goto fail;
  1118. }
  1119. u->query[qlen - 1] = 0;
  1120. }
  1121. }
  1122. else {
  1123. /* single byte query */
  1124. u->query = strdup("");
  1125. if(!u->query) {
  1126. result = CURLUE_OUT_OF_MEMORY;
  1127. goto fail;
  1128. }
  1129. }
  1130. }
  1131. if(pathlen && (flags & CURLU_URLENCODE)) {
  1132. struct dynbuf enc;
  1133. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1134. if(urlencode_str(&enc, path, pathlen, TRUE, FALSE)) {
  1135. result = CURLUE_OUT_OF_MEMORY;
  1136. goto fail;
  1137. }
  1138. pathlen = Curl_dyn_len(&enc);
  1139. path = u->path = Curl_dyn_ptr(&enc);
  1140. }
  1141. if(pathlen <= 1) {
  1142. /* there is no path left or just the slash, unset */
  1143. path = NULL;
  1144. }
  1145. else {
  1146. if(!u->path) {
  1147. u->path = Curl_memdup(path, pathlen + 1);
  1148. if(!u->path) {
  1149. result = CURLUE_OUT_OF_MEMORY;
  1150. goto fail;
  1151. }
  1152. u->path[pathlen] = 0;
  1153. path = u->path;
  1154. }
  1155. else if(flags & CURLU_URLENCODE)
  1156. /* it might have encoded more than just the path so cut it */
  1157. u->path[pathlen] = 0;
  1158. if(!(flags & CURLU_PATH_AS_IS)) {
  1159. /* remove ../ and ./ sequences according to RFC3986 */
  1160. char *dedot;
  1161. int err = dedotdotify((char *)path, pathlen, &dedot);
  1162. if(err) {
  1163. result = CURLUE_OUT_OF_MEMORY;
  1164. goto fail;
  1165. }
  1166. if(dedot) {
  1167. free(u->path);
  1168. u->path = dedot;
  1169. }
  1170. }
  1171. }
  1172. u->host = Curl_dyn_ptr(&host);
  1173. return result;
  1174. fail:
  1175. Curl_dyn_free(&host);
  1176. free_urlhandle(u);
  1177. return result;
  1178. }
  1179. /*
  1180. * Parse the URL and, if successful, replace everything in the Curl_URL struct.
  1181. */
  1182. static CURLUcode parseurl_and_replace(const char *url, CURLU *u,
  1183. unsigned int flags)
  1184. {
  1185. CURLUcode result;
  1186. CURLU tmpurl;
  1187. memset(&tmpurl, 0, sizeof(tmpurl));
  1188. result = parseurl(url, &tmpurl, flags);
  1189. if(!result) {
  1190. free_urlhandle(u);
  1191. *u = tmpurl;
  1192. }
  1193. return result;
  1194. }
  1195. /*
  1196. */
  1197. CURLU *curl_url(void)
  1198. {
  1199. return calloc(sizeof(struct Curl_URL), 1);
  1200. }
  1201. void curl_url_cleanup(CURLU *u)
  1202. {
  1203. if(u) {
  1204. free_urlhandle(u);
  1205. free(u);
  1206. }
  1207. }
  1208. #define DUP(dest, src, name) \
  1209. do { \
  1210. if(src->name) { \
  1211. dest->name = strdup(src->name); \
  1212. if(!dest->name) \
  1213. goto fail; \
  1214. } \
  1215. } while(0)
  1216. CURLU *curl_url_dup(const CURLU *in)
  1217. {
  1218. struct Curl_URL *u = calloc(sizeof(struct Curl_URL), 1);
  1219. if(u) {
  1220. DUP(u, in, scheme);
  1221. DUP(u, in, user);
  1222. DUP(u, in, password);
  1223. DUP(u, in, options);
  1224. DUP(u, in, host);
  1225. DUP(u, in, port);
  1226. DUP(u, in, path);
  1227. DUP(u, in, query);
  1228. DUP(u, in, fragment);
  1229. u->portnum = in->portnum;
  1230. }
  1231. return u;
  1232. fail:
  1233. curl_url_cleanup(u);
  1234. return NULL;
  1235. }
  1236. CURLUcode curl_url_get(const CURLU *u, CURLUPart what,
  1237. char **part, unsigned int flags)
  1238. {
  1239. const char *ptr;
  1240. CURLUcode ifmissing = CURLUE_UNKNOWN_PART;
  1241. char portbuf[7];
  1242. bool urldecode = (flags & CURLU_URLDECODE)?1:0;
  1243. bool urlencode = (flags & CURLU_URLENCODE)?1:0;
  1244. bool punycode = FALSE;
  1245. bool plusdecode = FALSE;
  1246. (void)flags;
  1247. if(!u)
  1248. return CURLUE_BAD_HANDLE;
  1249. if(!part)
  1250. return CURLUE_BAD_PARTPOINTER;
  1251. *part = NULL;
  1252. switch(what) {
  1253. case CURLUPART_SCHEME:
  1254. ptr = u->scheme;
  1255. ifmissing = CURLUE_NO_SCHEME;
  1256. urldecode = FALSE; /* never for schemes */
  1257. break;
  1258. case CURLUPART_USER:
  1259. ptr = u->user;
  1260. ifmissing = CURLUE_NO_USER;
  1261. break;
  1262. case CURLUPART_PASSWORD:
  1263. ptr = u->password;
  1264. ifmissing = CURLUE_NO_PASSWORD;
  1265. break;
  1266. case CURLUPART_OPTIONS:
  1267. ptr = u->options;
  1268. ifmissing = CURLUE_NO_OPTIONS;
  1269. break;
  1270. case CURLUPART_HOST:
  1271. ptr = u->host;
  1272. ifmissing = CURLUE_NO_HOST;
  1273. punycode = (flags & CURLU_PUNYCODE)?1:0;
  1274. break;
  1275. case CURLUPART_ZONEID:
  1276. ptr = u->zoneid;
  1277. ifmissing = CURLUE_NO_ZONEID;
  1278. break;
  1279. case CURLUPART_PORT:
  1280. ptr = u->port;
  1281. ifmissing = CURLUE_NO_PORT;
  1282. urldecode = FALSE; /* never for port */
  1283. if(!ptr && (flags & CURLU_DEFAULT_PORT) && u->scheme) {
  1284. /* there's no stored port number, but asked to deliver
  1285. a default one for the scheme */
  1286. const struct Curl_handler *h =
  1287. Curl_builtin_scheme(u->scheme, CURL_ZERO_TERMINATED);
  1288. if(h) {
  1289. msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
  1290. ptr = portbuf;
  1291. }
  1292. }
  1293. else if(ptr && u->scheme) {
  1294. /* there is a stored port number, but ask to inhibit if
  1295. it matches the default one for the scheme */
  1296. const struct Curl_handler *h =
  1297. Curl_builtin_scheme(u->scheme, CURL_ZERO_TERMINATED);
  1298. if(h && (h->defport == u->portnum) &&
  1299. (flags & CURLU_NO_DEFAULT_PORT))
  1300. ptr = NULL;
  1301. }
  1302. break;
  1303. case CURLUPART_PATH:
  1304. ptr = u->path;
  1305. if(!ptr)
  1306. ptr = "/";
  1307. break;
  1308. case CURLUPART_QUERY:
  1309. ptr = u->query;
  1310. ifmissing = CURLUE_NO_QUERY;
  1311. plusdecode = urldecode;
  1312. break;
  1313. case CURLUPART_FRAGMENT:
  1314. ptr = u->fragment;
  1315. ifmissing = CURLUE_NO_FRAGMENT;
  1316. break;
  1317. case CURLUPART_URL: {
  1318. char *url;
  1319. char *scheme;
  1320. char *options = u->options;
  1321. char *port = u->port;
  1322. char *allochost = NULL;
  1323. punycode = (flags & CURLU_PUNYCODE)?1:0;
  1324. if(u->scheme && strcasecompare("file", u->scheme)) {
  1325. url = aprintf("file://%s%s%s",
  1326. u->path,
  1327. u->fragment? "#": "",
  1328. u->fragment? u->fragment : "");
  1329. }
  1330. else if(!u->host)
  1331. return CURLUE_NO_HOST;
  1332. else {
  1333. const struct Curl_handler *h = NULL;
  1334. if(u->scheme)
  1335. scheme = u->scheme;
  1336. else if(flags & CURLU_DEFAULT_SCHEME)
  1337. scheme = (char *) DEFAULT_SCHEME;
  1338. else
  1339. return CURLUE_NO_SCHEME;
  1340. h = Curl_builtin_scheme(scheme, CURL_ZERO_TERMINATED);
  1341. if(!port && (flags & CURLU_DEFAULT_PORT)) {
  1342. /* there's no stored port number, but asked to deliver
  1343. a default one for the scheme */
  1344. if(h) {
  1345. msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
  1346. port = portbuf;
  1347. }
  1348. }
  1349. else if(port) {
  1350. /* there is a stored port number, but asked to inhibit if it matches
  1351. the default one for the scheme */
  1352. if(h && (h->defport == u->portnum) &&
  1353. (flags & CURLU_NO_DEFAULT_PORT))
  1354. port = NULL;
  1355. }
  1356. if(h && !(h->flags & PROTOPT_URLOPTIONS))
  1357. options = NULL;
  1358. if(u->host[0] == '[') {
  1359. if(u->zoneid) {
  1360. /* make it '[ host %25 zoneid ]' */
  1361. struct dynbuf enc;
  1362. size_t hostlen = strlen(u->host);
  1363. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1364. if(Curl_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host,
  1365. u->zoneid))
  1366. return CURLUE_OUT_OF_MEMORY;
  1367. allochost = Curl_dyn_ptr(&enc);
  1368. }
  1369. }
  1370. else if(urlencode) {
  1371. allochost = curl_easy_escape(NULL, u->host, 0);
  1372. if(!allochost)
  1373. return CURLUE_OUT_OF_MEMORY;
  1374. }
  1375. else if(punycode) {
  1376. if(!Curl_is_ASCII_name(u->host)) {
  1377. #ifndef USE_IDN
  1378. return CURLUE_LACKS_IDN;
  1379. #else
  1380. allochost = Curl_idn_decode(u->host);
  1381. if(!allochost)
  1382. return CURLUE_OUT_OF_MEMORY;
  1383. #endif
  1384. }
  1385. }
  1386. url = aprintf("%s://%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
  1387. scheme,
  1388. u->user ? u->user : "",
  1389. u->password ? ":": "",
  1390. u->password ? u->password : "",
  1391. options ? ";" : "",
  1392. options ? options : "",
  1393. (u->user || u->password || options) ? "@": "",
  1394. allochost ? allochost : u->host,
  1395. port ? ":": "",
  1396. port ? port : "",
  1397. u->path ? u->path : "/",
  1398. (u->query && u->query[0]) ? "?": "",
  1399. (u->query && u->query[0]) ? u->query : "",
  1400. u->fragment? "#": "",
  1401. u->fragment? u->fragment : "");
  1402. free(allochost);
  1403. }
  1404. if(!url)
  1405. return CURLUE_OUT_OF_MEMORY;
  1406. *part = url;
  1407. return CURLUE_OK;
  1408. }
  1409. default:
  1410. ptr = NULL;
  1411. break;
  1412. }
  1413. if(ptr) {
  1414. size_t partlen = strlen(ptr);
  1415. size_t i = 0;
  1416. *part = Curl_memdup(ptr, partlen + 1);
  1417. if(!*part)
  1418. return CURLUE_OUT_OF_MEMORY;
  1419. if(plusdecode) {
  1420. /* convert + to space */
  1421. char *plus = *part;
  1422. for(i = 0; i < partlen; ++plus, i++) {
  1423. if(*plus == '+')
  1424. *plus = ' ';
  1425. }
  1426. }
  1427. if(urldecode) {
  1428. char *decoded;
  1429. size_t dlen;
  1430. /* this unconditional rejection of control bytes is documented
  1431. API behavior */
  1432. CURLcode res = Curl_urldecode(*part, 0, &decoded, &dlen, REJECT_CTRL);
  1433. free(*part);
  1434. if(res) {
  1435. *part = NULL;
  1436. return CURLUE_URLDECODE;
  1437. }
  1438. *part = decoded;
  1439. partlen = dlen;
  1440. }
  1441. if(urlencode) {
  1442. struct dynbuf enc;
  1443. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1444. if(urlencode_str(&enc, *part, partlen, TRUE,
  1445. what == CURLUPART_QUERY))
  1446. return CURLUE_OUT_OF_MEMORY;
  1447. free(*part);
  1448. *part = Curl_dyn_ptr(&enc);
  1449. }
  1450. else if(punycode) {
  1451. if(!Curl_is_ASCII_name(u->host)) {
  1452. #ifndef USE_IDN
  1453. return CURLUE_LACKS_IDN;
  1454. #else
  1455. char *allochost = Curl_idn_decode(*part);
  1456. if(!allochost)
  1457. return CURLUE_OUT_OF_MEMORY;
  1458. free(*part);
  1459. *part = allochost;
  1460. #endif
  1461. }
  1462. }
  1463. return CURLUE_OK;
  1464. }
  1465. else
  1466. return ifmissing;
  1467. }
  1468. CURLUcode curl_url_set(CURLU *u, CURLUPart what,
  1469. const char *part, unsigned int flags)
  1470. {
  1471. char **storep = NULL;
  1472. long port = 0;
  1473. bool urlencode = (flags & CURLU_URLENCODE)? 1 : 0;
  1474. bool plusencode = FALSE;
  1475. bool urlskipslash = FALSE;
  1476. bool leadingslash = FALSE;
  1477. bool appendquery = FALSE;
  1478. bool equalsencode = FALSE;
  1479. size_t nalloc;
  1480. if(!u)
  1481. return CURLUE_BAD_HANDLE;
  1482. if(!part) {
  1483. /* setting a part to NULL clears it */
  1484. switch(what) {
  1485. case CURLUPART_URL:
  1486. break;
  1487. case CURLUPART_SCHEME:
  1488. storep = &u->scheme;
  1489. break;
  1490. case CURLUPART_USER:
  1491. storep = &u->user;
  1492. break;
  1493. case CURLUPART_PASSWORD:
  1494. storep = &u->password;
  1495. break;
  1496. case CURLUPART_OPTIONS:
  1497. storep = &u->options;
  1498. break;
  1499. case CURLUPART_HOST:
  1500. storep = &u->host;
  1501. break;
  1502. case CURLUPART_ZONEID:
  1503. storep = &u->zoneid;
  1504. break;
  1505. case CURLUPART_PORT:
  1506. u->portnum = 0;
  1507. storep = &u->port;
  1508. break;
  1509. case CURLUPART_PATH:
  1510. storep = &u->path;
  1511. break;
  1512. case CURLUPART_QUERY:
  1513. storep = &u->query;
  1514. break;
  1515. case CURLUPART_FRAGMENT:
  1516. storep = &u->fragment;
  1517. break;
  1518. default:
  1519. return CURLUE_UNKNOWN_PART;
  1520. }
  1521. if(storep && *storep) {
  1522. Curl_safefree(*storep);
  1523. }
  1524. else if(!storep) {
  1525. free_urlhandle(u);
  1526. memset(u, 0, sizeof(struct Curl_URL));
  1527. }
  1528. return CURLUE_OK;
  1529. }
  1530. nalloc = strlen(part);
  1531. if(nalloc > CURL_MAX_INPUT_LENGTH)
  1532. /* excessive input length */
  1533. return CURLUE_MALFORMED_INPUT;
  1534. switch(what) {
  1535. case CURLUPART_SCHEME: {
  1536. size_t plen = strlen(part);
  1537. const char *s = part;
  1538. if((plen > MAX_SCHEME_LEN) || (plen < 1))
  1539. /* too long or too short */
  1540. return CURLUE_BAD_SCHEME;
  1541. if(!(flags & CURLU_NON_SUPPORT_SCHEME) &&
  1542. /* verify that it is a fine scheme */
  1543. !Curl_builtin_scheme(part, CURL_ZERO_TERMINATED))
  1544. return CURLUE_UNSUPPORTED_SCHEME;
  1545. storep = &u->scheme;
  1546. urlencode = FALSE; /* never */
  1547. if(ISALPHA(*s)) {
  1548. /* ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
  1549. while(--plen) {
  1550. if(ISALNUM(*s) || (*s == '+') || (*s == '-') || (*s == '.'))
  1551. s++; /* fine */
  1552. else
  1553. return CURLUE_BAD_SCHEME;
  1554. }
  1555. }
  1556. else
  1557. return CURLUE_BAD_SCHEME;
  1558. break;
  1559. }
  1560. case CURLUPART_USER:
  1561. storep = &u->user;
  1562. break;
  1563. case CURLUPART_PASSWORD:
  1564. storep = &u->password;
  1565. break;
  1566. case CURLUPART_OPTIONS:
  1567. storep = &u->options;
  1568. break;
  1569. case CURLUPART_HOST:
  1570. storep = &u->host;
  1571. Curl_safefree(u->zoneid);
  1572. break;
  1573. case CURLUPART_ZONEID:
  1574. storep = &u->zoneid;
  1575. break;
  1576. case CURLUPART_PORT:
  1577. {
  1578. char *endp;
  1579. urlencode = FALSE; /* never */
  1580. port = strtol(part, &endp, 10); /* Port number must be decimal */
  1581. if((port <= 0) || (port > 0xffff))
  1582. return CURLUE_BAD_PORT_NUMBER;
  1583. if(*endp)
  1584. /* weirdly provided number, not good! */
  1585. return CURLUE_BAD_PORT_NUMBER;
  1586. storep = &u->port;
  1587. }
  1588. break;
  1589. case CURLUPART_PATH:
  1590. urlskipslash = TRUE;
  1591. leadingslash = TRUE; /* enforce */
  1592. storep = &u->path;
  1593. break;
  1594. case CURLUPART_QUERY:
  1595. plusencode = urlencode;
  1596. appendquery = (flags & CURLU_APPENDQUERY)?1:0;
  1597. equalsencode = appendquery;
  1598. storep = &u->query;
  1599. break;
  1600. case CURLUPART_FRAGMENT:
  1601. storep = &u->fragment;
  1602. break;
  1603. case CURLUPART_URL: {
  1604. /*
  1605. * Allow a new URL to replace the existing (if any) contents.
  1606. *
  1607. * If the existing contents is enough for a URL, allow a relative URL to
  1608. * replace it.
  1609. */
  1610. CURLUcode result;
  1611. char *oldurl;
  1612. char *redired_url;
  1613. /* if the new thing is absolute or the old one is not
  1614. * (we could not get an absolute url in 'oldurl'),
  1615. * then replace the existing with the new. */
  1616. if(Curl_is_absolute_url(part, NULL, 0,
  1617. flags & (CURLU_GUESS_SCHEME|
  1618. CURLU_DEFAULT_SCHEME))
  1619. || curl_url_get(u, CURLUPART_URL, &oldurl, flags)) {
  1620. return parseurl_and_replace(part, u, flags);
  1621. }
  1622. /* apply the relative part to create a new URL
  1623. * and replace the existing one with it. */
  1624. redired_url = concat_url(oldurl, part);
  1625. free(oldurl);
  1626. if(!redired_url)
  1627. return CURLUE_OUT_OF_MEMORY;
  1628. result = parseurl_and_replace(redired_url, u, flags);
  1629. free(redired_url);
  1630. return result;
  1631. }
  1632. default:
  1633. return CURLUE_UNKNOWN_PART;
  1634. }
  1635. DEBUGASSERT(storep);
  1636. {
  1637. const char *newp;
  1638. struct dynbuf enc;
  1639. Curl_dyn_init(&enc, nalloc * 3 + 1 + leadingslash);
  1640. if(leadingslash && (part[0] != '/')) {
  1641. CURLcode result = Curl_dyn_addn(&enc, "/", 1);
  1642. if(result)
  1643. return CURLUE_OUT_OF_MEMORY;
  1644. }
  1645. if(urlencode) {
  1646. const unsigned char *i;
  1647. for(i = (const unsigned char *)part; *i; i++) {
  1648. CURLcode result;
  1649. if((*i == ' ') && plusencode) {
  1650. result = Curl_dyn_addn(&enc, "+", 1);
  1651. if(result)
  1652. return CURLUE_OUT_OF_MEMORY;
  1653. }
  1654. else if(Curl_isunreserved(*i) ||
  1655. ((*i == '/') && urlskipslash) ||
  1656. ((*i == '=') && equalsencode)) {
  1657. if((*i == '=') && equalsencode)
  1658. /* only skip the first equals sign */
  1659. equalsencode = FALSE;
  1660. result = Curl_dyn_addn(&enc, i, 1);
  1661. if(result)
  1662. return CURLUE_OUT_OF_MEMORY;
  1663. }
  1664. else {
  1665. char out[3]={'%'};
  1666. out[1] = hexdigits[*i>>4];
  1667. out[2] = hexdigits[*i & 0xf];
  1668. result = Curl_dyn_addn(&enc, out, 3);
  1669. if(result)
  1670. return CURLUE_OUT_OF_MEMORY;
  1671. }
  1672. }
  1673. }
  1674. else {
  1675. char *p;
  1676. CURLcode result = Curl_dyn_add(&enc, part);
  1677. if(result)
  1678. return CURLUE_OUT_OF_MEMORY;
  1679. p = Curl_dyn_ptr(&enc);
  1680. while(*p) {
  1681. /* make sure percent encoded are lower case */
  1682. if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) &&
  1683. (ISUPPER(p[1]) || ISUPPER(p[2]))) {
  1684. p[1] = Curl_raw_tolower(p[1]);
  1685. p[2] = Curl_raw_tolower(p[2]);
  1686. p += 3;
  1687. }
  1688. else
  1689. p++;
  1690. }
  1691. }
  1692. newp = Curl_dyn_ptr(&enc);
  1693. if(appendquery) {
  1694. /* Append the 'newp' string onto the old query. Add a '&' separator if
  1695. none is present at the end of the existing query already */
  1696. size_t querylen = u->query ? strlen(u->query) : 0;
  1697. bool addamperand = querylen && (u->query[querylen -1] != '&');
  1698. if(querylen) {
  1699. struct dynbuf qbuf;
  1700. Curl_dyn_init(&qbuf, CURL_MAX_INPUT_LENGTH);
  1701. if(Curl_dyn_addn(&qbuf, u->query, querylen)) /* add original query */
  1702. goto nomem;
  1703. if(addamperand) {
  1704. if(Curl_dyn_addn(&qbuf, "&", 1))
  1705. goto nomem;
  1706. }
  1707. if(Curl_dyn_add(&qbuf, newp))
  1708. goto nomem;
  1709. Curl_dyn_free(&enc);
  1710. free(*storep);
  1711. *storep = Curl_dyn_ptr(&qbuf);
  1712. return CURLUE_OK;
  1713. nomem:
  1714. Curl_dyn_free(&enc);
  1715. return CURLUE_OUT_OF_MEMORY;
  1716. }
  1717. }
  1718. if(what == CURLUPART_HOST) {
  1719. size_t n = strlen(newp);
  1720. if(!n && (flags & CURLU_NO_AUTHORITY)) {
  1721. /* Skip hostname check, it's allowed to be empty. */
  1722. }
  1723. else {
  1724. if(!n || hostname_check(u, (char *)newp, n)) {
  1725. Curl_dyn_free(&enc);
  1726. return CURLUE_BAD_HOSTNAME;
  1727. }
  1728. }
  1729. }
  1730. free(*storep);
  1731. *storep = (char *)newp;
  1732. }
  1733. /* set after the string, to make it not assigned if the allocation above
  1734. fails */
  1735. if(port)
  1736. u->portnum = port;
  1737. return CURLUE_OK;
  1738. }