geom_gate userland utility improvements
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1069 lines
25 KiB

  1. /*-
  2. * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  3. *
  4. * Copyright (c) 2004 Pawel Jakub Dawidek <pjd@FreeBSD.org>
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
  17. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  22. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  23. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  24. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  25. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  26. * SUCH DAMAGE.
  27. *
  28. * $FreeBSD$
  29. */
  30. #include <sys/param.h>
  31. #include <sys/bio.h>
  32. #include <sys/disk.h>
  33. #include <sys/endian.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/queue.h>
  36. #include <sys/socket.h>
  37. #include <sys/stat.h>
  38. #include <sys/time.h>
  39. #include <arpa/inet.h>
  40. #include <netinet/in.h>
  41. #include <netinet/tcp.h>
  42. #include <assert.h>
  43. #include <err.h>
  44. #include <errno.h>
  45. #include <fcntl.h>
  46. #include <libgen.h>
  47. #include <libutil.h>
  48. #include <paths.h>
  49. #include <pthread.h>
  50. #include <signal.h>
  51. #include <stdarg.h>
  52. #include <stdio.h>
  53. #include <stdlib.h>
  54. #include <stdint.h>
  55. #include <string.h>
  56. #include <syslog.h>
  57. #include <unistd.h>
  58. #include "ggate.h"
  59. #define GGATED_EXPORT_FILE "/etc/gg.exports"
  60. struct ggd_connection {
  61. off_t c_mediasize;
  62. unsigned c_sectorsize;
  63. unsigned c_flags; /* flags (RO/RW) */
  64. int c_diskfd;
  65. int c_sendfd;
  66. int c_recvfd;
  67. time_t c_birthtime;
  68. char *c_path;
  69. uint64_t c_token;
  70. in_addr_t c_srcip;
  71. LIST_ENTRY(ggd_connection) c_next;
  72. };
  73. struct ggd_request {
  74. struct g_gate_hdr r_hdr;
  75. char *r_data;
  76. TAILQ_ENTRY(ggd_request) r_next;
  77. };
  78. #define r_cmd r_hdr.gh_cmd
  79. #define r_offset r_hdr.gh_offset
  80. #define r_length r_hdr.gh_length
  81. #define r_error r_hdr.gh_error
  82. struct ggd_export {
  83. char *e_path; /* path to device/file */
  84. in_addr_t e_ip; /* remote IP address */
  85. in_addr_t e_mask; /* IP mask */
  86. unsigned e_flags; /* flags (RO/RW) */
  87. SLIST_ENTRY(ggd_export) e_next;
  88. };
  89. static const char *exports_file = GGATED_EXPORT_FILE;
  90. static int got_sighup = 0;
  91. static in_addr_t bindaddr;
  92. static TAILQ_HEAD(, ggd_request) inqueue = TAILQ_HEAD_INITIALIZER(inqueue);
  93. static TAILQ_HEAD(, ggd_request) outqueue = TAILQ_HEAD_INITIALIZER(outqueue);
  94. static pthread_mutex_t inqueue_mtx, outqueue_mtx;
  95. static pthread_cond_t inqueue_cond, outqueue_cond;
  96. static SLIST_HEAD(, ggd_export) exports = SLIST_HEAD_INITIALIZER(exports);
  97. static LIST_HEAD(, ggd_connection) connections = LIST_HEAD_INITIALIZER(connections);
  98. static void *recv_thread(void *arg);
  99. static void *disk_thread(void *arg);
  100. static void *send_thread(void *arg);
  101. static void
  102. usage(void)
  103. {
  104. fprintf(stderr, "usage: %s [-nv] [-a address] [-F pidfile] [-p port] "
  105. "[-R rcvbuf] [-S sndbuf] [exports file]\n", getprogname());
  106. exit(EXIT_FAILURE);
  107. }
  108. static char *
  109. ip2str(in_addr_t ip)
  110. {
  111. static char sip[16];
  112. snprintf(sip, sizeof(sip), "%u.%u.%u.%u",
  113. ((ip >> 24) & 0xff),
  114. ((ip >> 16) & 0xff),
  115. ((ip >> 8) & 0xff),
  116. (ip & 0xff));
  117. return (sip);
  118. }
  119. static in_addr_t
  120. countmask(unsigned m)
  121. {
  122. in_addr_t mask;
  123. if (m == 0) {
  124. mask = 0x0;
  125. } else {
  126. mask = 1 << (32 - m);
  127. mask--;
  128. mask = ~mask;
  129. }
  130. return (mask);
  131. }
  132. static void
  133. line_parse(char *line, unsigned lineno)
  134. {
  135. struct ggd_export *ex;
  136. char *word, *path, *sflags;
  137. unsigned flags, i, vmask;
  138. in_addr_t ip, mask;
  139. ip = mask = flags = vmask = 0;
  140. path = NULL;
  141. sflags = NULL;
  142. for (i = 0, word = strtok(line, " \t"); word != NULL;
  143. i++, word = strtok(NULL, " \t")) {
  144. switch (i) {
  145. case 0: /* IP address or host name */
  146. ip = g_gate_str2ip(strsep(&word, "/"));
  147. if (ip == INADDR_NONE) {
  148. g_gate_xlog("Invalid IP/host name at line %u.",
  149. lineno);
  150. }
  151. ip = ntohl(ip);
  152. if (word == NULL)
  153. vmask = 32;
  154. else {
  155. errno = 0;
  156. vmask = strtoul(word, NULL, 10);
  157. if (vmask == 0 && errno != 0) {
  158. g_gate_xlog("Invalid IP mask value at "
  159. "line %u.", lineno);
  160. }
  161. if ((unsigned)vmask > 32) {
  162. g_gate_xlog("Invalid IP mask value at line %u.",
  163. lineno);
  164. }
  165. }
  166. mask = countmask(vmask);
  167. break;
  168. case 1: /* flags */
  169. if (strcasecmp("rd", word) == 0 ||
  170. strcasecmp("ro", word) == 0) {
  171. flags = O_RDONLY;
  172. } else if (strcasecmp("wo", word) == 0) {
  173. flags = O_WRONLY;
  174. } else if (strcasecmp("rw", word) == 0) {
  175. flags = O_RDWR;
  176. } else {
  177. g_gate_xlog("Invalid value in flags field at "
  178. "line %u.", lineno);
  179. }
  180. sflags = word;
  181. break;
  182. case 2: /* path */
  183. if (strlen(word) >= MAXPATHLEN) {
  184. g_gate_xlog("Path too long at line %u. ",
  185. lineno);
  186. }
  187. path = word;
  188. break;
  189. default:
  190. g_gate_xlog("Too many arguments at line %u. ", lineno);
  191. }
  192. }
  193. if (i != 3)
  194. g_gate_xlog("Too few arguments at line %u.", lineno);
  195. ex = malloc(sizeof(*ex));
  196. if (ex == NULL)
  197. g_gate_xlog("Not enough memory.");
  198. ex->e_path = strdup(path);
  199. if (ex->e_path == NULL)
  200. g_gate_xlog("Not enough memory.");
  201. /* Made 'and' here. */
  202. ex->e_ip = (ip & mask);
  203. ex->e_mask = mask;
  204. ex->e_flags = flags;
  205. SLIST_INSERT_HEAD(&exports, ex, e_next);
  206. g_gate_log(LOG_DEBUG, "Added %s/%u %s %s to exports list.",
  207. ip2str(ex->e_ip), vmask, path, sflags);
  208. }
  209. static void
  210. exports_clear(void)
  211. {
  212. struct ggd_export *ex;
  213. while (!SLIST_EMPTY(&exports)) {
  214. ex = SLIST_FIRST(&exports);
  215. SLIST_REMOVE_HEAD(&exports, e_next);
  216. free(ex);
  217. }
  218. }
  219. #define EXPORTS_LINE_SIZE 2048
  220. static void
  221. exports_get(void)
  222. {
  223. char buf[EXPORTS_LINE_SIZE], *line;
  224. unsigned lineno = 0, objs = 0, len;
  225. FILE *fd;
  226. exports_clear();
  227. fd = fopen(exports_file, "r");
  228. if (fd == NULL) {
  229. g_gate_xlog("Cannot open exports file (%s): %s.", exports_file,
  230. strerror(errno));
  231. }
  232. g_gate_log(LOG_INFO, "Reading exports file (%s).", exports_file);
  233. for (;;) {
  234. if (fgets(buf, sizeof(buf), fd) == NULL) {
  235. if (feof(fd))
  236. break;
  237. g_gate_xlog("Error while reading exports file: %s.",
  238. strerror(errno));
  239. }
  240. /* Increase line count. */
  241. lineno++;
  242. /* Skip spaces and tabs. */
  243. for (line = buf; *line == ' ' || *line == '\t'; ++line)
  244. ;
  245. /* Empty line, comment or empty line at the end of file. */
  246. if (*line == '\n' || *line == '#' || *line == '\0')
  247. continue;
  248. len = strlen(line);
  249. if (line[len - 1] == '\n') {
  250. /* Remove new line char. */
  251. line[len - 1] = '\0';
  252. } else {
  253. if (!feof(fd))
  254. g_gate_xlog("Line %u too long.", lineno);
  255. }
  256. line_parse(line, lineno);
  257. objs++;
  258. }
  259. fclose(fd);
  260. if (objs == 0)
  261. g_gate_xlog("There are no objects to export.");
  262. g_gate_log(LOG_INFO, "Exporting %u object(s).", objs);
  263. }
  264. static int
  265. exports_check(struct ggd_export *ex, struct g_gate_cinit *cinit,
  266. struct ggd_connection *conn)
  267. {
  268. char ipmask[32]; /* 32 == strlen("xxx.xxx.xxx.xxx/xxx.xxx.xxx.xxx")+1 */
  269. int error = 0, flags;
  270. strlcpy(ipmask, ip2str(ex->e_ip), sizeof(ipmask));
  271. strlcat(ipmask, "/", sizeof(ipmask));
  272. strlcat(ipmask, ip2str(ex->e_mask), sizeof(ipmask));
  273. if ((cinit->gc_flags & GGATE_FLAG_RDONLY) != 0) {
  274. if (ex->e_flags == O_WRONLY) {
  275. g_gate_log(LOG_WARNING, "Read-only access requested, "
  276. "but %s (%s) is exported write-only.", ex->e_path,
  277. ipmask);
  278. return (EPERM);
  279. } else {
  280. conn->c_flags |= GGATE_FLAG_RDONLY;
  281. }
  282. } else if ((cinit->gc_flags & GGATE_FLAG_WRONLY) != 0) {
  283. if (ex->e_flags == O_RDONLY) {
  284. g_gate_log(LOG_WARNING, "Write-only access requested, "
  285. "but %s (%s) is exported read-only.", ex->e_path,
  286. ipmask);
  287. return (EPERM);
  288. } else {
  289. conn->c_flags |= GGATE_FLAG_WRONLY;
  290. }
  291. } else {
  292. if (ex->e_flags == O_RDONLY) {
  293. g_gate_log(LOG_WARNING, "Read-write access requested, "
  294. "but %s (%s) is exported read-only.", ex->e_path,
  295. ipmask);
  296. return (EPERM);
  297. } else if (ex->e_flags == O_WRONLY) {
  298. g_gate_log(LOG_WARNING, "Read-write access requested, "
  299. "but %s (%s) is exported write-only.", ex->e_path,
  300. ipmask);
  301. return (EPERM);
  302. }
  303. }
  304. if ((conn->c_flags & GGATE_FLAG_RDONLY) != 0)
  305. flags = O_RDONLY;
  306. else if ((conn->c_flags & GGATE_FLAG_WRONLY) != 0)
  307. flags = O_WRONLY;
  308. else
  309. flags = O_RDWR;
  310. conn->c_diskfd = open(ex->e_path, flags);
  311. if (conn->c_diskfd == -1) {
  312. error = errno;
  313. g_gate_log(LOG_ERR, "Cannot open %s: %s.", ex->e_path,
  314. strerror(error));
  315. return (error);
  316. }
  317. return (0);
  318. }
  319. static struct ggd_export *
  320. exports_find(struct sockaddr *s, struct g_gate_cinit *cinit,
  321. struct ggd_connection *conn)
  322. {
  323. struct ggd_export *ex;
  324. in_addr_t ip;
  325. int error;
  326. ip = htonl(((struct sockaddr_in *)(void *)s)->sin_addr.s_addr);
  327. SLIST_FOREACH(ex, &exports, e_next) {
  328. if ((ip & ex->e_mask) != ex->e_ip) {
  329. g_gate_log(LOG_DEBUG, "exports[%s]: IP mismatch.",
  330. ex->e_path);
  331. continue;
  332. }
  333. if (strcmp(cinit->gc_path, ex->e_path) != 0) {
  334. g_gate_log(LOG_DEBUG, "exports[%s]: Path mismatch.",
  335. ex->e_path);
  336. continue;
  337. }
  338. error = exports_check(ex, cinit, conn);
  339. if (error == 0)
  340. return (ex);
  341. else {
  342. errno = error;
  343. return (NULL);
  344. }
  345. }
  346. g_gate_log(LOG_WARNING, "Unauthorized connection from: %s.",
  347. ip2str(ip));
  348. errno = EPERM;
  349. return (NULL);
  350. }
  351. /*
  352. * Remove timed out connections.
  353. */
  354. static void
  355. connection_cleanups(void)
  356. {
  357. struct ggd_connection *conn, *tconn;
  358. time_t now;
  359. time(&now);
  360. LIST_FOREACH_SAFE(conn, &connections, c_next, tconn) {
  361. if (now - conn->c_birthtime > 10) {
  362. LIST_REMOVE(conn, c_next);
  363. g_gate_log(LOG_NOTICE,
  364. "Connection from %s [%s] removed.",
  365. ip2str(conn->c_srcip), conn->c_path);
  366. close(conn->c_diskfd);
  367. close(conn->c_sendfd);
  368. close(conn->c_recvfd);
  369. free(conn->c_path);
  370. free(conn);
  371. }
  372. }
  373. }
  374. static struct ggd_connection *
  375. connection_find(struct g_gate_cinit *cinit)
  376. {
  377. struct ggd_connection *conn;
  378. LIST_FOREACH(conn, &connections, c_next) {
  379. if (conn->c_token == cinit->gc_token)
  380. break;
  381. }
  382. return (conn);
  383. }
  384. static struct ggd_connection *
  385. connection_new(struct g_gate_cinit *cinit, struct sockaddr *s, int sfd)
  386. {
  387. struct ggd_connection *conn;
  388. in_addr_t ip;
  389. /*
  390. * First, look for old connections.
  391. * We probably should do it every X seconds, but what for?
  392. * It is only dangerous if an attacker wants to overload connections
  393. * queue, so here is a good place to do the cleanups.
  394. */
  395. connection_cleanups();
  396. conn = malloc(sizeof(*conn));
  397. if (conn == NULL)
  398. return (NULL);
  399. conn->c_path = strdup(cinit->gc_path);
  400. if (conn->c_path == NULL) {
  401. free(conn);
  402. return (NULL);
  403. }
  404. conn->c_token = cinit->gc_token;
  405. ip = htonl(((struct sockaddr_in *)(void *)s)->sin_addr.s_addr);
  406. conn->c_srcip = ip;
  407. conn->c_sendfd = conn->c_recvfd = -1;
  408. if ((cinit->gc_flags & GGATE_FLAG_SEND) != 0)
  409. conn->c_sendfd = sfd;
  410. else
  411. conn->c_recvfd = sfd;
  412. conn->c_mediasize = 0;
  413. conn->c_sectorsize = 0;
  414. time(&conn->c_birthtime);
  415. conn->c_flags = cinit->gc_flags;
  416. LIST_INSERT_HEAD(&connections, conn, c_next);
  417. g_gate_log(LOG_DEBUG, "Connection created [%s, %s].", ip2str(ip),
  418. conn->c_path);
  419. return (conn);
  420. }
  421. static int
  422. connection_add(struct ggd_connection *conn, struct g_gate_cinit *cinit,
  423. struct sockaddr *s, int sfd)
  424. {
  425. in_addr_t ip;
  426. ip = htonl(((struct sockaddr_in *)(void *)s)->sin_addr.s_addr);
  427. if ((cinit->gc_flags & GGATE_FLAG_SEND) != 0) {
  428. if (conn->c_sendfd != -1) {
  429. g_gate_log(LOG_WARNING,
  430. "Send socket already exists [%s, %s].", ip2str(ip),
  431. conn->c_path);
  432. return (EEXIST);
  433. }
  434. conn->c_sendfd = sfd;
  435. } else {
  436. if (conn->c_recvfd != -1) {
  437. g_gate_log(LOG_WARNING,
  438. "Receive socket already exists [%s, %s].",
  439. ip2str(ip), conn->c_path);
  440. return (EEXIST);
  441. }
  442. conn->c_recvfd = sfd;
  443. }
  444. g_gate_log(LOG_DEBUG, "Connection added [%s, %s].", ip2str(ip),
  445. conn->c_path);
  446. return (0);
  447. }
  448. /*
  449. * Remove one socket from the given connection or the whole
  450. * connection if sfd == -1.
  451. */
  452. static void
  453. connection_remove(struct ggd_connection *conn)
  454. {
  455. LIST_REMOVE(conn, c_next);
  456. g_gate_log(LOG_DEBUG, "Connection removed [%s %s].",
  457. ip2str(conn->c_srcip), conn->c_path);
  458. if (conn->c_sendfd != -1)
  459. close(conn->c_sendfd);
  460. if (conn->c_recvfd != -1)
  461. close(conn->c_recvfd);
  462. free(conn->c_path);
  463. free(conn);
  464. }
  465. static int
  466. connection_ready(struct ggd_connection *conn)
  467. {
  468. return (conn->c_sendfd != -1 && conn->c_recvfd != -1);
  469. }
  470. static void
  471. connection_launch(struct ggd_connection *conn)
  472. {
  473. pthread_t td;
  474. int error, pid;
  475. pid = fork();
  476. if (pid > 0)
  477. return;
  478. else if (pid == -1) {
  479. g_gate_log(LOG_ERR, "Cannot fork: %s.", strerror(errno));
  480. return;
  481. }
  482. g_gate_log(LOG_DEBUG, "Process created [%s].", conn->c_path);
  483. /*
  484. * Create condition variables and mutexes for in-queue and out-queue
  485. * synchronization.
  486. */
  487. error = pthread_mutex_init(&inqueue_mtx, NULL);
  488. if (error != 0) {
  489. g_gate_xlog("pthread_mutex_init(inqueue_mtx): %s.",
  490. strerror(error));
  491. }
  492. error = pthread_cond_init(&inqueue_cond, NULL);
  493. if (error != 0) {
  494. g_gate_xlog("pthread_cond_init(inqueue_cond): %s.",
  495. strerror(error));
  496. }
  497. error = pthread_mutex_init(&outqueue_mtx, NULL);
  498. if (error != 0) {
  499. g_gate_xlog("pthread_mutex_init(outqueue_mtx): %s.",
  500. strerror(error));
  501. }
  502. error = pthread_cond_init(&outqueue_cond, NULL);
  503. if (error != 0) {
  504. g_gate_xlog("pthread_cond_init(outqueue_cond): %s.",
  505. strerror(error));
  506. }
  507. /*
  508. * Create threads:
  509. * recvtd - thread for receiving I/O request
  510. * diskio - thread for doing I/O request
  511. * sendtd - thread for sending I/O requests back
  512. */
  513. error = pthread_create(&td, NULL, send_thread, conn);
  514. if (error != 0) {
  515. g_gate_xlog("pthread_create(send_thread): %s.",
  516. strerror(error));
  517. }
  518. error = pthread_create(&td, NULL, recv_thread, conn);
  519. if (error != 0) {
  520. g_gate_xlog("pthread_create(recv_thread): %s.",
  521. strerror(error));
  522. }
  523. disk_thread(conn);
  524. }
  525. static void
  526. sendfail(int sfd, int error, const char *fmt, ...)
  527. {
  528. struct g_gate_sinit sinit;
  529. va_list ap;
  530. ssize_t data;
  531. memset(&sinit, 0, sizeof(sinit));
  532. sinit.gs_error = error;
  533. g_gate_swap2n_sinit(&sinit);
  534. data = g_gate_send(sfd, &sinit, sizeof(sinit), 0);
  535. g_gate_swap2h_sinit(&sinit);
  536. if (data != sizeof(sinit)) {
  537. g_gate_log(LOG_WARNING, "Cannot send initial packet: %s.",
  538. strerror(errno));
  539. return;
  540. }
  541. if (fmt != NULL) {
  542. va_start(ap, fmt);
  543. g_gate_vlog(LOG_WARNING, fmt, ap);
  544. va_end(ap);
  545. }
  546. }
  547. static void *
  548. malloc_waitok(size_t size)
  549. {
  550. void *p;
  551. while ((p = malloc(size)) == NULL) {
  552. g_gate_log(LOG_DEBUG, "Cannot allocate %zu bytes.", size);
  553. sleep(1);
  554. }
  555. return (p);
  556. }
  557. static void *
  558. recv_thread(void *arg)
  559. {
  560. struct ggd_connection *conn;
  561. struct ggd_request *req;
  562. ssize_t data;
  563. int error, fd;
  564. conn = arg;
  565. g_gate_log(LOG_NOTICE, "%s: started [%s]!", __func__, conn->c_path);
  566. fd = conn->c_recvfd;
  567. for (;;) {
  568. /*
  569. * Get header packet.
  570. */
  571. req = malloc_waitok(sizeof(*req));
  572. data = g_gate_recv(fd, &req->r_hdr, sizeof(req->r_hdr),
  573. MSG_WAITALL);
  574. if (data == 0) {
  575. g_gate_log(LOG_DEBUG, "Process %u exiting.", getpid());
  576. exit(EXIT_SUCCESS);
  577. } else if (data == -1) {
  578. g_gate_xlog("Error while receiving hdr packet: %s.",
  579. strerror(errno));
  580. } else if (data != sizeof(req->r_hdr)) {
  581. g_gate_xlog("Malformed hdr packet received.");
  582. }
  583. g_gate_log(LOG_DEBUG, "Received hdr packet.");
  584. g_gate_swap2h_hdr(&req->r_hdr);
  585. g_gate_log(LOG_DEBUG, "%s: offset=%jd length=%u", __func__,
  586. (intmax_t)req->r_offset, (unsigned)req->r_length);
  587. /*
  588. * Allocate memory for data.
  589. */
  590. req->r_data = malloc_waitok(req->r_length);
  591. /*
  592. * Receive data to write for WRITE request.
  593. */
  594. if (req->r_cmd == GGATE_CMD_WRITE) {
  595. g_gate_log(LOG_DEBUG, "Waiting for %u bytes of data...",
  596. req->r_length);
  597. data = g_gate_recv(fd, req->r_data, req->r_length,
  598. MSG_WAITALL);
  599. if (data == -1) {
  600. g_gate_xlog("Error while receiving data: %s.",
  601. strerror(errno));
  602. }
  603. }
  604. /*
  605. * Put the request onto the incoming queue.
  606. */
  607. error = pthread_mutex_lock(&inqueue_mtx);
  608. assert(error == 0);
  609. TAILQ_INSERT_TAIL(&inqueue, req, r_next);
  610. error = pthread_cond_signal(&inqueue_cond);
  611. assert(error == 0);
  612. error = pthread_mutex_unlock(&inqueue_mtx);
  613. assert(error == 0);
  614. }
  615. }
  616. static void *
  617. disk_thread(void *arg)
  618. {
  619. struct ggd_connection *conn;
  620. struct ggd_request *req;
  621. ssize_t data;
  622. int error, fd;
  623. conn = arg;
  624. g_gate_log(LOG_NOTICE, "%s: started [%s]!", __func__, conn->c_path);
  625. fd = conn->c_diskfd;
  626. for (;;) {
  627. /*
  628. * Get a request from the incoming queue.
  629. */
  630. error = pthread_mutex_lock(&inqueue_mtx);
  631. assert(error == 0);
  632. while ((req = TAILQ_FIRST(&inqueue)) == NULL) {
  633. error = pthread_cond_wait(&inqueue_cond, &inqueue_mtx);
  634. assert(error == 0);
  635. }
  636. TAILQ_REMOVE(&inqueue, req, r_next);
  637. error = pthread_mutex_unlock(&inqueue_mtx);
  638. assert(error == 0);
  639. /*
  640. * Check the request.
  641. */
  642. assert(req->r_cmd == GGATE_CMD_READ || req->r_cmd == GGATE_CMD_WRITE);
  643. assert(req->r_offset + req->r_length <= (uintmax_t)conn->c_mediasize);
  644. assert((req->r_offset % conn->c_sectorsize) == 0);
  645. assert((req->r_length % conn->c_sectorsize) == 0);
  646. g_gate_log(LOG_DEBUG, "%s: offset=%jd length=%u", __func__,
  647. (intmax_t)req->r_offset, (unsigned)req->r_length);
  648. /*
  649. * Do the request.
  650. */
  651. data = 0;
  652. switch (req->r_cmd) {
  653. case GGATE_CMD_READ:
  654. data = pread(fd, req->r_data, req->r_length,
  655. req->r_offset);
  656. break;
  657. case GGATE_CMD_WRITE:
  658. data = pwrite(fd, req->r_data, req->r_length,
  659. req->r_offset);
  660. /* Free data memory here - better sooner. */
  661. free(req->r_data);
  662. req->r_data = NULL;
  663. break;
  664. }
  665. if (data != (ssize_t)req->r_length) {
  666. /* Report short reads/writes as I/O errors. */
  667. if (errno == 0)
  668. errno = EIO;
  669. g_gate_log(LOG_ERR, "Disk error: %s", strerror(errno));
  670. req->r_error = errno;
  671. if (req->r_data != NULL) {
  672. free(req->r_data);
  673. req->r_data = NULL;
  674. }
  675. }
  676. /*
  677. * Put the request onto the outgoing queue.
  678. */
  679. error = pthread_mutex_lock(&outqueue_mtx);
  680. assert(error == 0);
  681. TAILQ_INSERT_TAIL(&outqueue, req, r_next);
  682. error = pthread_cond_signal(&outqueue_cond);
  683. assert(error == 0);
  684. error = pthread_mutex_unlock(&outqueue_mtx);
  685. assert(error == 0);
  686. }
  687. /* NOTREACHED */
  688. return (NULL);
  689. }
  690. static void *
  691. send_thread(void *arg)
  692. {
  693. struct ggd_connection *conn;
  694. struct ggd_request *req;
  695. ssize_t data;
  696. int error, fd;
  697. conn = arg;
  698. g_gate_log(LOG_NOTICE, "%s: started [%s]!", __func__, conn->c_path);
  699. fd = conn->c_sendfd;
  700. for (;;) {
  701. /*
  702. * Get a request from the outgoing queue.
  703. */
  704. error = pthread_mutex_lock(&outqueue_mtx);
  705. assert(error == 0);
  706. while ((req = TAILQ_FIRST(&outqueue)) == NULL) {
  707. error = pthread_cond_wait(&outqueue_cond,
  708. &outqueue_mtx);
  709. assert(error == 0);
  710. }
  711. TAILQ_REMOVE(&outqueue, req, r_next);
  712. error = pthread_mutex_unlock(&outqueue_mtx);
  713. assert(error == 0);
  714. g_gate_log(LOG_DEBUG, "%s: offset=%jd length=%u", __func__,
  715. (intmax_t)req->r_offset, (unsigned)req->r_length);
  716. /*
  717. * Send the request.
  718. */
  719. g_gate_swap2n_hdr(&req->r_hdr);
  720. if (g_gate_send(fd, &req->r_hdr, sizeof(req->r_hdr), 0) == -1) {
  721. g_gate_xlog("Error while sending hdr packet: %s.",
  722. strerror(errno));
  723. }
  724. g_gate_log(LOG_DEBUG, "Sent hdr packet.");
  725. g_gate_swap2h_hdr(&req->r_hdr);
  726. if (req->r_data != NULL) {
  727. data = g_gate_send(fd, req->r_data, req->r_length, 0);
  728. if (data != (ssize_t)req->r_length) {
  729. g_gate_xlog("Error while sending data: %s.",
  730. strerror(errno));
  731. }
  732. g_gate_log(LOG_DEBUG,
  733. "Sent %zd bytes (offset=%ju, size=%zu).", data,
  734. (uintmax_t)req->r_offset, (size_t)req->r_length);
  735. free(req->r_data);
  736. }
  737. free(req);
  738. }
  739. /* NOTREACHED */
  740. return (NULL);
  741. }
  742. static void
  743. log_connection(struct sockaddr *from)
  744. {
  745. in_addr_t ip;
  746. ip = htonl(((struct sockaddr_in *)(void *)from)->sin_addr.s_addr);
  747. g_gate_log(LOG_INFO, "Connection from: %s.", ip2str(ip));
  748. }
  749. static int
  750. handshake(struct sockaddr *from, int sfd)
  751. {
  752. struct g_gate_version ver;
  753. struct g_gate_cinit cinit;
  754. struct g_gate_sinit sinit;
  755. struct ggd_connection *conn;
  756. struct ggd_export *ex;
  757. ssize_t data;
  758. log_connection(from);
  759. /*
  760. * Phase 1: Version verification.
  761. */
  762. g_gate_log(LOG_DEBUG, "Receiving version packet.");
  763. data = g_gate_recv(sfd, &ver, sizeof(ver), MSG_WAITALL);
  764. g_gate_swap2h_version(&ver);
  765. if (data != sizeof(ver)) {
  766. g_gate_log(LOG_WARNING, "Malformed version packet.");
  767. return (0);
  768. }
  769. g_gate_log(LOG_DEBUG, "Version packet received.");
  770. if (memcmp(ver.gv_magic, GGATE_MAGIC, strlen(GGATE_MAGIC)) != 0) {
  771. g_gate_log(LOG_WARNING, "Invalid magic field.");
  772. return (0);
  773. }
  774. if (ver.gv_version != GGATE_VERSION) {
  775. g_gate_log(LOG_WARNING, "Version %u is not supported.",
  776. ver.gv_version);
  777. return (0);
  778. }
  779. ver.gv_error = 0;
  780. g_gate_swap2n_version(&ver);
  781. data = g_gate_send(sfd, &ver, sizeof(ver), 0);
  782. g_gate_swap2h_version(&ver);
  783. if (data == -1) {
  784. sendfail(sfd, errno, "Error while sending version packet: %s.",
  785. strerror(errno));
  786. return (0);
  787. }
  788. /*
  789. * Phase 2: Request verification.
  790. */
  791. g_gate_log(LOG_DEBUG, "Receiving initial packet.");
  792. data = g_gate_recv(sfd, &cinit, sizeof(cinit), MSG_WAITALL);
  793. g_gate_swap2h_cinit(&cinit);
  794. if (data != sizeof(cinit)) {
  795. g_gate_log(LOG_WARNING, "Malformed initial packet.");
  796. return (0);
  797. }
  798. g_gate_log(LOG_DEBUG, "Initial packet received.");
  799. conn = connection_find(&cinit);
  800. if (conn != NULL) {
  801. /*
  802. * Connection should already exists.
  803. */
  804. g_gate_log(LOG_DEBUG, "Found existing connection (token=%lu).",
  805. (unsigned long)conn->c_token);
  806. if (connection_add(conn, &cinit, from, sfd) == -1) {
  807. connection_remove(conn);
  808. return (0);
  809. }
  810. } else {
  811. /*
  812. * New connection, allocate space.
  813. */
  814. conn = connection_new(&cinit, from, sfd);
  815. if (conn == NULL) {
  816. sendfail(sfd, ENOMEM,
  817. "Cannot allocate new connection.");
  818. return (0);
  819. }
  820. g_gate_log(LOG_DEBUG, "New connection created (token=%lu).",
  821. (unsigned long)conn->c_token);
  822. }
  823. ex = exports_find(from, &cinit, conn);
  824. if (ex == NULL) {
  825. sendfail(sfd, errno, NULL);
  826. connection_remove(conn);
  827. return (0);
  828. }
  829. if (conn->c_mediasize == 0) {
  830. conn->c_mediasize = g_gate_mediasize(conn->c_diskfd);
  831. conn->c_sectorsize = g_gate_sectorsize(conn->c_diskfd);
  832. }
  833. sinit.gs_mediasize = conn->c_mediasize;
  834. sinit.gs_sectorsize = conn->c_sectorsize;
  835. sinit.gs_error = 0;
  836. g_gate_log(LOG_DEBUG, "Sending initial packet.");
  837. g_gate_swap2n_sinit(&sinit);
  838. data = g_gate_send(sfd, &sinit, sizeof(sinit), 0);
  839. g_gate_swap2h_sinit(&sinit);
  840. if (data == -1) {
  841. sendfail(sfd, errno, "Error while sending initial packet: %s.",
  842. strerror(errno));
  843. return (0);
  844. }
  845. if (connection_ready(conn)) {
  846. connection_launch(conn);
  847. connection_remove(conn);
  848. }
  849. return (1);
  850. }
  851. static void
  852. huphandler(int sig __unused)
  853. {
  854. got_sighup = 1;
  855. }
  856. int
  857. main(int argc, char *argv[])
  858. {
  859. const char *ggated_pidfile = _PATH_VARRUN "/ggated.pid";
  860. struct pidfh *pfh;
  861. struct sockaddr_in serv;
  862. struct sockaddr from;
  863. socklen_t fromlen;
  864. pid_t otherpid;
  865. int ch, sfd, tmpsfd;
  866. unsigned port;
  867. bindaddr = htonl(INADDR_ANY);
  868. port = G_GATE_PORT;
  869. while ((ch = getopt(argc, argv, "a:hnp:F:R:S:v")) != -1) {
  870. switch (ch) {
  871. case 'a':
  872. bindaddr = g_gate_str2ip(optarg);
  873. if (bindaddr == INADDR_NONE) {
  874. errx(EXIT_FAILURE,
  875. "Invalid IP/host name to bind to.");
  876. }
  877. break;
  878. case 'F':
  879. ggated_pidfile = optarg;
  880. break;
  881. case 'n':
  882. nagle = 0;
  883. break;
  884. case 'p':
  885. errno = 0;
  886. port = strtoul(optarg, NULL, 10);
  887. if (port == 0 && errno != 0)
  888. errx(EXIT_FAILURE, "Invalid port.");
  889. break;
  890. case 'R':
  891. errno = 0;
  892. rcvbuf = strtoul(optarg, NULL, 10);
  893. if (rcvbuf == 0 && errno != 0)
  894. errx(EXIT_FAILURE, "Invalid rcvbuf.");
  895. break;
  896. case 'S':
  897. errno = 0;
  898. sndbuf = strtoul(optarg, NULL, 10);
  899. if (sndbuf == 0 && errno != 0)
  900. errx(EXIT_FAILURE, "Invalid sndbuf.");
  901. break;
  902. case 'v':
  903. g_gate_verbose++;
  904. break;
  905. case 'h':
  906. default:
  907. usage();
  908. }
  909. }
  910. argc -= optind;
  911. argv += optind;
  912. if (argv[0] != NULL)
  913. exports_file = argv[0];
  914. exports_get();
  915. pfh = pidfile_open(ggated_pidfile, 0600, &otherpid);
  916. if (pfh == NULL) {
  917. if (errno == EEXIST) {
  918. errx(EXIT_FAILURE, "Daemon already running, pid: %jd.",
  919. (intmax_t)otherpid);
  920. }
  921. err(EXIT_FAILURE, "Cannot open/create pidfile");
  922. }
  923. if (!g_gate_verbose) {
  924. /* Run in daemon mode. */
  925. if (daemon(0, 0) == -1)
  926. g_gate_xlog("Cannot daemonize: %s", strerror(errno));
  927. }
  928. pidfile_write(pfh);
  929. signal(SIGCHLD, SIG_IGN);
  930. sfd = socket(AF_INET, SOCK_STREAM, 0);
  931. if (sfd == -1)
  932. g_gate_xlog("Cannot open stream socket: %s.", strerror(errno));
  933. bzero(&serv, sizeof(serv));
  934. serv.sin_family = AF_INET;
  935. serv.sin_addr.s_addr = bindaddr;
  936. serv.sin_port = htons(port);
  937. g_gate_socket_settings(sfd);
  938. if (bind(sfd, (struct sockaddr *)&serv, sizeof(serv)) == -1)
  939. g_gate_xlog("bind(): %s.", strerror(errno));
  940. if (listen(sfd, 5) == -1)
  941. g_gate_xlog("listen(): %s.", strerror(errno));
  942. g_gate_log(LOG_INFO, "Listen on port: %d.", port);
  943. signal(SIGHUP, huphandler);
  944. for (;;) {
  945. fromlen = sizeof(from);
  946. tmpsfd = accept(sfd, &from, &fromlen);
  947. if (tmpsfd == -1)
  948. g_gate_xlog("accept(): %s.", strerror(errno));
  949. if (got_sighup) {
  950. got_sighup = 0;
  951. exports_get();
  952. }
  953. if (!handshake(&from, tmpsfd))
  954. close(tmpsfd);
  955. }
  956. close(sfd);
  957. pidfile_remove(pfh);
  958. exit(EXIT_SUCCESS);
  959. }