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.
 
 
 
 

1066 lines
25 KiB

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