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.
 
 
 
 

1068 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. sinit.gs_error = error;
  532. g_gate_swap2n_sinit(&sinit);
  533. data = g_gate_send(sfd, &sinit, sizeof(sinit), 0);
  534. g_gate_swap2h_sinit(&sinit);
  535. if (data != sizeof(sinit)) {
  536. g_gate_log(LOG_WARNING, "Cannot send initial packet: %s.",
  537. strerror(errno));
  538. return;
  539. }
  540. if (fmt != NULL) {
  541. va_start(ap, fmt);
  542. g_gate_vlog(LOG_WARNING, fmt, ap);
  543. va_end(ap);
  544. }
  545. }
  546. static void *
  547. malloc_waitok(size_t size)
  548. {
  549. void *p;
  550. while ((p = malloc(size)) == NULL) {
  551. g_gate_log(LOG_DEBUG, "Cannot allocate %zu bytes.", size);
  552. sleep(1);
  553. }
  554. return (p);
  555. }
  556. static void *
  557. recv_thread(void *arg)
  558. {
  559. struct ggd_connection *conn;
  560. struct ggd_request *req;
  561. ssize_t data;
  562. int error, fd;
  563. conn = arg;
  564. g_gate_log(LOG_NOTICE, "%s: started [%s]!", __func__, conn->c_path);
  565. fd = conn->c_recvfd;
  566. for (;;) {
  567. /*
  568. * Get header packet.
  569. */
  570. req = malloc_waitok(sizeof(*req));
  571. data = g_gate_recv(fd, &req->r_hdr, sizeof(req->r_hdr),
  572. MSG_WAITALL);
  573. if (data == 0) {
  574. g_gate_log(LOG_DEBUG, "Process %u exiting.", getpid());
  575. exit(EXIT_SUCCESS);
  576. } else if (data == -1) {
  577. g_gate_xlog("Error while receiving hdr packet: %s.",
  578. strerror(errno));
  579. } else if (data != sizeof(req->r_hdr)) {
  580. g_gate_xlog("Malformed hdr packet received.");
  581. }
  582. g_gate_log(LOG_DEBUG, "Received hdr packet.");
  583. g_gate_swap2h_hdr(&req->r_hdr);
  584. g_gate_log(LOG_DEBUG, "%s: offset=%jd length=%u", __func__,
  585. (intmax_t)req->r_offset, (unsigned)req->r_length);
  586. /*
  587. * Allocate memory for data.
  588. */
  589. req->r_data = malloc_waitok(req->r_length);
  590. /*
  591. * Receive data to write for WRITE request.
  592. */
  593. if (req->r_cmd == GGATE_CMD_WRITE) {
  594. g_gate_log(LOG_DEBUG, "Waiting for %u bytes of data...",
  595. req->r_length);
  596. data = g_gate_recv(fd, req->r_data, req->r_length,
  597. MSG_WAITALL);
  598. if (data == -1) {
  599. g_gate_xlog("Error while receiving data: %s.",
  600. strerror(errno));
  601. }
  602. }
  603. /*
  604. * Put the request onto the incoming queue.
  605. */
  606. error = pthread_mutex_lock(&inqueue_mtx);
  607. assert(error == 0);
  608. TAILQ_INSERT_TAIL(&inqueue, req, r_next);
  609. error = pthread_cond_signal(&inqueue_cond);
  610. assert(error == 0);
  611. error = pthread_mutex_unlock(&inqueue_mtx);
  612. assert(error == 0);
  613. }
  614. }
  615. static void *
  616. disk_thread(void *arg)
  617. {
  618. struct ggd_connection *conn;
  619. struct ggd_request *req;
  620. ssize_t data;
  621. int error, fd;
  622. conn = arg;
  623. g_gate_log(LOG_NOTICE, "%s: started [%s]!", __func__, conn->c_path);
  624. fd = conn->c_diskfd;
  625. for (;;) {
  626. /*
  627. * Get a request from the incoming queue.
  628. */
  629. error = pthread_mutex_lock(&inqueue_mtx);
  630. assert(error == 0);
  631. while ((req = TAILQ_FIRST(&inqueue)) == NULL) {
  632. error = pthread_cond_wait(&inqueue_cond, &inqueue_mtx);
  633. assert(error == 0);
  634. }
  635. TAILQ_REMOVE(&inqueue, req, r_next);
  636. error = pthread_mutex_unlock(&inqueue_mtx);
  637. assert(error == 0);
  638. /*
  639. * Check the request.
  640. */
  641. assert(req->r_cmd == GGATE_CMD_READ || req->r_cmd == GGATE_CMD_WRITE);
  642. assert(req->r_offset + req->r_length <= (uintmax_t)conn->c_mediasize);
  643. assert((req->r_offset % conn->c_sectorsize) == 0);
  644. assert((req->r_length % conn->c_sectorsize) == 0);
  645. g_gate_log(LOG_DEBUG, "%s: offset=%jd length=%u", __func__,
  646. (intmax_t)req->r_offset, (unsigned)req->r_length);
  647. /*
  648. * Do the request.
  649. */
  650. data = 0;
  651. switch (req->r_cmd) {
  652. case GGATE_CMD_READ:
  653. data = pread(fd, req->r_data, req->r_length,
  654. req->r_offset);
  655. break;
  656. case GGATE_CMD_WRITE:
  657. data = pwrite(fd, req->r_data, req->r_length,
  658. req->r_offset);
  659. /* Free data memory here - better sooner. */
  660. free(req->r_data);
  661. req->r_data = NULL;
  662. break;
  663. }
  664. if (data != (ssize_t)req->r_length) {
  665. /* Report short reads/writes as I/O errors. */
  666. if (errno == 0)
  667. errno = EIO;
  668. g_gate_log(LOG_ERR, "Disk error: %s", strerror(errno));
  669. req->r_error = errno;
  670. if (req->r_data != NULL) {
  671. free(req->r_data);
  672. req->r_data = NULL;
  673. }
  674. }
  675. /*
  676. * Put the request onto the outgoing queue.
  677. */
  678. error = pthread_mutex_lock(&outqueue_mtx);
  679. assert(error == 0);
  680. TAILQ_INSERT_TAIL(&outqueue, req, r_next);
  681. error = pthread_cond_signal(&outqueue_cond);
  682. assert(error == 0);
  683. error = pthread_mutex_unlock(&outqueue_mtx);
  684. assert(error == 0);
  685. }
  686. /* NOTREACHED */
  687. return (NULL);
  688. }
  689. static void *
  690. send_thread(void *arg)
  691. {
  692. struct ggd_connection *conn;
  693. struct ggd_request *req;
  694. ssize_t data;
  695. int error, fd;
  696. conn = arg;
  697. g_gate_log(LOG_NOTICE, "%s: started [%s]!", __func__, conn->c_path);
  698. fd = conn->c_sendfd;
  699. for (;;) {
  700. /*
  701. * Get a request from the outgoing queue.
  702. */
  703. error = pthread_mutex_lock(&outqueue_mtx);
  704. assert(error == 0);
  705. while ((req = TAILQ_FIRST(&outqueue)) == NULL) {
  706. error = pthread_cond_wait(&outqueue_cond,
  707. &outqueue_mtx);
  708. assert(error == 0);
  709. }
  710. TAILQ_REMOVE(&outqueue, req, r_next);
  711. error = pthread_mutex_unlock(&outqueue_mtx);
  712. assert(error == 0);
  713. g_gate_log(LOG_DEBUG, "%s: offset=%jd length=%u", __func__,
  714. (intmax_t)req->r_offset, (unsigned)req->r_length);
  715. /*
  716. * Send the request.
  717. */
  718. g_gate_swap2n_hdr(&req->r_hdr);
  719. if (g_gate_send(fd, &req->r_hdr, sizeof(req->r_hdr), 0) == -1) {
  720. g_gate_xlog("Error while sending hdr packet: %s.",
  721. strerror(errno));
  722. }
  723. g_gate_log(LOG_DEBUG, "Sent hdr packet.");
  724. g_gate_swap2h_hdr(&req->r_hdr);
  725. if (req->r_data != NULL) {
  726. data = g_gate_send(fd, req->r_data, req->r_length, 0);
  727. if (data != (ssize_t)req->r_length) {
  728. g_gate_xlog("Error while sending data: %s.",
  729. strerror(errno));
  730. }
  731. g_gate_log(LOG_DEBUG,
  732. "Sent %zd bytes (offset=%ju, size=%zu).", data,
  733. (uintmax_t)req->r_offset, (size_t)req->r_length);
  734. free(req->r_data);
  735. }
  736. free(req);
  737. }
  738. /* NOTREACHED */
  739. return (NULL);
  740. }
  741. static void
  742. log_connection(struct sockaddr *from)
  743. {
  744. in_addr_t ip;
  745. ip = htonl(((struct sockaddr_in *)(void *)from)->sin_addr.s_addr);
  746. g_gate_log(LOG_INFO, "Connection from: %s.", ip2str(ip));
  747. }
  748. static int
  749. handshake(struct sockaddr *from, int sfd)
  750. {
  751. struct g_gate_version ver;
  752. struct g_gate_cinit cinit;
  753. struct g_gate_sinit sinit;
  754. struct ggd_connection *conn;
  755. struct ggd_export *ex;
  756. ssize_t data;
  757. log_connection(from);
  758. /*
  759. * Phase 1: Version verification.
  760. */
  761. g_gate_log(LOG_DEBUG, "Receiving version packet.");
  762. data = g_gate_recv(sfd, &ver, sizeof(ver), MSG_WAITALL);
  763. g_gate_swap2h_version(&ver);
  764. if (data != sizeof(ver)) {
  765. g_gate_log(LOG_WARNING, "Malformed version packet.");
  766. return (0);
  767. }
  768. g_gate_log(LOG_DEBUG, "Version packet received.");
  769. if (memcmp(ver.gv_magic, GGATE_MAGIC, strlen(GGATE_MAGIC)) != 0) {
  770. g_gate_log(LOG_WARNING, "Invalid magic field.");
  771. return (0);
  772. }
  773. if (ver.gv_version != GGATE_VERSION) {
  774. g_gate_log(LOG_WARNING, "Version %u is not supported.",
  775. ver.gv_version);
  776. return (0);
  777. }
  778. ver.gv_error = 0;
  779. g_gate_swap2n_version(&ver);
  780. data = g_gate_send(sfd, &ver, sizeof(ver), 0);
  781. g_gate_swap2h_version(&ver);
  782. if (data == -1) {
  783. sendfail(sfd, errno, "Error while sending version packet: %s.",
  784. strerror(errno));
  785. return (0);
  786. }
  787. /*
  788. * Phase 2: Request verification.
  789. */
  790. g_gate_log(LOG_DEBUG, "Receiving initial packet.");
  791. data = g_gate_recv(sfd, &cinit, sizeof(cinit), MSG_WAITALL);
  792. g_gate_swap2h_cinit(&cinit);
  793. if (data != sizeof(cinit)) {
  794. g_gate_log(LOG_WARNING, "Malformed initial packet.");
  795. return (0);
  796. }
  797. g_gate_log(LOG_DEBUG, "Initial packet received.");
  798. conn = connection_find(&cinit);
  799. if (conn != NULL) {
  800. /*
  801. * Connection should already exists.
  802. */
  803. g_gate_log(LOG_DEBUG, "Found existing connection (token=%lu).",
  804. (unsigned long)conn->c_token);
  805. if (connection_add(conn, &cinit, from, sfd) == -1) {
  806. connection_remove(conn);
  807. return (0);
  808. }
  809. } else {
  810. /*
  811. * New connection, allocate space.
  812. */
  813. conn = connection_new(&cinit, from, sfd);
  814. if (conn == NULL) {
  815. sendfail(sfd, ENOMEM,
  816. "Cannot allocate new connection.");
  817. return (0);
  818. }
  819. g_gate_log(LOG_DEBUG, "New connection created (token=%lu).",
  820. (unsigned long)conn->c_token);
  821. }
  822. ex = exports_find(from, &cinit, conn);
  823. if (ex == NULL) {
  824. sendfail(sfd, errno, NULL);
  825. connection_remove(conn);
  826. return (0);
  827. }
  828. if (conn->c_mediasize == 0) {
  829. conn->c_mediasize = g_gate_mediasize(conn->c_diskfd);
  830. conn->c_sectorsize = g_gate_sectorsize(conn->c_diskfd);
  831. }
  832. sinit.gs_mediasize = conn->c_mediasize;
  833. sinit.gs_sectorsize = conn->c_sectorsize;
  834. sinit.gs_error = 0;
  835. g_gate_log(LOG_DEBUG, "Sending initial packet.");
  836. g_gate_swap2n_sinit(&sinit);
  837. data = g_gate_send(sfd, &sinit, sizeof(sinit), 0);
  838. g_gate_swap2h_sinit(&sinit);
  839. if (data == -1) {
  840. sendfail(sfd, errno, "Error while sending initial packet: %s.",
  841. strerror(errno));
  842. return (0);
  843. }
  844. if (connection_ready(conn)) {
  845. connection_launch(conn);
  846. connection_remove(conn);
  847. }
  848. return (1);
  849. }
  850. static void
  851. huphandler(int sig __unused)
  852. {
  853. got_sighup = 1;
  854. }
  855. int
  856. main(int argc, char *argv[])
  857. {
  858. const char *ggated_pidfile = _PATH_VARRUN "/ggated.pid";
  859. struct pidfh *pfh;
  860. struct sockaddr_in serv;
  861. struct sockaddr from;
  862. socklen_t fromlen;
  863. pid_t otherpid;
  864. int ch, sfd, tmpsfd;
  865. unsigned port;
  866. bindaddr = htonl(INADDR_ANY);
  867. port = G_GATE_PORT;
  868. while ((ch = getopt(argc, argv, "a:hnp:F:R:S:v")) != -1) {
  869. switch (ch) {
  870. case 'a':
  871. bindaddr = g_gate_str2ip(optarg);
  872. if (bindaddr == INADDR_NONE) {
  873. errx(EXIT_FAILURE,
  874. "Invalid IP/host name to bind to.");
  875. }
  876. break;
  877. case 'F':
  878. ggated_pidfile = optarg;
  879. break;
  880. case 'n':
  881. nagle = 0;
  882. break;
  883. case 'p':
  884. errno = 0;
  885. port = strtoul(optarg, NULL, 10);
  886. if (port == 0 && errno != 0)
  887. errx(EXIT_FAILURE, "Invalid port.");
  888. break;
  889. case 'R':
  890. errno = 0;
  891. rcvbuf = strtoul(optarg, NULL, 10);
  892. if (rcvbuf == 0 && errno != 0)
  893. errx(EXIT_FAILURE, "Invalid rcvbuf.");
  894. break;
  895. case 'S':
  896. errno = 0;
  897. sndbuf = strtoul(optarg, NULL, 10);
  898. if (sndbuf == 0 && errno != 0)
  899. errx(EXIT_FAILURE, "Invalid sndbuf.");
  900. break;
  901. case 'v':
  902. g_gate_verbose++;
  903. break;
  904. case 'h':
  905. default:
  906. usage();
  907. }
  908. }
  909. argc -= optind;
  910. argv += optind;
  911. if (argv[0] != NULL)
  912. exports_file = argv[0];
  913. exports_get();
  914. pfh = pidfile_open(ggated_pidfile, 0600, &otherpid);
  915. if (pfh == NULL) {
  916. if (errno == EEXIST) {
  917. errx(EXIT_FAILURE, "Daemon already running, pid: %jd.",
  918. (intmax_t)otherpid);
  919. }
  920. err(EXIT_FAILURE, "Cannot open/create pidfile");
  921. }
  922. if (!g_gate_verbose) {
  923. /* Run in daemon mode. */
  924. if (daemon(0, 0) == -1)
  925. g_gate_xlog("Cannot daemonize: %s", strerror(errno));
  926. }
  927. pidfile_write(pfh);
  928. signal(SIGCHLD, SIG_IGN);
  929. sfd = socket(AF_INET, SOCK_STREAM, 0);
  930. if (sfd == -1)
  931. g_gate_xlog("Cannot open stream socket: %s.", strerror(errno));
  932. bzero(&serv, sizeof(serv));
  933. serv.sin_family = AF_INET;
  934. serv.sin_addr.s_addr = bindaddr;
  935. serv.sin_port = htons(port);
  936. g_gate_socket_settings(sfd);
  937. if (bind(sfd, (struct sockaddr *)&serv, sizeof(serv)) == -1)
  938. g_gate_xlog("bind(): %s.", strerror(errno));
  939. if (listen(sfd, 5) == -1)
  940. g_gate_xlog("listen(): %s.", strerror(errno));
  941. g_gate_log(LOG_INFO, "Listen on port: %d.", port);
  942. signal(SIGHUP, huphandler);
  943. for (;;) {
  944. fromlen = sizeof(from);
  945. tmpsfd = accept(sfd, &from, &fromlen);
  946. if (tmpsfd == -1)
  947. g_gate_xlog("accept(): %s.", strerror(errno));
  948. if (got_sighup) {
  949. got_sighup = 0;
  950. exports_get();
  951. }
  952. if (!handshake(&from, tmpsfd))
  953. close(tmpsfd);
  954. }
  955. close(sfd);
  956. pidfile_remove(pfh);
  957. exit(EXIT_SUCCESS);
  958. }