share.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /* $Id: share.c,v 1.6 2002/07/11 15:27:33 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 monmuxes */
  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 <string.h>
  43. #include <stdlib.h>
  44. #include <unistd.h>
  45. #include "data.h"
  46. #include "error.h"
  47. #include "muxnet.h"
  48. #include "share.h"
  49. /* Shared operation:
  50. *
  51. * The moment the master monmux 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. void check_master();
  78. void check_sem();
  79. void client_doneread();
  80. void client_loop();
  81. void client_waitread();
  82. void exitmaster();
  83. void master_resetsem();
  84. void reap_clients();
  85. int recvfd(int);
  86. int sendfd(int, int);
  87. __END_DECLS
  88. #define SEM_WAIT 0 /* wait semaphore */
  89. #define SEM_READ 1 /* have read semaphore */
  90. #define SEM_TOTAL 2
  91. int realclients; /* number of clients active */
  92. int newclients;
  93. int master; /* is current process master or child */
  94. int clientsock; /* connected client */
  95. enum ipcstat { SIPC_FREE, SIPC_KEYED, SIPC_ATTACHED };
  96. key_t shmid;
  97. struct sharedregion *shm;
  98. enum ipcstat shmstat;
  99. key_t semid;
  100. enum ipcstat semstat;
  101. int seqnr;
  102. /* Get start of data in shared region */
  103. long *
  104. shared_getmem()
  105. {
  106. return &shm->data;
  107. }
  108. /* Get max length of data stored in shared region */
  109. long
  110. shared_getmaxlen()
  111. {
  112. return shm->reglen - sizeof(struct sharedregion);
  113. }
  114. /* Set length of data stored in shared region */
  115. void
  116. shared_setlen(long length)
  117. {
  118. if (length > (shm->reglen - (long)sizeof(struct sharedregion)))
  119. fatal("%s:%d: Internal error:"
  120. "set_length of shared region called with value larger than actual size",
  121. __FILE__, __LINE__);
  122. shm->ctlen = length;
  123. }
  124. /* Get length of data stored in shared region */
  125. long
  126. shared_getlen()
  127. {
  128. return shm->ctlen;
  129. }
  130. /* Check whether semaphore is available */
  131. void
  132. check_sem()
  133. {
  134. if (semstat != SIPC_KEYED)
  135. fatal("%s:%d: Internal error: Semaphore not available",
  136. __FILE__, __LINE__);
  137. }
  138. /* Check whether process is the master process */
  139. void
  140. check_master()
  141. {
  142. if (master == 0)
  143. fatal("%s:%d: Internal error: Child process tried to access master routines",
  144. __FILE__, __LINE__);
  145. }
  146. /* Reset semaphores before each distribution cycle */
  147. void
  148. master_resetsem()
  149. {
  150. check_sem();
  151. check_master();
  152. if ((semctl(semid, SEM_WAIT, SETVAL, 0) != 0) ||
  153. (semctl(semid, SEM_READ, SETVAL, 0) != 0))
  154. fatal("%s:%d: Internal error: Cannot reset semaphores",
  155. __FILE__, __LINE__);
  156. }
  157. /* Prepare for writing to shm */
  158. void
  159. master_forbidread()
  160. {
  161. int clientsread;
  162. check_sem();
  163. check_master();
  164. /* prepare for a new read */
  165. if ((clientsread = semctl(semid, SEM_READ, GETVAL, 0)) < 0)
  166. fatal("%s:%d: Internal error: Cannot read semaphore",
  167. __FILE__, __LINE__);
  168. if (clientsread != realclients)
  169. reap_clients();
  170. /* add new clients */
  171. realclients += newclients;
  172. newclients = 0;
  173. master_resetsem();
  174. }
  175. /* Signal 'permit read' to all clients */
  176. void
  177. master_permitread()
  178. {
  179. shm->seqnr++;
  180. if (semctl(semid, SEM_WAIT, SETVAL, realclients) != 0)
  181. fatal("%s:%d: Internal error: Cannot reset semaphores",
  182. __FILE__, __LINE__);
  183. }
  184. /* Make clients wait until master signals */
  185. void
  186. client_waitread()
  187. {
  188. struct sembuf sops;
  189. check_sem();
  190. sops.sem_num = SEM_WAIT;
  191. sops.sem_op = -1;
  192. sops.sem_flg = 0;
  193. if (semop(semid, &sops, 1) != 0 )
  194. fatal("%s:%d: Internal error: Cannot obtain semaphore (%.200s)",
  195. __FILE__, __LINE__, strerror(errno));
  196. seqnr = shm->seqnr;
  197. }
  198. /* Client signal 'done reading' to master */
  199. void
  200. client_doneread()
  201. {
  202. struct sembuf sops;
  203. check_sem();
  204. if (seqnr != shm->seqnr)
  205. fatal("%s:%d: Internal error: Client lagging behind (%d, %d)",
  206. __FILE__, __LINE__, seqnr, shm->seqnr);
  207. sops.sem_num = SEM_READ;
  208. sops.sem_op = 1;
  209. sops.sem_flg = IPC_NOWAIT;
  210. if (semop(semid, &sops, 1) != 0 )
  211. fatal("%s:%d: Internal error: Cannot release semaphore (%.200s)",
  212. __FILE__, __LINE__, strerror(errno));
  213. }
  214. /* Prepare sharing structures for use */
  215. void
  216. initshare(int bufsize)
  217. {
  218. newclients = 0;
  219. realclients = 0;
  220. master = 1;
  221. /* need some extra space for housekeeping */
  222. bufsize += sizeof(struct sharedregion);
  223. /* allocate shared memory region for control information */
  224. shmstat = semstat = SIPC_FREE;
  225. atexit(exitmaster);
  226. if ((shmid = shmget(IPC_PRIVATE, bufsize, SHM_R | SHM_W)) < 0)
  227. fatal("Could not get a shared memory identifier");
  228. shmstat = SIPC_KEYED;
  229. if ((int)(shm = (struct sharedregion *)shmat(shmid, 0, 0)) < 0)
  230. fatal("Could not attach shared memory");
  231. shmstat = SIPC_ATTACHED;
  232. bzero(shm, bufsize);
  233. shm->reglen = bufsize;
  234. /* allocate semaphores */
  235. if ((semid = semget(IPC_PRIVATE, SEM_TOTAL, SEM_A | SEM_R)) < 0)
  236. fatal("Could not get a semaphore");
  237. semstat = SIPC_KEYED;
  238. master_resetsem();
  239. }
  240. /* Spawn off a new client */
  241. void
  242. spawn_client(int sock)
  243. {
  244. pid_t client_pid;
  245. check_master();
  246. clientsock = acceptconnection(sock);
  247. if ((client_pid = fork())) {
  248. /* server */
  249. newclients++;
  250. close(clientsock);
  251. } else {
  252. /* client */
  253. master = 0;
  254. client_loop();
  255. }
  256. }
  257. /* Reap exit/stopped clients */
  258. void
  259. reap_clients()
  260. {
  261. pid_t clientpid;
  262. int status;
  263. status = 0;
  264. /* Reap all children that died */
  265. while (((int)(clientpid = wait4(-1, &status, WNOHANG, NULL)) > 0) && realclients >= 0) {
  266. /* wait4 is supposed to return 0 if there is no status to report, but
  267. it also reports -1 on OpenBSD 2.9 */
  268. if (WIFEXITED(status))
  269. info("client process %d exited", clientpid, status);
  270. if (WIFSIGNALED(status))
  271. info("client process %d killed with signal %d", clientpid, WTERMSIG(status));
  272. if (WIFSTOPPED(status))
  273. info("client process %d stopped with signal %d", clientpid, WSTOPSIG(status));
  274. realclients--;
  275. }
  276. }
  277. /* Remove shared memory and semaphores at exit */
  278. void
  279. exitmaster()
  280. {
  281. if (master == 0)
  282. return;
  283. switch (shmstat) {
  284. case SIPC_ATTACHED:
  285. if (shmdt(shm))
  286. warning("%s:%d: Internal error: control region could not be detached",
  287. __FILE__, __LINE__);
  288. /* no break */
  289. case SIPC_KEYED:
  290. if (shmctl(shmid, IPC_RMID, NULL))
  291. warning("%s:%d: Internal error: could remove control region %d",
  292. __FILE__, __LINE__, shmid);
  293. /* no break */
  294. case SIPC_FREE:
  295. break;
  296. default:
  297. warning("%s:%d: Internal error: control region is in an unknown state",
  298. __FILE__, __LINE__);
  299. }
  300. switch (semstat) {
  301. case SIPC_KEYED:
  302. if (semctl(semid, 0, IPC_RMID, 0) != 0)
  303. warning("%s:%d: Internal error: could not remove semaphore %d",
  304. __FILE__, __LINE__, semid);
  305. /* no break */
  306. case SIPC_FREE:
  307. break;
  308. default:
  309. warning("%s:%d: Internal error: semaphore is in an unknown state",
  310. __FILE__, __LINE__);
  311. }
  312. }
  313. void
  314. client_loop()
  315. {
  316. int total;
  317. int sent;
  318. int written;
  319. for (;;) { /* FOREVER */
  320. client_waitread();
  321. total = shared_getlen();
  322. sent = 0;
  323. while (sent < total) {
  324. if ((written = write(clientsock, (char *)(shared_getmem() + sent), total - sent)) == -1) {
  325. info("Write error. Client will quit.");
  326. exit(1);
  327. }
  328. sent += written;
  329. debug("client written %d bytes of %d total", sent, total);
  330. }
  331. client_doneread();
  332. }
  333. }