urlapi.c 44 KB

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