share.c 11 KB

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