share.c 11 KB

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