2
0

urlapi.c 50 KB

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