share.c 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /* $Id: share.c,v 1.8 2002/08/31 16:09:56 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. union semun semarg;
  151. semarg.val = 0;
  152. check_sem();
  153. check_master();
  154. if ((semctl(semid, SEM_WAIT, SETVAL, semarg) != 0) ||
  155. (semctl(semid, SEM_READ, SETVAL, semarg) != 0))
  156. fatal("%s:%d: Internal error: Cannot reset semaphores",
  157. __FILE__, __LINE__);
  158. }
  159. /* Prepare for writing to shm */
  160. void
  161. master_forbidread()
  162. {
  163. int clientsread;
  164. union semun semarg;
  165. check_sem();
  166. check_master();
  167. /* prepare for a new read */
  168. semarg.val = 0;
  169. if ((clientsread = semctl(semid, SEM_READ, GETVAL, semarg)) < 0)
  170. fatal("%s:%d: Internal error: Cannot read semaphore",
  171. __FILE__, __LINE__);
  172. if (clientsread != realclients)
  173. reap_clients();
  174. /* add new clients */
  175. realclients += newclients;
  176. newclients = 0;
  177. master_resetsem();
  178. }
  179. /* Signal 'permit read' to all clients */
  180. void
  181. master_permitread()
  182. {
  183. union semun semarg;
  184. shm->seqnr++;
  185. semarg.val = realclients;
  186. if (semctl(semid, SEM_WAIT, SETVAL, semarg) != 0)
  187. fatal("%s:%d: Internal error: Cannot reset semaphores",
  188. __FILE__, __LINE__);
  189. }
  190. /* Make clients wait until master signals */
  191. void
  192. client_waitread()
  193. {
  194. struct sembuf sops;
  195. check_sem();
  196. sops.sem_num = SEM_WAIT;
  197. sops.sem_op = -1;
  198. sops.sem_flg = 0;
  199. if (semop(semid, &sops, 1) != 0 )
  200. fatal("%s:%d: Internal error: Cannot obtain semaphore (%.200s)",
  201. __FILE__, __LINE__, strerror(errno));
  202. seqnr = shm->seqnr;
  203. }
  204. /* Client signal 'done reading' to master */
  205. void
  206. client_doneread()
  207. {
  208. struct sembuf sops;
  209. check_sem();
  210. if (seqnr != shm->seqnr)
  211. fatal("%s:%d: Internal error: Client lagging behind (%d, %d)",
  212. __FILE__, __LINE__, seqnr, shm->seqnr);
  213. sops.sem_num = SEM_READ;
  214. sops.sem_op = 1;
  215. sops.sem_flg = IPC_NOWAIT;
  216. if (semop(semid, &sops, 1) != 0 )
  217. fatal("%s:%d: Internal error: Cannot release semaphore (%.200s)",
  218. __FILE__, __LINE__, strerror(errno));
  219. }
  220. /* Prepare sharing structures for use */
  221. void
  222. initshare(int bufsize)
  223. {
  224. newclients = 0;
  225. realclients = 0;
  226. master = 1;
  227. /* need some extra space for housekeeping */
  228. bufsize += sizeof(struct sharedregion);
  229. /* allocate shared memory region for control information */
  230. shmstat = semstat = SIPC_FREE;
  231. atexit(exitmaster);
  232. if ((shmid = shmget(IPC_PRIVATE, bufsize, SHM_R | SHM_W)) < 0)
  233. fatal("Could not get a shared memory identifier");
  234. shmstat = SIPC_KEYED;
  235. if ((shm = (struct sharedregion *)shmat(shmid, 0, 0)) == (void *)(-1))
  236. fatal("Could not attach shared memory");
  237. shmstat = SIPC_ATTACHED;
  238. bzero(shm, bufsize);
  239. shm->reglen = bufsize;
  240. /* allocate semaphores */
  241. if ((semid = semget(IPC_PRIVATE, SEM_TOTAL, SEM_A | SEM_R)) < 0)
  242. fatal("Could not get a semaphore");
  243. semstat = SIPC_KEYED;
  244. master_resetsem();
  245. }
  246. /* Spawn off a new client */
  247. void
  248. spawn_client(int sock)
  249. {
  250. pid_t client_pid;
  251. check_master();
  252. clientsock = acceptconnection(sock);
  253. if ((client_pid = fork())) {
  254. /* server */
  255. newclients++;
  256. close(clientsock);
  257. } else {
  258. /* client */
  259. master = 0;
  260. client_loop();
  261. }
  262. }
  263. /* Reap exit/stopped clients */
  264. void
  265. reap_clients()
  266. {
  267. pid_t clientpid;
  268. int status;
  269. status = 0;
  270. /* Reap all children that died */
  271. while (((int)(clientpid = wait4(-1, &status, WNOHANG, NULL)) > 0) && realclients >= 0) {
  272. /* wait4 is supposed to return 0 if there is no status to report, but
  273. it also reports -1 on OpenBSD 2.9 */
  274. if (WIFEXITED(status))
  275. info("client process %d exited", clientpid, status);
  276. if (WIFSIGNALED(status))
  277. info("client process %d killed with signal %d", clientpid, WTERMSIG(status));
  278. if (WIFSTOPPED(status))
  279. info("client process %d stopped with signal %d", clientpid, WSTOPSIG(status));
  280. realclients--;
  281. }
  282. }
  283. /* Remove shared memory and semaphores at exit */
  284. void
  285. exitmaster()
  286. {
  287. union semun semarg;
  288. if (master == 0)
  289. return;
  290. switch (shmstat) {
  291. case SIPC_ATTACHED:
  292. if (shmdt(shm))
  293. warning("%s:%d: Internal error: control region could not be detached",
  294. __FILE__, __LINE__);
  295. /* no break */
  296. case SIPC_KEYED:
  297. if (shmctl(shmid, IPC_RMID, NULL))
  298. warning("%s:%d: Internal error: could remove control region %d",
  299. __FILE__, __LINE__, shmid);
  300. /* no break */
  301. case SIPC_FREE:
  302. break;
  303. default:
  304. warning("%s:%d: Internal error: control region is in an unknown state",
  305. __FILE__, __LINE__);
  306. }
  307. switch (semstat) {
  308. case SIPC_KEYED:
  309. semarg.val = 0;
  310. if (semctl(semid, 0, IPC_RMID, semarg) != 0)
  311. warning("%s:%d: Internal error: could not remove semaphore %d",
  312. __FILE__, __LINE__, semid);
  313. /* no break */
  314. case SIPC_FREE:
  315. break;
  316. default:
  317. warning("%s:%d: Internal error: semaphore is in an unknown state",
  318. __FILE__, __LINE__);
  319. }
  320. }
  321. void
  322. client_loop()
  323. {
  324. int total;
  325. int sent;
  326. int written;
  327. for (;;) { /* FOREVER */
  328. client_waitread();
  329. total = shared_getlen();
  330. sent = 0;
  331. while (sent < total) {
  332. if ((written = write(clientsock, (char *)(shared_getmem() + sent), total - sent)) == -1) {
  333. info("Write error. Client will quit.");
  334. exit(1);
  335. }
  336. sent += written;
  337. debug("client written %d bytes of %d total", sent, total);
  338. }
  339. client_doneread();
  340. }
  341. }