share.c 11 KB

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