urlapi.c 49 KB

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