ssl.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. /*
  2. * OpenConnect (SSL + DTLS) VPN client
  3. *
  4. * Copyright © 2008-2015 Intel Corporation.
  5. *
  6. * Author: David Woodhouse <dwmw2@infradead.org>
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public License
  10. * version 2.1, as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. */
  17. #include <config.h>
  18. #include "openconnect-internal.h"
  19. #include <unistd.h>
  20. #include <sys/types.h>
  21. #include <sys/stat.h>
  22. #include <inttypes.h>
  23. #include <fcntl.h>
  24. #if defined(__linux__) || defined(__ANDROID__)
  25. #include <sys/vfs.h>
  26. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__APPLE__)
  27. #include <sys/param.h>
  28. #include <sys/mount.h>
  29. #elif defined(__sun__) || defined(__NetBSD__) || defined(__DragonFly__)
  30. #include <sys/statvfs.h>
  31. #elif defined(__GNU__)
  32. #include <sys/statfs.h>
  33. #endif
  34. /* setsockopt and TCP_NODELAY */
  35. #ifndef _WIN32
  36. #include <netinet/tcp.h>
  37. #include <sys/socket.h>
  38. #endif
  39. #ifdef ANDROID_KEYSTORE
  40. #include <sys/un.h>
  41. #endif
  42. #include <string.h>
  43. #include <stdio.h>
  44. #include <errno.h>
  45. #include <stdlib.h>
  46. #include <stdarg.h>
  47. #include <time.h>
  48. /* OSX < 1.6 doesn't have AI_NUMERICSERV */
  49. #ifndef AI_NUMERICSERV
  50. #define AI_NUMERICSERV 0
  51. #endif
  52. /* GNU Hurd doesn't yet declare IPV6_TCLASS */
  53. #ifndef IPV6_TCLASS
  54. #if defined(__GNU__)
  55. #define IPV6_TCLASS 61
  56. #elif defined(__APPLE__)
  57. #define IPV6_TCLASS 36
  58. #endif
  59. #endif
  60. static inline int connect_pending(void)
  61. {
  62. #ifdef _WIN32
  63. return WSAGetLastError() == WSAEWOULDBLOCK;
  64. #else
  65. return errno == EINPROGRESS;
  66. #endif
  67. }
  68. /* Windows is interminably horrid, and has disjoint errno spaces.
  69. * So if we return a positive value, that's a WSA Error and should
  70. * be handled with openconnect__win32_strerror(). But if we return a
  71. * negative value, that's a normal errno and should be handled with
  72. * strerror(). No, you can't just pass the latter value (negated) to
  73. * openconnect__win32_strerror() because it gives nonsense results. */
  74. static int cancellable_connect(struct openconnect_info *vpninfo, int sockfd,
  75. const struct sockaddr *addr, socklen_t addrlen)
  76. {
  77. struct sockaddr_storage peer;
  78. socklen_t peerlen = sizeof(peer);
  79. fd_set wr_set, rd_set, ex_set;
  80. int maxfd = sockfd;
  81. int err;
  82. if (set_sock_nonblock(sockfd))
  83. goto sockerr;
  84. if (vpninfo->protect_socket)
  85. vpninfo->protect_socket(vpninfo->cbdata, sockfd);
  86. if (connect(sockfd, addr, addrlen) < 0 && !connect_pending()) {
  87. sockerr:
  88. #ifdef _WIN32
  89. return WSAGetLastError();
  90. #else
  91. return -errno;
  92. #endif
  93. }
  94. do {
  95. FD_ZERO(&wr_set);
  96. FD_ZERO(&rd_set);
  97. FD_ZERO(&ex_set);
  98. FD_SET(sockfd, &wr_set);
  99. #ifdef _WIN32 /* Windows indicates failure this way, not in wr_set */
  100. FD_SET(sockfd, &ex_set);
  101. #endif
  102. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  103. if (select(maxfd + 1, &rd_set, &wr_set, &ex_set, NULL) < 0 &&
  104. errno != EINTR) {
  105. vpn_perror(vpninfo, _("Failed select() for socket connect"));
  106. return -EIO;
  107. }
  108. if (is_cancel_pending(vpninfo, &rd_set)) {
  109. vpn_progress(vpninfo, PRG_ERR, _("Socket connect cancelled\n"));
  110. return -EINTR;
  111. }
  112. } while (!FD_ISSET(sockfd, &wr_set) && !FD_ISSET(sockfd, &ex_set) &&
  113. !vpninfo->got_pause_cmd);
  114. /* Check whether connect() succeeded or failed by using
  115. getpeername(). See https://cr.yp.to/docs/connect.html */
  116. if (!getpeername(sockfd, (void *)&peer, &peerlen))
  117. return 0;
  118. #ifdef _WIN32 /* On Windows, use getsockopt() to determine the error.
  119. * We don't ddo this on Windows because it just reports
  120. * -ENOTCONN, which we already knew. */
  121. err = WSAGetLastError();
  122. if (err == WSAENOTCONN) {
  123. socklen_t errlen = sizeof(err);
  124. getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
  125. (void *)&err, &errlen);
  126. }
  127. #else
  128. err = -errno;
  129. if (err == -ENOTCONN) {
  130. char ch;
  131. if (read(sockfd, &ch, 1) < 0)
  132. err = -errno;
  133. /* It should *always* fail! */
  134. }
  135. #endif
  136. return err;
  137. }
  138. static inline int accept_pending(void)
  139. {
  140. #ifdef _WIN32
  141. return WSAGetLastError() == WSAEWOULDBLOCK;
  142. #else
  143. return errno == EAGAIN || errno == EWOULDBLOCK;
  144. #endif
  145. }
  146. int cancellable_accept(struct openconnect_info *vpninfo, int sockfd)
  147. {
  148. fd_set wr_set, rd_set, ex_set;
  149. int accept_fd, maxfd = sockfd;
  150. char *errstr;
  151. do {
  152. accept_fd = accept(sockfd, NULL, NULL);
  153. if (accept_fd >= 0)
  154. return accept_fd;
  155. if (!accept_pending())
  156. break;
  157. FD_ZERO(&wr_set);
  158. FD_ZERO(&rd_set);
  159. FD_ZERO(&ex_set);
  160. FD_SET(sockfd, &rd_set);
  161. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  162. if (select(maxfd + 1, &rd_set, &wr_set, &ex_set, NULL) < 0 &&
  163. errno != EINTR) {
  164. vpn_perror(vpninfo, _("Failed select() for socket accept"));
  165. return -EIO;
  166. }
  167. if (is_cancel_pending(vpninfo, &rd_set)) {
  168. vpn_progress(vpninfo, PRG_ERR, _("Socket accept cancelled\n"));
  169. return -EINTR;
  170. }
  171. } while (!FD_ISSET(sockfd, &ex_set) && !vpninfo->got_pause_cmd);
  172. #ifdef _WIN32
  173. errstr = openconnect__win32_strerror(WSAGetLastError());
  174. #else
  175. errstr = strerror(errno);
  176. #endif
  177. vpn_progress(vpninfo, PRG_ERR,
  178. _("Failed to accept local connection: %s\n"),
  179. errstr);
  180. #ifdef _WIN32
  181. free(errstr);
  182. #endif
  183. return -1;
  184. }
  185. /* checks whether the provided string is an IP or a hostname.
  186. */
  187. unsigned string_is_hostname(const char *str)
  188. {
  189. struct in_addr buf;
  190. /* We don't use inet_pton() because an IPv6 literal is likely to
  191. be encased in []. So just check for a colon, which shouldn't
  192. occur in hostnames anyway. */
  193. if (!str || inet_aton(str, &buf) || strchr(str, ':'))
  194. return 0;
  195. return 1;
  196. }
  197. static int match_sockaddr(struct sockaddr *a, struct sockaddr *b)
  198. {
  199. if (a->sa_family == AF_INET) {
  200. struct sockaddr_in *a4 = (void *)a;
  201. struct sockaddr_in *b4 = (void *)b;
  202. return (a4->sin_addr.s_addr == b4->sin_addr.s_addr) &&
  203. (a4->sin_port == b4->sin_port);
  204. } else if (a->sa_family == AF_INET6) {
  205. struct sockaddr_in6 *a6 = (void *)a;
  206. struct sockaddr_in6 *b6 = (void *)b;
  207. return !memcmp(&a6->sin6_addr, &b6->sin6_addr, sizeof(a6->sin6_addr)) &&
  208. a6->sin6_port == b6->sin6_port;
  209. } else
  210. return 0;
  211. }
  212. static int set_tcp_nodelay(struct openconnect_info *vpninfo, int ssl_sock)
  213. {
  214. int flag = 1;
  215. if (setsockopt(ssl_sock, IPPROTO_TCP, TCP_NODELAY, (void *)(&flag), sizeof(flag)) < 0) {;
  216. vpn_perror(vpninfo,
  217. _("Failed setsockopt(TCP_NODELAY) on TLS socket:"));
  218. #ifdef _WIN32
  219. return WSAGetLastError();
  220. #else
  221. return -errno;
  222. #endif
  223. }
  224. return 0;
  225. }
  226. int connect_https_socket(struct openconnect_info *vpninfo)
  227. {
  228. int ssl_sock = -1;
  229. int err;
  230. /* If we're talking to a server which told us it has dynamic DNS, don't
  231. just re-use its previous IP address. If we're talking to a proxy, we
  232. can use *its* previous IP address. We expect it'll re-do the DNS
  233. lookup for the server anyway. */
  234. if (vpninfo->peer_addr && (!vpninfo->is_dyndns || vpninfo->proxy)) {
  235. reconnect:
  236. #ifdef SOCK_CLOEXEC
  237. ssl_sock = socket(vpninfo->peer_addr->sa_family, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_IP);
  238. if (ssl_sock < 0)
  239. #endif
  240. {
  241. ssl_sock = socket(vpninfo->peer_addr->sa_family, SOCK_STREAM, IPPROTO_IP);
  242. if (ssl_sock < 0) {
  243. #ifdef _WIN32
  244. err = WSAGetLastError();
  245. #else
  246. err = -errno;
  247. #endif
  248. goto reconn_err;
  249. }
  250. set_fd_cloexec(ssl_sock);
  251. }
  252. set_tcp_nodelay(vpninfo, ssl_sock);
  253. err = cancellable_connect(vpninfo, ssl_sock, vpninfo->peer_addr, vpninfo->peer_addrlen);
  254. if (err) {
  255. char *errstr;
  256. reconn_err:
  257. #ifdef _WIN32
  258. if (err > 0)
  259. errstr = openconnect__win32_strerror(err);
  260. else
  261. #endif
  262. errstr = strerror(-err);
  263. if (vpninfo->proxy) {
  264. vpn_progress(vpninfo, PRG_ERR,
  265. _("Failed to reconnect to proxy %s: %s\n"),
  266. vpninfo->proxy, errstr);
  267. } else {
  268. vpn_progress(vpninfo, PRG_ERR,
  269. _("Failed to reconnect to host %s: %s\n"),
  270. vpninfo->hostname, errstr);
  271. }
  272. #ifdef _WIN32
  273. if (err > 0)
  274. free(errstr);
  275. #endif
  276. if (ssl_sock >= 0)
  277. closesocket(ssl_sock);
  278. ssl_sock = -EINVAL;
  279. goto out;
  280. }
  281. } else {
  282. struct addrinfo hints, *result, *rp;
  283. char *hostname;
  284. char port[6];
  285. memset(&hints, 0, sizeof(struct addrinfo));
  286. hints.ai_family = AF_UNSPEC;
  287. hints.ai_socktype = SOCK_STREAM;
  288. hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
  289. hints.ai_protocol = 0;
  290. hints.ai_canonname = NULL;
  291. hints.ai_addr = NULL;
  292. hints.ai_next = NULL;
  293. /* The 'port' variable is a string because it's easier
  294. this way than if we pass NULL to getaddrinfo() and
  295. then try to fill in the numeric value into
  296. different types of returned sockaddr_in{6,}. */
  297. #ifdef LIBPROXY_HDR
  298. if (vpninfo->proxy_factory) {
  299. struct oc_text_buf *url_buf = buf_alloc();
  300. char **proxies;
  301. int i = 0;
  302. free(vpninfo->proxy_type);
  303. vpninfo->proxy_type = NULL;
  304. free(vpninfo->proxy);
  305. vpninfo->proxy = NULL;
  306. buf_append(url_buf, "https://%s", vpninfo->hostname);
  307. if (vpninfo->port != 443)
  308. buf_append(url_buf, ":%d", vpninfo->port);
  309. buf_append(url_buf, "/%s", vpninfo->urlpath?:"");
  310. if (buf_error(url_buf)) {
  311. buf_free(url_buf);
  312. ssl_sock = -ENOMEM;
  313. goto out;
  314. }
  315. proxies = px_proxy_factory_get_proxies(vpninfo->proxy_factory,
  316. url_buf->data);
  317. i = 0;
  318. while (proxies && proxies[i]) {
  319. if (!vpninfo->proxy &&
  320. (!strncmp(proxies[i], "http://", 7) ||
  321. !strncmp(proxies[i], "socks://", 8) ||
  322. !strncmp(proxies[i], "socks5://", 9)))
  323. internal_parse_url(proxies[i], &vpninfo->proxy_type,
  324. &vpninfo->proxy, &vpninfo->proxy_port,
  325. NULL, 0);
  326. i++;
  327. }
  328. buf_free(url_buf);
  329. free(proxies);
  330. if (vpninfo->proxy)
  331. vpn_progress(vpninfo, PRG_DEBUG,
  332. _("Proxy from libproxy: %s://%s:%d/\n"),
  333. vpninfo->proxy_type, vpninfo->proxy, vpninfo->port);
  334. }
  335. #endif
  336. if (vpninfo->proxy) {
  337. hostname = vpninfo->proxy;
  338. snprintf(port, 6, "%d", vpninfo->proxy_port);
  339. } else {
  340. hostname = vpninfo->hostname;
  341. snprintf(port, 6, "%d", vpninfo->port);
  342. }
  343. if (hostname[0] == '[' && hostname[strlen(hostname)-1] == ']') {
  344. hostname = strndup(hostname + 1, strlen(hostname) - 2);
  345. if (!hostname) {
  346. ssl_sock = -ENOMEM;
  347. goto out;
  348. }
  349. hints.ai_flags |= AI_NUMERICHOST;
  350. }
  351. if (vpninfo->getaddrinfo_override)
  352. err = vpninfo->getaddrinfo_override(vpninfo->cbdata, hostname, port, &hints, &result);
  353. else
  354. err = getaddrinfo(hostname, port, &hints, &result);
  355. if (err) {
  356. #ifdef _WIN32
  357. char *errstr = openconnect__win32_strerror(WSAGetLastError());
  358. #else
  359. const char *errstr = gai_strerror(err);
  360. #endif
  361. vpn_progress(vpninfo, PRG_ERR,
  362. _("getaddrinfo failed for host '%s': %s\n"),
  363. hostname, errstr);
  364. #ifdef _WIN32
  365. free(errstr);
  366. #endif
  367. if (hints.ai_flags & AI_NUMERICHOST)
  368. free(hostname);
  369. ssl_sock = -EINVAL;
  370. /* If we were just retrying for dynamic DNS, reconnect using
  371. the previously-known IP address */
  372. if (vpninfo->peer_addr) {
  373. vpn_progress(vpninfo, PRG_ERR,
  374. _("Reconnecting to DynDNS server using previously cached IP address\n"));
  375. goto reconnect;
  376. }
  377. goto out;
  378. }
  379. if (hints.ai_flags & AI_NUMERICHOST)
  380. free(hostname);
  381. for (rp = result; rp ; rp = rp->ai_next) {
  382. char host[80];
  383. host[0] = 0;
  384. if (!getnameinfo(rp->ai_addr, rp->ai_addrlen, host,
  385. sizeof(host), NULL, 0, NI_NUMERICHOST))
  386. vpn_progress(vpninfo, PRG_DEBUG, vpninfo->proxy_type ?
  387. _("Attempting to connect to proxy %s%s%s:%s\n") :
  388. _("Attempting to connect to server %s%s%s:%s\n"),
  389. rp->ai_family == AF_INET6 ? "[" : "",
  390. host,
  391. rp->ai_family == AF_INET6 ? "]" : "",
  392. port);
  393. ssl_sock = socket(rp->ai_family, rp->ai_socktype,
  394. rp->ai_protocol);
  395. if (ssl_sock < 0)
  396. continue;
  397. set_fd_cloexec(ssl_sock);
  398. set_tcp_nodelay(vpninfo, ssl_sock);
  399. err = cancellable_connect(vpninfo, ssl_sock, rp->ai_addr, rp->ai_addrlen);
  400. if (!err) {
  401. /* Store the peer address we actually used, so that DTLS can
  402. use it again later */
  403. free(vpninfo->ip_info.gateway_addr);
  404. vpninfo->ip_info.gateway_addr = NULL;
  405. if (host[0]) {
  406. vpninfo->ip_info.gateway_addr = strdup(host);
  407. vpn_progress(vpninfo, PRG_INFO, _("Connected to %s%s%s:%s\n"),
  408. rp->ai_family == AF_INET6 ? "[" : "",
  409. host,
  410. rp->ai_family == AF_INET6 ? "]" : "",
  411. port);
  412. }
  413. free(vpninfo->peer_addr);
  414. vpninfo->peer_addrlen = 0;
  415. vpninfo->peer_addr = malloc(rp->ai_addrlen);
  416. if (!vpninfo->peer_addr) {
  417. vpn_progress(vpninfo, PRG_ERR,
  418. _("Failed to allocate sockaddr storage\n"));
  419. closesocket(ssl_sock);
  420. ssl_sock = -ENOMEM;
  421. freeaddrinfo(result);
  422. goto out;
  423. }
  424. vpninfo->peer_addrlen = rp->ai_addrlen;
  425. memcpy(vpninfo->peer_addr, rp->ai_addr, rp->ai_addrlen);
  426. /* If no proxy, ensure that we output *this* IP address in
  427. * authentication results because we're going to need to
  428. * reconnect to the *same* server from the rotation. And with
  429. * some trick DNS setups, it might possibly be a "rotation"
  430. * even if we only got one result from getaddrinfo() this
  431. * time.
  432. *
  433. * If there's a proxy, we're kind of screwed; we can't know
  434. * which IP address we connected to. Perhaps we ought to do
  435. * the DNS lookup locally and connect to a specific IP? */
  436. if (!vpninfo->proxy && host[0]) {
  437. char *p = malloc(strlen(host) + 3);
  438. if (p) {
  439. free(vpninfo->unique_hostname);
  440. vpninfo->unique_hostname = p;
  441. if (rp->ai_family == AF_INET6)
  442. *p++ = '[';
  443. memcpy(p, host, strlen(host));
  444. p += strlen(host);
  445. if (rp->ai_family == AF_INET6)
  446. *p++ = ']';
  447. *p = 0;
  448. }
  449. }
  450. break;
  451. }
  452. if (host[0]) {
  453. char *errstr;
  454. #ifdef _WIN32
  455. if (err > 0)
  456. errstr = openconnect__win32_strerror(err);
  457. else
  458. #endif
  459. errstr = strerror(-err);
  460. vpn_progress(vpninfo, PRG_INFO, _("Failed to connect to %s%s%s:%s: %s\n"),
  461. rp->ai_family == AF_INET6 ? "[" : "",
  462. host,
  463. rp->ai_family == AF_INET6 ? "]" : "",
  464. port, errstr);
  465. #ifdef _WIN32
  466. if (err > 0)
  467. free(errstr);
  468. #endif
  469. }
  470. closesocket(ssl_sock);
  471. ssl_sock = -1;
  472. /* If we're in DynDNS mode but this *was* the cached IP address,
  473. * don't bother falling back to it if it didn't work. */
  474. if (vpninfo->peer_addr && vpninfo->peer_addrlen == rp->ai_addrlen &&
  475. match_sockaddr(vpninfo->peer_addr, rp->ai_addr)) {
  476. vpn_progress(vpninfo, PRG_TRACE,
  477. _("Forgetting non-functional previous peer address\n"));
  478. free(vpninfo->peer_addr);
  479. vpninfo->peer_addr = 0;
  480. vpninfo->peer_addrlen = 0;
  481. free(vpninfo->ip_info.gateway_addr);
  482. vpninfo->ip_info.gateway_addr = NULL;
  483. }
  484. }
  485. freeaddrinfo(result);
  486. if (ssl_sock < 0) {
  487. vpn_progress(vpninfo, PRG_ERR,
  488. _("Failed to connect to host %s\n"),
  489. vpninfo->proxy?:vpninfo->hostname);
  490. ssl_sock = -EINVAL;
  491. if (vpninfo->peer_addr) {
  492. vpn_progress(vpninfo, PRG_ERR,
  493. _("Reconnecting to DynDNS server using previously cached IP address\n"));
  494. goto reconnect;
  495. }
  496. goto out;
  497. }
  498. }
  499. if (vpninfo->proxy) {
  500. err = process_proxy(vpninfo, ssl_sock);
  501. if (err) {
  502. closesocket(ssl_sock);
  503. if (err == -EAGAIN) {
  504. /* Proxy authentication failed and we need to retry */
  505. vpn_progress(vpninfo, PRG_DEBUG,
  506. _("Reconnecting to proxy %s\n"), vpninfo->proxy);
  507. goto reconnect;
  508. }
  509. ssl_sock = err;
  510. }
  511. }
  512. out:
  513. /* If proxy processing returned -EAGAIN to reconnect before attempting
  514. further auth, and we failed to reconnect, we have to clean up here. */
  515. clear_auth_states(vpninfo, vpninfo->proxy_auth, 1);
  516. return ssl_sock;
  517. }
  518. int __attribute__ ((format (printf, 2, 3)))
  519. openconnect_SSL_printf(struct openconnect_info *vpninfo, const char *fmt, ...)
  520. {
  521. char buf[1024];
  522. va_list args;
  523. buf[1023] = 0;
  524. va_start(args, fmt);
  525. vsnprintf(buf, 1023, fmt, args);
  526. va_end(args);
  527. return vpninfo->ssl_write(vpninfo, buf, strlen(buf));
  528. }
  529. int __attribute__ ((format(printf, 4, 5)))
  530. request_passphrase(struct openconnect_info *vpninfo, const char *label,
  531. char **response, const char *fmt, ...)
  532. {
  533. struct oc_auth_form f;
  534. struct oc_form_opt o;
  535. char buf[1024];
  536. va_list args;
  537. int ret;
  538. buf[1023] = 0;
  539. memset(&f, 0, sizeof(f));
  540. va_start(args, fmt);
  541. vsnprintf(buf, 1023, fmt, args);
  542. va_end(args);
  543. f.auth_id = (char *)label;
  544. f.opts = &o;
  545. o.next = NULL;
  546. o.type = OC_FORM_OPT_PASSWORD;
  547. o.name = (char *)label;
  548. o.label = buf;
  549. o._value = NULL;
  550. ret = process_auth_form(vpninfo, &f);
  551. if (!ret) {
  552. *response = o._value;
  553. return 0;
  554. }
  555. return -EIO;
  556. }
  557. #if defined(__sun__) || defined(__NetBSD__) || defined(__DragonFly__)
  558. int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo)
  559. {
  560. struct statvfs buf;
  561. char *sslkey = openconnect_utf8_to_legacy(vpninfo, vpninfo->certinfo[0].key);
  562. int err = 0;
  563. if (statvfs(sslkey, &buf)) {
  564. err = -errno;
  565. vpn_progress(vpninfo, PRG_ERR, _("statvfs: %s\n"),
  566. strerror(errno));
  567. } else if (asprintf(&vpninfo->certinfo[0].password, "%lx", buf.f_fsid) == -1)
  568. err = -ENOMEM;
  569. if (sslkey != vpninfo->certinfo[0].key)
  570. free(sslkey);
  571. return err;
  572. }
  573. #elif defined(_WIN32)
  574. #include <fileapi.h>
  575. typedef BOOL WINAPI (*GVIBH)(HANDLE, LPWSTR, DWORD, LPDWORD, LPDWORD, LPDWORD, LPWSTR, DWORD);
  576. int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo)
  577. {
  578. HANDLE h;
  579. DWORD serial;
  580. HINSTANCE kernlib;
  581. GVIBH func = NULL;
  582. int success;
  583. int fd;
  584. /* Some versions of Windows don't have this so don't use standard
  585. load-time linking or it'll cause failures. */
  586. kernlib = LoadLibraryA("Kernel32.dll");
  587. if (!kernlib) {
  588. notsupp:
  589. vpn_progress(vpninfo, PRG_ERR,
  590. _("Could not obtain file system ID for passphrase\n"));
  591. return -EOPNOTSUPP;
  592. }
  593. func = (void *)GetProcAddress(kernlib, "GetVolumeInformationByHandleW");
  594. FreeLibrary(kernlib);
  595. if (!func)
  596. goto notsupp;
  597. fd = openconnect_open_utf8(vpninfo, vpninfo->certinfo[0].key, O_RDONLY);
  598. if (fd == -1) {
  599. vpn_progress(vpninfo, PRG_ERR,
  600. _("Failed to open private key file '%s': %s\n"),
  601. vpninfo->certinfo[0].key, strerror(errno));
  602. return -ENOENT;
  603. }
  604. h = (HANDLE)_get_osfhandle(fd);
  605. success = func(h, NULL, 0, &serial, NULL, NULL, NULL, 0);
  606. close(fd);
  607. if (!success)
  608. return -EIO;
  609. if (asprintf(&vpninfo->certinfo[0].password, "%lx", serial) == -1)
  610. return -ENOMEM;
  611. return 0;
  612. }
  613. #elif defined(HAVE_STATFS)
  614. int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo)
  615. {
  616. char *sslkey = openconnect_utf8_to_legacy(vpninfo, vpninfo->certinfo[0].key);
  617. struct statfs buf;
  618. unsigned *fsid = (unsigned *)&buf.f_fsid;
  619. unsigned long long fsid64;
  620. int err = 0;
  621. if (statfs(sslkey, &buf)) {
  622. err = -errno;
  623. vpn_progress(vpninfo, PRG_ERR, _("statfs: %s\n"),
  624. strerror(errno));
  625. return -err;
  626. } else {
  627. fsid64 = ((unsigned long long)fsid[0] << 32) | fsid[1];
  628. if (asprintf(&vpninfo->certinfo[0].password, "%llx", fsid64) == -1)
  629. err = -ENOMEM;
  630. }
  631. if (sslkey != vpninfo->certinfo[0].key)
  632. free(sslkey);
  633. return err;
  634. }
  635. #else
  636. int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo)
  637. {
  638. return -EOPNOTSUPP;
  639. }
  640. #endif
  641. #if defined(OPENCONNECT_OPENSSL)
  642. /* We put this here rather than in openssl.c because it might be needed
  643. for OpenSSL DTLS support even when GnuTLS is being used for HTTPS */
  644. int openconnect_print_err_cb(const char *str, size_t len, void *ptr)
  645. {
  646. struct openconnect_info *vpninfo = ptr;
  647. vpn_progress(vpninfo, PRG_ERR, "%s", str);
  648. return 0;
  649. }
  650. #endif
  651. #ifdef FAKE_ANDROID_KEYSTORE
  652. char *keystore_strerror(int err)
  653. {
  654. return (char *)strerror(-err);
  655. }
  656. int keystore_fetch(const char *key, unsigned char **result)
  657. {
  658. unsigned char *data;
  659. struct stat st;
  660. int fd;
  661. int ret;
  662. fd = open(key, O_RDONLY);
  663. if (fd < 0)
  664. return -errno;
  665. if (fstat(fd, &st)) {
  666. ret = -errno;
  667. goto out_fd;
  668. }
  669. data = malloc(st.st_size + 1);
  670. if (!data) {
  671. ret = -ENOMEM;
  672. goto out_fd;
  673. }
  674. if (read(fd, data, st.st_size) != st.st_size) {
  675. ret = -EIO;
  676. free(data);
  677. goto out_fd;
  678. }
  679. data[st.st_size] = 0;
  680. *result = data;
  681. ret = st.st_size;
  682. out_fd:
  683. close(fd);
  684. return ret;
  685. }
  686. #elif defined(ANDROID_KEYSTORE)
  687. /* keystore.h isn't in the NDK so we need to define these */
  688. #define NO_ERROR 1
  689. #define LOCKED 2
  690. #define UNINITIALIZED 3
  691. #define SYSTEM_ERROR 4
  692. #define PROTOCOL_ERROR 5
  693. #define PERMISSION_DENIED 6
  694. #define KEY_NOT_FOUND 7
  695. #define VALUE_CORRUPTED 8
  696. #define UNDEFINED_ACTION 9
  697. #define WRONG_PASSWORD 10
  698. const char *keystore_strerror(int err)
  699. {
  700. switch (-err) {
  701. case NO_ERROR: return _("No error");
  702. case LOCKED: return _("Keystore locked");
  703. case UNINITIALIZED: return _("Keystore uninitialized");
  704. case SYSTEM_ERROR: return _("System error");
  705. case PROTOCOL_ERROR: return _("Protocol error");
  706. case PERMISSION_DENIED: return _("Permission denied");
  707. case KEY_NOT_FOUND: return _("Key not found");
  708. case VALUE_CORRUPTED: return _("Value corrupted");
  709. case UNDEFINED_ACTION: return _("Undefined action");
  710. case WRONG_PASSWORD:
  711. case WRONG_PASSWORD+1:
  712. case WRONG_PASSWORD+2:
  713. case WRONG_PASSWORD+3: return _("Wrong password");
  714. default: return _("Unknown error");
  715. }
  716. }
  717. /* Returns length, or a negative errno in its own namespace (handled by its
  718. own strerror function above). The numbers are from Android's keystore.h */
  719. int keystore_fetch(const char *key, unsigned char **result)
  720. {
  721. struct sockaddr_un sa = { AF_UNIX, "/dev/socket/keystore" };
  722. socklen_t sl = offsetof(struct sockaddr_un, sun_path) + strlen(sa.sun_path) + 1;
  723. unsigned char *data, *p;
  724. unsigned char buf[3];
  725. int len, fd;
  726. int ret = -SYSTEM_ERROR;
  727. fd = socket(AF_UNIX, SOCK_STREAM, 0);
  728. if (fd < 0)
  729. return -SYSTEM_ERROR;
  730. if (connect(fd, (void *)&sa, sl)) {
  731. close(fd);
  732. return -SYSTEM_ERROR;
  733. }
  734. len = strlen(key);
  735. buf[0] = 'g';
  736. store_be16(buf + 1, len);
  737. if (send(fd, buf, 3, 0) != 3 || send(fd, key, len, 0) != len ||
  738. shutdown(fd, SHUT_WR) || recv(fd, buf, 1, 0) != 1)
  739. goto out;
  740. if (buf[0] != NO_ERROR) {
  741. /* Should never be zero */
  742. ret = buf[0] ? -buf[0] : -PROTOCOL_ERROR;
  743. goto out;
  744. }
  745. if (recv(fd, buf, 2, 0) != 2)
  746. goto out;
  747. len = load_be16(buf);
  748. data = malloc(len);
  749. if (!data)
  750. goto out;
  751. p = data;
  752. ret = len;
  753. while (len) {
  754. int got = recv(fd, p, len, 0);
  755. if (got <= 0) {
  756. free(data);
  757. ret = -PROTOCOL_ERROR;
  758. goto out;
  759. }
  760. len -= got;
  761. p += got;
  762. }
  763. *result = data;
  764. out:
  765. close(fd);
  766. return ret;
  767. }
  768. #endif
  769. void cmd_fd_set(struct openconnect_info *vpninfo, fd_set *fds, int *maxfd)
  770. {
  771. if (vpninfo->cmd_fd != -1) {
  772. FD_SET(vpninfo->cmd_fd, fds);
  773. if (vpninfo->cmd_fd > *maxfd)
  774. *maxfd = vpninfo->cmd_fd;
  775. }
  776. }
  777. void check_cmd_fd(struct openconnect_info *vpninfo, fd_set *fds)
  778. {
  779. char cmd;
  780. if (vpninfo->cmd_fd == -1 || !FD_ISSET(vpninfo->cmd_fd, fds))
  781. return;
  782. if (vpninfo->cmd_fd_write == -1) {
  783. /* legacy openconnect_set_cancel_fd() users */
  784. vpninfo->got_cancel_cmd = 1;
  785. return;
  786. }
  787. #ifdef _WIN32
  788. if (recv(vpninfo->cmd_fd, &cmd, 1, 0) != 1)
  789. return;
  790. #else
  791. if (read(vpninfo->cmd_fd, &cmd, 1) != 1)
  792. return;
  793. #endif
  794. switch (cmd) {
  795. case OC_CMD_CANCEL:
  796. case OC_CMD_DETACH:
  797. vpninfo->got_cancel_cmd = 1;
  798. vpninfo->cancel_type = cmd;
  799. break;
  800. case OC_CMD_PAUSE:
  801. vpninfo->got_pause_cmd = 1;
  802. break;
  803. case OC_CMD_STATS:
  804. if (vpninfo->stats_handler)
  805. vpninfo->stats_handler(vpninfo->cbdata, &vpninfo->stats);
  806. }
  807. }
  808. int is_cancel_pending(struct openconnect_info *vpninfo, fd_set *fds)
  809. {
  810. check_cmd_fd(vpninfo, fds);
  811. return vpninfo->got_cancel_cmd || vpninfo->got_pause_cmd;
  812. }
  813. void poll_cmd_fd(struct openconnect_info *vpninfo, int timeout)
  814. {
  815. fd_set rd_set;
  816. int maxfd = 0;
  817. time_t expiration = time(NULL) + timeout, now = 0;
  818. while (now < expiration && !vpninfo->got_cancel_cmd && !vpninfo->got_pause_cmd) {
  819. struct timeval tv;
  820. now = time(NULL);
  821. tv.tv_sec = now >= expiration ? 0 : expiration - now;
  822. tv.tv_usec = 0;
  823. /* If the cmd_fd is internal and we've been told to poll it,
  824. * don't *keep* doing so afterwards. */
  825. vpninfo->need_poll_cmd_fd = !vpninfo->cmd_fd_internal;
  826. FD_ZERO(&rd_set);
  827. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  828. if (select(maxfd + 1, &rd_set, NULL, NULL, &tv) < 0 &&
  829. errno != EINTR) {
  830. vpn_perror(vpninfo, _("Failed select() for command socket"));
  831. }
  832. if (FD_ISSET(vpninfo->cmd_fd, &rd_set)) {
  833. vpninfo->need_poll_cmd_fd = 1; /* Until it's *empty */
  834. check_cmd_fd(vpninfo, &rd_set);
  835. }
  836. }
  837. }
  838. #ifdef _WIN32
  839. #include <io.h>
  840. #include <sys/stat.h>
  841. int openconnect_open_utf8(struct openconnect_info *vpninfo, const char *fname, int mode)
  842. {
  843. wchar_t *fname_w;
  844. int nr_chars = MultiByteToWideChar(CP_UTF8, 0, fname, -1, NULL, 0);
  845. int fd;
  846. if (!nr_chars) {
  847. errno = EINVAL;
  848. return -1;
  849. }
  850. fname_w = malloc(nr_chars * sizeof(wchar_t));
  851. if (!fname_w) {
  852. errno = ENOMEM;
  853. return -1;
  854. }
  855. MultiByteToWideChar(CP_UTF8, 0, fname, -1, fname_w, nr_chars);
  856. fd = _wopen(fname_w, mode, _S_IREAD | _S_IWRITE);
  857. free(fname_w);
  858. return fd;
  859. }
  860. #else
  861. int openconnect_open_utf8(struct openconnect_info *vpninfo, const char *fname, int mode)
  862. {
  863. char *legacy_fname = openconnect_utf8_to_legacy(vpninfo, fname);
  864. int fd;
  865. fd = open(legacy_fname, mode, 0644);
  866. if (legacy_fname != fname)
  867. free(legacy_fname);
  868. return fd;
  869. }
  870. #endif
  871. FILE *openconnect_fopen_utf8(struct openconnect_info *vpninfo, const char *fname,
  872. const char *mode)
  873. {
  874. int fd;
  875. int flags;
  876. if (!strcmp(mode, "r"))
  877. flags = O_RDONLY|O_CLOEXEC;
  878. else if (!strcmp(mode, "rb"))
  879. flags = O_RDONLY|O_CLOEXEC|O_BINARY;
  880. else if (!strcmp(mode, "w"))
  881. flags = O_WRONLY|O_CLOEXEC|O_CREAT|O_TRUNC;
  882. else if (!strcmp(mode, "wb"))
  883. flags = O_WRONLY|O_CLOEXEC|O_CREAT|O_TRUNC|O_BINARY;
  884. else {
  885. /* This should never happen, but if we forget and start using other
  886. modes without implementing proper mode->flags conversion, complain! */
  887. vpn_progress(vpninfo, PRG_ERR,
  888. _("%s() used with unsupported mode '%s'\n"),
  889. __func__, mode);
  890. return NULL;
  891. }
  892. fd = openconnect_open_utf8(vpninfo, fname, flags);
  893. if (fd == -1)
  894. return NULL;
  895. return fdopen(fd, mode);
  896. }
  897. ssize_t openconnect_read_file(struct openconnect_info *vpninfo, const char *fname,
  898. char **ptr)
  899. {
  900. int fd, len;
  901. struct stat st;
  902. char *buf;
  903. fd = openconnect_open_utf8(vpninfo, fname, O_RDONLY|O_BINARY);
  904. if (fd < 0) {
  905. vpn_progress(vpninfo, PRG_ERR,
  906. _("Failed to open %s: %s\n"),
  907. fname, strerror(errno));
  908. return -ENOENT;
  909. }
  910. if (fstat(fd, &st)) {
  911. vpn_progress(vpninfo, PRG_ERR,
  912. _("Failed to fstat() %s: %s\n"),
  913. fname, strerror(errno));
  914. close(fd);
  915. return -EIO;
  916. }
  917. if (st.st_size == 0) {
  918. vpn_progress(vpninfo, PRG_INFO, _("File %s is empty\n"),
  919. vpninfo->xmlconfig);
  920. close(fd);
  921. return -ENOENT;
  922. }
  923. if (st.st_size >= INT_MAX || st.st_size < 0) {
  924. vpn_progress(vpninfo, PRG_INFO, _("File %s has suspicious size %" PRId64 "\n"),
  925. vpninfo->xmlconfig, (int64_t)st.st_size);
  926. close(fd);
  927. return -EIO;
  928. }
  929. len = st.st_size;
  930. buf = malloc(len + 1);
  931. if (!buf) {
  932. vpn_progress(vpninfo, PRG_ERR,
  933. _("Failed to allocate %d bytes for %s\n"),
  934. len + 1, fname);
  935. close(fd);
  936. return -ENOMEM;
  937. }
  938. if (read(fd, buf, len) != len) {
  939. vpn_progress(vpninfo, PRG_ERR,
  940. _("Failed to read %s: %s\n"),
  941. fname, strerror(errno));
  942. free(buf);
  943. close(fd);
  944. return -EIO;
  945. }
  946. buf[len] = 0;
  947. close(fd);
  948. *ptr = buf;
  949. return len;
  950. }
  951. int udp_sockaddr(struct openconnect_info *vpninfo, int port)
  952. {
  953. free(vpninfo->dtls_addr);
  954. vpninfo->dtls_addr = malloc(vpninfo->peer_addrlen);
  955. if (!vpninfo->dtls_addr)
  956. return -ENOMEM;
  957. memcpy(vpninfo->dtls_addr, vpninfo->peer_addr, vpninfo->peer_addrlen);
  958. if (vpninfo->peer_addr->sa_family == AF_INET) {
  959. struct sockaddr_in *sin = (void *)vpninfo->dtls_addr;
  960. sin->sin_port = htons(port);
  961. vpninfo->dtls_tos_proto = IPPROTO_IP;
  962. vpninfo->dtls_tos_optname = IP_TOS;
  963. } else if (vpninfo->peer_addr->sa_family == AF_INET6) {
  964. struct sockaddr_in6 *sin = (void *)vpninfo->dtls_addr;
  965. sin->sin6_port = htons(port);
  966. #if defined(IPV6_TCLASS)
  967. vpninfo->dtls_tos_proto = IPPROTO_IPV6;
  968. vpninfo->dtls_tos_optname = IPV6_TCLASS;
  969. #endif
  970. } else {
  971. vpn_progress(vpninfo, PRG_ERR,
  972. _("Unknown protocol family %d. Cannot create UDP server address\n"),
  973. vpninfo->peer_addr->sa_family);
  974. return -EINVAL;
  975. }
  976. /* in case DTLS TOS copy is disabled, reset the optname value */
  977. /* so that the copy won't be applied in dtls.c / dtls_mainloop() */
  978. if (!vpninfo->dtls_pass_tos)
  979. vpninfo->dtls_tos_optname = 0;
  980. return 0;
  981. }
  982. int udp_connect(struct openconnect_info *vpninfo)
  983. {
  984. int fd, sndbuf;
  985. fd = socket(vpninfo->peer_addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
  986. if (fd < 0) {
  987. vpn_perror(vpninfo, _("Open UDP socket"));
  988. return -EINVAL;
  989. }
  990. if (vpninfo->protect_socket)
  991. vpninfo->protect_socket(vpninfo->cbdata, fd);
  992. sndbuf = vpninfo->ip_info.mtu;
  993. if (!sndbuf)
  994. sndbuf = 1500;
  995. sndbuf *= vpninfo->max_qlen;
  996. if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&sndbuf, sizeof(sndbuf)) < 0) {
  997. vpn_perror(vpninfo, "Set UDP socket send buffer");
  998. }
  999. socklen_t l = sizeof(sndbuf);
  1000. if (!getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&sndbuf, &l))
  1001. vpn_progress(vpninfo, PRG_DEBUG, "UDP SO_SNDBUF: %d\n", sndbuf);
  1002. if (vpninfo->dtls_local_port) {
  1003. union {
  1004. struct sockaddr_in in;
  1005. struct sockaddr_in6 in6;
  1006. } dtls_bind_addr;
  1007. int dtls_bind_addrlen;
  1008. memset(&dtls_bind_addr, 0, sizeof(dtls_bind_addr));
  1009. if (vpninfo->peer_addr->sa_family == AF_INET) {
  1010. struct sockaddr_in *addr = &dtls_bind_addr.in;
  1011. dtls_bind_addrlen = sizeof(*addr);
  1012. addr->sin_family = AF_INET;
  1013. addr->sin_addr.s_addr = INADDR_ANY;
  1014. addr->sin_port = htons(vpninfo->dtls_local_port);
  1015. } else if (vpninfo->peer_addr->sa_family == AF_INET6) {
  1016. struct sockaddr_in6 *addr = &dtls_bind_addr.in6;
  1017. dtls_bind_addrlen = sizeof(*addr);
  1018. addr->sin6_family = AF_INET6;
  1019. addr->sin6_addr = in6addr_any;
  1020. addr->sin6_port = htons(vpninfo->dtls_local_port);
  1021. } else {
  1022. vpn_progress(vpninfo, PRG_ERR,
  1023. _("Unknown protocol family %d. Cannot use UDP transport\n"),
  1024. vpninfo->peer_addr->sa_family);
  1025. vpninfo->dtls_attempt_period = 0;
  1026. closesocket(fd);
  1027. return -EINVAL;
  1028. }
  1029. if (bind(fd, (struct sockaddr *)&dtls_bind_addr, dtls_bind_addrlen)) {
  1030. vpn_perror(vpninfo, _("Bind UDP socket"));
  1031. closesocket(fd);
  1032. return -EINVAL;
  1033. }
  1034. }
  1035. if (connect(fd, vpninfo->dtls_addr, vpninfo->peer_addrlen)) {
  1036. vpn_perror(vpninfo, _("Connect UDP socket"));
  1037. closesocket(fd);
  1038. return -EINVAL;
  1039. }
  1040. set_fd_cloexec(fd);
  1041. if (set_sock_nonblock(fd)) {
  1042. vpn_perror(vpninfo, _("Make UDP socket non-blocking"));
  1043. closesocket(fd);
  1044. return -EIO;
  1045. }
  1046. return fd;
  1047. }
  1048. int ssl_reconnect(struct openconnect_info *vpninfo)
  1049. {
  1050. int ret;
  1051. int timeout;
  1052. int interval;
  1053. int tun_up = tun_is_up(vpninfo);
  1054. openconnect_close_https(vpninfo, 0);
  1055. timeout = vpninfo->reconnect_timeout;
  1056. interval = vpninfo->reconnect_interval;
  1057. free_pkt(vpninfo, vpninfo->dtls_pkt);
  1058. vpninfo->dtls_pkt = NULL;
  1059. free_pkt(vpninfo, vpninfo->tun_pkt);
  1060. vpninfo->tun_pkt = NULL;
  1061. while (1) {
  1062. if (tun_up)
  1063. script_config_tun(vpninfo, "attempt-reconnect");
  1064. ret = vpninfo->proto->tcp_connect(vpninfo);
  1065. if (!ret)
  1066. break;
  1067. if (timeout <= 0)
  1068. return ret;
  1069. if (ret == -EPERM) {
  1070. vpn_progress(vpninfo, PRG_ERR,
  1071. _("Cookie is no longer valid, ending session\n"));
  1072. return ret;
  1073. }
  1074. vpn_progress(vpninfo, PRG_INFO,
  1075. _("sleep %ds, remaining timeout %ds\n"),
  1076. interval, timeout);
  1077. poll_cmd_fd(vpninfo, interval);
  1078. if (vpninfo->got_cancel_cmd)
  1079. return -EINTR;
  1080. if (vpninfo->got_pause_cmd)
  1081. return 0;
  1082. timeout -= interval;
  1083. interval += vpninfo->reconnect_interval;
  1084. if (interval > RECONNECT_INTERVAL_MAX)
  1085. interval = RECONNECT_INTERVAL_MAX;
  1086. }
  1087. if (tun_up) {
  1088. script_config_tun(vpninfo, "reconnect");
  1089. if (vpninfo->reconnected)
  1090. vpninfo->reconnected(vpninfo->cbdata);
  1091. }
  1092. return 0;
  1093. }
  1094. int cancellable_gets(struct openconnect_info *vpninfo, int fd,
  1095. char *buf, size_t len)
  1096. {
  1097. int i = 0;
  1098. int ret;
  1099. if (len < 2)
  1100. return -EINVAL;
  1101. while ((ret = cancellable_recv(vpninfo, fd, (void *)(buf + i), 1)) == 1) {
  1102. if (buf[i] == '\n') {
  1103. buf[i] = 0;
  1104. if (i && buf[i-1] == '\r') {
  1105. buf[i-1] = 0;
  1106. i--;
  1107. }
  1108. return i;
  1109. }
  1110. i++;
  1111. if (i >= len - 1) {
  1112. buf[i] = 0;
  1113. return i;
  1114. }
  1115. }
  1116. buf[i] = 0;
  1117. return i ?: ret;
  1118. }
  1119. int cancellable_send(struct openconnect_info *vpninfo, int fd,
  1120. const char *buf, size_t len)
  1121. {
  1122. size_t count;
  1123. if (fd == -1)
  1124. return -EINVAL;
  1125. for (count = 0; count < len; ) {
  1126. fd_set rd_set, wr_set;
  1127. int maxfd = fd;
  1128. int i;
  1129. FD_ZERO(&wr_set);
  1130. FD_ZERO(&rd_set);
  1131. FD_SET(fd, &wr_set);
  1132. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  1133. if (select(maxfd + 1, &rd_set, &wr_set, NULL, NULL) < 0 &&
  1134. errno != EINTR) {
  1135. vpn_perror(vpninfo, _("Failed select() for socket send"));
  1136. return -EIO;
  1137. }
  1138. if (is_cancel_pending(vpninfo, &rd_set))
  1139. return -EINTR;
  1140. /* Not that this should ever be able to happen... */
  1141. if (!FD_ISSET(fd, &wr_set))
  1142. continue;
  1143. i = send(fd, (void *)&buf[count], len - count, 0);
  1144. if (i < 0)
  1145. return -errno;
  1146. count += i;
  1147. }
  1148. return count;
  1149. }
  1150. int cancellable_recv(struct openconnect_info *vpninfo, int fd,
  1151. char *buf, size_t len)
  1152. {
  1153. size_t count;
  1154. if (fd == -1)
  1155. return -EINVAL;
  1156. for (count = 0; count < len; ) {
  1157. fd_set rd_set;
  1158. int maxfd = fd;
  1159. int i;
  1160. FD_ZERO(&rd_set);
  1161. FD_SET(fd, &rd_set);
  1162. cmd_fd_set(vpninfo, &rd_set, &maxfd);
  1163. if (select(maxfd + 1, &rd_set, NULL, NULL, NULL) < 0 &&
  1164. errno != EINTR) {
  1165. vpn_perror(vpninfo, _("Failed select() for socket recv"));
  1166. return -EIO;
  1167. }
  1168. if (is_cancel_pending(vpninfo, &rd_set))
  1169. return -EINTR;
  1170. /* Not that this should ever be able to happen... */
  1171. if (!FD_ISSET(fd, &rd_set))
  1172. continue;
  1173. i = recv(fd, (void *)&buf[count], len - count, 0);
  1174. if (i < 0)
  1175. return -errno;
  1176. else if (i == 0)
  1177. return -ECONNRESET;
  1178. count += i;
  1179. }
  1180. return count;
  1181. }