share.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /* $Id: share.c,v 1.15 2004/02/26 22:48:08 dijkstra Exp $ */
  2. /*
  3. * Copyright (c) 2001-2004 Willem Dijkstra
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * - Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * - Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following
  14. * disclaimer in the documentation and/or other materials provided
  15. * with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. * POSSIBILITY OF SUCH DAMAGE.
  29. *
  30. */
  31. /* Share contains all routines needed for the ipc between symuxes */
  32. #include <sys/types.h>
  33. #include <sys/ipc.h>
  34. #include <sys/sem.h>
  35. #include <sys/shm.h>
  36. #include <sys/wait.h>
  37. #include <errno.h>
  38. #include <netdb.h>
  39. #include <signal.h>
  40. #include <string.h>
  41. #include <stdlib.h>
  42. #include <sysexits.h>
  43. #include <unistd.h>
  44. #include "data.h"
  45. #include "error.h"
  46. #include "symuxnet.h"
  47. #include "share.h"
  48. #include "net.h"
  49. /* Shared operation:
  50. *
  51. * The moment the master symux receives a new packet:
  52. *
  53. * master calls master_forbidread:
  54. * - master checks the 'SEM_READ' semaphore to be equal to the number of
  55. * children active. If so, all children are up to date. If not, a child is
  56. * lagging and will die soon. Reap_clients().
  57. * - master adds any pending new clients
  58. * - master resets all semaphores, preventing clients to start reading
  59. *
  60. * master calls master_permitread:
  61. * - increment sequence number in the shared region
  62. * - increment 'SEM_WAIT' with the number of registered clients
  63. *
  64. * clients call client_waitread:
  65. * - block on semaphore 'SEM_WAIT'
  66. * - set client sequence number to shared region sequence number
  67. *
  68. * clients do something to the data in the shared region
  69. *
  70. * clients call client_doneread:
  71. * - If the recorded sequence number deviates from the one in the shared region
  72. * the client is lagging behind. The client will kill itself.
  73. * - The client increments 'SEM_READ'.
  74. *
  75. */
  76. __BEGIN_DECLS
  77. int recvfd(int);
  78. int sendfd(int, int);
  79. void check_master();
  80. void check_sem();
  81. void client_doneread();
  82. void client_loop();
  83. void client_signalhandler();
  84. void client_waitread();
  85. void exitmaster();
  86. void master_resetsem();
  87. void reap_clients();
  88. __END_DECLS
  89. #define SEM_WAIT 0 /* wait semaphore */
  90. #define SEM_READ 1 /* have read semaphore */
  91. #define SEM_TOTAL 2
  92. int realclients; /* number of clients active */
  93. int newclients;
  94. int master; /* is current process master or child */
  95. int clientsock; /* connected client */
  96. pid_t clientpid;
  97. enum ipcstat {
  98. SIPC_FREE, SIPC_KEYED, SIPC_ATTACHED
  99. };
  100. key_t shmid;
  101. struct sharedregion *shm;
  102. enum ipcstat shmstat;
  103. key_t semid;
  104. enum ipcstat semstat;
  105. int seqnr;
  106. /* Get start of data in shared region */
  107. long *
  108. shared_getmem()
  109. {
  110. return &shm->data;
  111. }
  112. /* Get max length of data stored in shared region */
  113. long
  114. shared_getmaxlen()
  115. {
  116. return shm->reglen - sizeof(struct sharedregion);
  117. }
  118. /* Set length of data stored in shared region */
  119. void
  120. shared_setlen(long length)
  121. {
  122. if (length > (shm->reglen - (long) sizeof(struct sharedregion)))
  123. fatal("%s:%d: internal error:"
  124. "set_length of shared region called with value larger than actual size",
  125. __FILE__, __LINE__);
  126. shm->ctlen = length;
  127. }
  128. /* Get length of data stored in shared region */
  129. long
  130. shared_getlen()
  131. {
  132. return shm->ctlen;
  133. }
  134. /* Check whether semaphore is available */
  135. void
  136. check_sem()
  137. {
  138. if (semstat != SIPC_KEYED)
  139. fatal("%s:%d: internal error: semaphore not available",
  140. __FILE__, __LINE__);
  141. }
  142. /* Check whether process is the master process */
  143. void
  144. check_master()
  145. {
  146. if (master == 0)
  147. fatal("%s:%d: internal error: child process tried to access master routines",
  148. __FILE__, __LINE__);
  149. }
  150. /* Reset semaphores before each distribution cycle */
  151. void
  152. master_resetsem()
  153. {
  154. union semun semarg;
  155. semarg.val = 0;
  156. check_sem();
  157. check_master();
  158. if ((semctl(semid, SEM_WAIT, SETVAL, semarg) != 0) ||
  159. (semctl(semid, SEM_READ, SETVAL, semarg) != 0))
  160. fatal("%s:%d: internal error: cannot reset semaphores",
  161. __FILE__, __LINE__);
  162. }
  163. /* Prepare for writing to shm */
  164. void
  165. master_forbidread()
  166. {
  167. int clientsread;
  168. union semun semarg;
  169. check_sem();
  170. check_master();
  171. /* prepare for a new read */
  172. semarg.val = 0;
  173. if ((clientsread = semctl(semid, SEM_READ, GETVAL, semarg)) < 0)
  174. fatal("%s:%d: internal error: cannot read semaphore",
  175. __FILE__, __LINE__);
  176. if (clientsread != realclients) {
  177. reap_clients();
  178. debug("realclients = %d; clientsread = %d", realclients, clientsread);
  179. }
  180. /* add new clients */
  181. realclients += newclients;
  182. newclients = 0;
  183. master_resetsem();
  184. }
  185. /* Signal 'permit read' to all clients */
  186. void
  187. master_permitread()
  188. {
  189. union semun semarg;
  190. shm->seqnr++;
  191. semarg.val = realclients;
  192. if (semctl(semid, SEM_WAIT, SETVAL, semarg) != 0)
  193. fatal("%s:%d: internal error: cannot reset semaphores",
  194. __FILE__, __LINE__);
  195. }
  196. /* Make clients wait until master signals */
  197. void
  198. client_waitread()
  199. {
  200. struct sembuf sops;
  201. check_sem();
  202. sops.sem_num = SEM_WAIT;
  203. sops.sem_op = -1;
  204. sops.sem_flg = 0;
  205. if (semop(semid, &sops, 1) != 0)
  206. fatal("%s:%d: internal error: client(%d): cannot obtain semaphore (%.200s)",
  207. __FILE__, __LINE__, clientpid, strerror(errno));
  208. seqnr = shm->seqnr;
  209. }
  210. /* Client signal 'done reading' to master */
  211. void
  212. client_doneread()
  213. {
  214. struct sembuf sops;
  215. check_sem();
  216. if (seqnr != shm->seqnr) {
  217. close(clientsock);
  218. fatal("%s:%d: client(%d) lagging behind (%d, %d) = high load?",
  219. __FILE__, __LINE__, clientpid, seqnr, shm->seqnr);
  220. }
  221. sops.sem_num = SEM_READ;
  222. sops.sem_op = 1;
  223. sops.sem_flg = IPC_NOWAIT;
  224. if (semop(semid, &sops, 1) != 0)
  225. fatal("%s:%d: internal error: cannot release semaphore (%.200s)",
  226. __FILE__, __LINE__, strerror(errno));
  227. /* force scheduling by sleeping a single second */
  228. sleep(1);
  229. }
  230. /* Client signal handler => always exit */
  231. void
  232. client_signalhandler(int s)
  233. {
  234. debug("client(%d) received signal %d - quitting", clientpid, s);
  235. exit(EX_TEMPFAIL);
  236. }
  237. /* Prepare sharing structures for use */
  238. void
  239. initshare(int bufsize)
  240. {
  241. newclients = 0;
  242. realclients = 0;
  243. master = 1;
  244. /* need some extra space for housekeeping */
  245. bufsize += sizeof(struct sharedregion);
  246. /* allocate shared memory region for control information */
  247. shmstat = semstat = SIPC_FREE;
  248. atexit(exitmaster);
  249. if ((shmid = shmget(IPC_PRIVATE, bufsize, SHM_R | SHM_W)) < 0)
  250. fatal("could not get a shared memory identifier");
  251. shmstat = SIPC_KEYED;
  252. if ((shm = (struct sharedregion *) shmat(shmid, 0, 0)) == (void *) (-1))
  253. fatal("could not attach shared memory");
  254. shmstat = SIPC_ATTACHED;
  255. bzero(shm, bufsize);
  256. shm->reglen = bufsize;
  257. /* allocate semaphores */
  258. if ((semid = semget(IPC_PRIVATE, SEM_TOTAL, SEM_A | SEM_R)) < 0)
  259. fatal("could not get a semaphore");
  260. semstat = SIPC_KEYED;
  261. master_resetsem();
  262. }
  263. /* Spawn off a new client */
  264. pid_t
  265. spawn_client(int sock)
  266. {
  267. pid_t pid;
  268. check_master();
  269. clientsock = accept_connection(sock);
  270. if ((pid = fork())) {
  271. /* server */
  272. if (pid == -1) {
  273. info("could not fork client process");
  274. } else {
  275. newclients++;
  276. info("forked client(%d) for incoming connection from %.200s:%.200s",
  277. pid, res_host, res_service);
  278. }
  279. close(clientsock);
  280. return pid;
  281. } else {
  282. /* client */
  283. master = 0;
  284. /* catch signals */
  285. signal(SIGHUP, client_signalhandler);
  286. signal(SIGINT, client_signalhandler);
  287. signal(SIGQUIT, client_signalhandler);
  288. signal(SIGTERM, client_signalhandler);
  289. signal(SIGTERM, client_signalhandler);
  290. signal(SIGPIPE, client_signalhandler);
  291. clientpid = getpid();
  292. client_loop();
  293. /* NOT REACHED */
  294. return 0;
  295. }
  296. }
  297. /* Reap exit/stopped clients */
  298. void
  299. reap_clients()
  300. {
  301. pid_t pid;
  302. int status;
  303. status = 0;
  304. /* Reap all children that died */
  305. while (((int) (pid = wait4(-1, &status, WNOHANG, NULL)) > 0) && realclients >= 0) {
  306. /*
  307. * wait4 is supposed to return 0 if there is no status to report, but
  308. * it also reports -1 on OpenBSD 2.9
  309. */
  310. if (WIFEXITED(status))
  311. info("client process %d exited", pid, status);
  312. if (WIFSIGNALED(status))
  313. info("client process %d killed with signal %d", pid, WTERMSIG(status));
  314. if (WIFSTOPPED(status))
  315. info("client process %d stopped with signal %d", pid, WSTOPSIG(status));
  316. realclients--;
  317. }
  318. }
  319. /* Remove shared memory and semaphores at exit */
  320. void
  321. exitmaster()
  322. {
  323. union semun semarg;
  324. if (master == 0)
  325. return;
  326. switch (shmstat) {
  327. case SIPC_ATTACHED:
  328. if (shmdt(shm))
  329. warning("%s:%d: internal error: control region could not be detached",
  330. __FILE__, __LINE__);
  331. /* no break */
  332. case SIPC_KEYED:
  333. if (shmctl(shmid, IPC_RMID, NULL))
  334. warning("%s:%d: internal error: could remove control region %d",
  335. __FILE__, __LINE__, shmid);
  336. /* no break */
  337. case SIPC_FREE:
  338. break;
  339. default:
  340. warning("%s:%d: internal error: control region is in an unknown state",
  341. __FILE__, __LINE__);
  342. }
  343. switch (semstat) {
  344. case SIPC_KEYED:
  345. semarg.val = 0;
  346. if (semctl(semid, 0, IPC_RMID, semarg) != 0)
  347. warning("%s:%d: internal error: could not remove semaphore %d",
  348. __FILE__, __LINE__, semid);
  349. /* no break */
  350. case SIPC_FREE:
  351. break;
  352. default:
  353. warning("%s:%d: internal error: semaphore is in an unknown state",
  354. __FILE__, __LINE__);
  355. }
  356. }
  357. void
  358. client_loop()
  359. {
  360. int total;
  361. int sent;
  362. int written;
  363. for (;;) { /* FOREVER */
  364. client_waitread();
  365. total = shared_getlen();
  366. sent = 0;
  367. while (sent < total) {
  368. if ((written = write(clientsock, (char *) (shared_getmem() + sent), total - sent)) == -1) {
  369. info("client(%d): write error. Client will quit.", clientpid);
  370. exit(1);
  371. }
  372. sent += written;
  373. debug("client(%d): written %d bytes of %d total", clientpid, sent, total);
  374. }
  375. client_doneread();
  376. }
  377. }