2 #include <sys/socket.h>
5 #include <netinet/in.h>
16 #include "codemuxlib.h"
24 #define CONF_FILE "/etc/codemux/codemux.conf"
26 #define PIDFILE "/var/run/codemux.pid"
27 #define TARG_SETSIZE 4096
29 /* set aside some small number of fds for us, allow the rest for
31 #define MAX_CONNS ((TARG_SETSIZE-20)/2)
33 /* no single service can take more than half the connections */
34 #define SERVICE_MAX (MAX_CONNS/2)
36 /* how many total connections before we get concerned about fairness
38 #define FAIRNESS_CUTOFF (MAX_CONNS * 0.85)
40 /* codemux version, from Makefile, or specfile */
41 #define CODEMUX_VERSION RPM_VERSION
43 typedef struct FlowBuf {
44 int fb_refs; /* num refs */
45 char *fb_buf; /* actual buffer */
46 int fb_used; /* bytes used in buffer */
48 #define FB_SIZE 3800 /* max usable size */
49 #define FB_ALLOCSIZE 4000 /* extra to include IP address */
51 typedef struct SockInfo {
52 int si_peerFd; /* fd of peer */
53 struct in_addr si_cliAddr; /* address of client */
54 int si_blocked; /* are we blocked? */
55 int si_needsHeaderSince; /* since when are we waiting for a header */
56 int si_whichService; /* index of service */
57 FlowBuf *si_readBuf; /* read data into this buffer */
58 FlowBuf *si_writeBuf; /* drain this buffer for writing */
61 static SockInfo sockInfo[TARG_SETSIZE]; /* fd number of peer socket */
63 typedef struct ServiceSig {
64 char *ss_host; /* suffix in host */
67 int ss_slicePos; /* position in slices array */
70 static ServiceSig *serviceSig;
71 static int numServices;
72 static int confFileReadTime;
75 typedef struct SliceInfo {
77 int si_inUse; /* do any services refer to this? */
82 static SliceInfo *slices;
84 static int numActiveSlices;
85 static int numTotalSliceConns;
86 static int anySliceXidsNeeded;
88 typedef struct OurFDSet {
89 long __fds_bits[TARG_SETSIZE/32];
91 static OurFDSet masterReadSet, masterWriteSet;
92 static int highestSetFd;
93 static int numNeedingHeaders; /* how many conns waiting on headers? */
97 /* PLC netflow domain name like netflow.planet-lab.org */
98 static char* domainNamePLCNetflow = NULL;
101 #define SO_SETXID SO_PEERCRED
103 /*-----------------------------------------------------------------*/
105 ServiceToSlice(int whichService)
107 if (whichService < 0)
109 return(&slices[serviceSig[whichService].ss_slicePos]);
111 /*-----------------------------------------------------------------*/
121 "CoDemux version %s\n"
122 "numForks %d, numActiveSlices %d, numTotalSliceConns %d\n"
123 "numNeedingHeaders %d, anySliceXidsNeeded %d\n",
125 numForks, numActiveSlices, numTotalSliceConns,
126 numNeedingHeaders, anySliceXidsNeeded);
127 start += strlen(start);
129 for (i = 0; i < numSlices; i++) {
130 SliceInfo *si = &slices[i];
131 sprintf(start, "Slice %d: %s xid %d, %d conns, inUse %d\n",
132 i, si->si_sliceName, si->si_xid, si->si_numConns,
134 start += strlen(start);
137 for (i = 0; i < numServices; i++) {
138 ServiceSig *ss = &serviceSig[i];
139 sprintf(start, "Service %d: %s %s port %d, slice# %d\n", i, ss->ss_host,
140 ss->ss_slice, (int) ss->ss_port, ss->ss_slicePos);
141 start += strlen(start);
147 /*-----------------------------------------------------------------*/
151 /* walks through /etc/passwd, and gets the uid for every slice we
157 if (!anySliceXidsNeeded)
160 for (i = 0; i < numSlices; i++) {
161 SliceInfo *si = &slices[i];
164 for (i = 0; i < numServices; i++) {
165 SliceInfo *si = ServiceToSlice(i);
170 if ((f = fopen("/etc/passwd", "r")) == NULL)
173 while ((line = GetNextLine(f)) != NULL) {
177 if ((temp = strchr(line, ':')) == NULL)
178 goto next_line; /* weird line */
179 *temp = '\0'; /* terminate slice name */
181 if ((temp = strchr(temp+1, ':')) == NULL)
182 goto next_line; /* weird line */
183 if ((xid = atoi(temp+1)) < 1)
184 goto next_line; /* weird xid */
186 /* we've got a slice name and xid, let's try to match */
187 for (i = 0; i < numSlices; i++) {
188 if (slices[i].si_xid == 0 &&
189 strcasecmp(slices[i].si_sliceName, line) == 0) {
190 slices[i].si_xid = xid;
199 /* assume service 0 is the root service, and don't check it since
200 it'll have xid zero */
201 anySliceXidsNeeded = FALSE;
202 for (i = 1; i < numSlices; i++) {
203 if (slices[i].si_xid == 0 && slices[i].si_inUse > 0) {
204 anySliceXidsNeeded = TRUE;
211 /*-----------------------------------------------------------------*/
213 SliceConnsInc(int whichService)
215 SliceInfo *si = ServiceToSlice(whichService);
219 numTotalSliceConns++;
221 if (si->si_numConns == 1)
224 /*-----------------------------------------------------------------*/
226 SliceConnsDec(int whichService)
228 SliceInfo *si = ServiceToSlice(whichService);
232 numTotalSliceConns--;
234 if (si->si_numConns == 0)
237 /*-----------------------------------------------------------------*/
239 WhichSlicePos(char *slice)
241 /* adds the new slice if necessary, returns the index into slice
242 array. Never change the ordering of existing slices */
244 static int numSlicesAlloc;
246 for (i = 0; i < numSlices; i++) {
247 if (strcasecmp(slice, slices[i].si_sliceName) == 0)
251 if (numSlices >= numSlicesAlloc) {
252 numSlicesAlloc = MAX(8, numSlicesAlloc * 2);
253 slices = xrealloc(slices, numSlicesAlloc * sizeof(SliceInfo));
256 memset(&slices[numSlices], 0, sizeof(SliceInfo));
257 slices[numSlices].si_sliceName = xstrdup(slice);
261 /*-----------------------------------------------------------------*/
267 ServiceSig *servs = NULL;
273 if (stat(CONF_FILE, &statBuf) != 0) {
274 fprintf(stderr, "failed stat on codemux.conf\n");
279 if (statBuf.st_mtime == confFileReadTime)
282 if ((f = fopen(CONF_FILE, "r")) == NULL) {
283 fprintf(stderr, "failed reading codemux.conf\n");
289 /* conf file entries look like
290 coblitz.codeen.org princeton_coblitz 3125
299 if ((line = GetNextLine(f)) == NULL)
302 memset(&serv, 0, sizeof(serv));
303 if (WordCount(line) < 3) {
304 fprintf(stderr, "bad line: %s\n", line);
307 serv.ss_port = port = atoi(GetField(line, 2));
308 if (port < 1 || port > 65535 || port == DEMUX_PORT) {
309 fprintf(stderr, "bad port: %s\n", line);
313 serv.ss_host = GetWord(line, 0);
314 serv.ss_slice = GetWord(line, 1);
317 /* the first row must be an entry for apache */
318 if (strcmp(serv.ss_host, "*") != 0 ||
319 strcmp(serv.ss_slice, "root") != 0) {
320 fprintf(stderr, "first row has to be for webserver\n");
323 /* see if there's PLC netflow's domain name */
324 if (domainNamePLCNetflow != NULL) {
325 xfree(domainNamePLCNetflow);
326 domainNamePLCNetflow = NULL;
328 domainNamePLCNetflow = GetWord(line, 3);
330 if (num >= numAlloc) {
331 numAlloc = MAX(numAlloc * 2, 8);
332 servs = xrealloc(servs, numAlloc * sizeof(ServiceSig));
334 serv.ss_slicePos = WhichSlicePos(serv.ss_slice);
335 if (slices[serv.ss_slicePos].si_inUse == 0 &&
336 slices[serv.ss_slicePos].si_xid < 1)
337 anySliceXidsNeeded = TRUE; /* if new/inactive, we need xid */
345 /* Faiyaz asked me to allow a single-entry codemux conf */
347 if (numServices == 0) {
348 fprintf(stderr, "nothing found in codemux.conf\n");
355 fprintf(stderr, "no entry found in codemux.conf\n");
359 for (i = 0; i < numServices; i++) {
360 xfree(serviceSig[i].ss_host);
361 xfree(serviceSig[i].ss_slice);
366 confFileReadTime = statBuf.st_mtime;
368 /*-----------------------------------------------------------------*/
369 static char *err400BadRequest =
370 "HTTP/1.0 400 Bad Request\r\n"
371 "Content-Type: text/html\r\n"
373 "You are trying to access a PlanetLab node, and your\n"
374 "request header exceeded the allowable size. Please\n"
375 "try again if you believe this error is temporary.\n";
376 /*-----------------------------------------------------------------*/
377 static char *err503Unavailable =
378 "HTTP/1.0 503 Service Unavailable\r\n"
379 "Content-Type: text/html\r\n"
381 "You are trying to access a PlanetLab node, but the service\n"
382 "seems to be unavailable at the moment. Please try again.\n";
383 /*-----------------------------------------------------------------*/
384 static char *err503TooBusy =
385 "HTTP/1.0 503 Service Unavailable\r\n"
386 "Content-Type: text/html\r\n"
388 "You are trying to access a PlanetLab node, but the service\n"
389 "seems to be overloaded at the moment. Please try again.\n";
390 /*-----------------------------------------------------------------*/
392 SetFd(int fd, OurFDSet *set)
394 if (highestSetFd < fd)
398 /*-----------------------------------------------------------------*/
400 ClearFd(int fd, OurFDSet *set)
404 /*-----------------------------------------------------------------*/
406 RemoveHeader(char *lower, char *real, int totalSize, char *header)
408 /* returns number of characters removed */
413 sprintf(h2, "\n%s", header);
415 if ((conn = strstr(lower, h2)) == NULL)
419 /* determine how many characters to remove */
420 if ((temp = strchr(conn, '\n')) != NULL)
421 len = (temp - conn) + 1;
423 len = strlen(conn) + 1;
424 start = conn - lower;
426 memmove(&real[start], &real[end], totalSize - end);
427 memmove(&lower[start], &lower[end], totalSize - end);
431 /*-----------------------------------------------------------------*/
433 InsertHeader(char *buf, int totalSize, char *header)
435 /* returns number of bytes inserted */
441 sprintf(h2, "%s\r\n", header);
444 /* if we don't encounter a \n, it means that we have only a single
445 line, and we'd converted the \n to a \0 */
446 if ((temp = strchr(buf, '\n')) == NULL)
447 temp = strchr(buf, '\0');
450 memmove(temp + len, temp, totalSize - (temp - buf));
451 memcpy(temp, h2, len);
455 /*-----------------------------------------------------------------*/
457 FindService(FlowBuf *fb, int *whichService, struct in_addr addr)
462 char *buf = fb->fb_buf;
470 if (strstr(buf, "\n\r\n") == NULL && strstr(buf, "\n\n") == NULL)
473 /* insert client info after first line */
474 sprintf(orig, "X-CoDemux-Client: %s", inet_ntoa(addr));
475 fb->fb_used += InsertHeader(buf, fb->fb_used + 1, orig);
477 /* get just the header, so we can work on it */
478 LOCAL_STR_DUP_LOWER(lowerBuf, buf);
479 if ((end = strstr(lowerBuf, "\n\r\n")) == NULL)
480 end = strstr(lowerBuf, "\n\n");
483 /* remove any existing connection, keep-alive headers, add ours */
484 fb->fb_used -= RemoveHeader(lowerBuf, buf, fb->fb_used + 1, "keep-alive:");
485 fb->fb_used -= RemoveHeader(lowerBuf, buf, fb->fb_used + 1, "connection:");
486 fb->fb_used += InsertHeader(buf, fb->fb_used + 1, "Connection: close");
487 InsertHeader(lowerBuf, fb->fb_used + 1, "connection: close");
489 /* isolate host, see if it matches */
490 if ((hostVal = strstr(lowerBuf, "\nhost:")) != NULL) {
492 hostVal += strlen("\nhost:");
493 if ((end = strchr(hostVal, '\n')) != NULL)
495 if ((end = strchr(hostVal, ':')) != NULL)
497 while (isspace(*hostVal))
499 if (strlen(hostVal) > 0) {
500 hostVal = GetWord(hostVal, 0);
501 for (i = 1; i < numServices; i++) {
502 if (serviceSig[i].ss_host != NULL &&
503 DoesDotlessSuffixMatch(hostVal, 0, serviceSig[i].ss_host)) {
506 /* printf("%s", buf); */
515 /* see if URL prefix matches */
516 if ((end = strchr(lowerBuf, '\n')) != NULL)
518 if ((url = GetField(lowerBuf, 1)) == NULL ||
520 /* bad request - let apache handle it ? */
524 url++; /* skip the leading slash */
525 for (i = 1; i < numServices; i++) {
526 if (serviceSig[i].ss_prefix != NULL &&
527 (len = strlen(serviceSig[i].ss_prefix)) > 0 &&
528 strncmp(url, serviceSig[i].ss_prefix, len) == 0 &&
529 (url[len] == ' ' || url[len] == '/')) {
530 int startPos = url - lowerBuf;
531 int stripLen = len + ((url[len] == '/') ? 1 : 0);
532 /* strip out prefix */
533 fb->fb_used -= stripLen;
534 memmove(&buf[startPos], &buf[startPos+stripLen],
535 fb->fb_used + 1 - startPos);
536 /* printf("%s", buf); */
543 /* default to first service */
547 /*-----------------------------------------------------------------*/
549 StartConnect(int origFD, int whichService)
552 struct sockaddr_in dest;
556 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
560 /* make socket non-blocking */
561 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) {
566 /* set addr structure */
567 memset(&dest, 0, sizeof(dest));
568 dest.sin_family = AF_INET;
569 dest.sin_port = htons(serviceSig[whichService].ss_port);
570 dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
572 /* start connection process - we should be told that it's in
574 if (connect(sock, (struct sockaddr *) &dest, sizeof(dest)) != -1 ||
575 errno != EINPROGRESS) {
580 SetFd(sock, &masterWriteSet); /* determine when connect finishes */
581 sockInfo[origFD].si_peerFd = sock;
582 si = &sockInfo[sock];
583 memset(si, 0, sizeof(SockInfo));
584 si->si_peerFd = origFD;
585 si->si_blocked = TRUE; /* still connecting */
586 si->si_whichService = whichService;
587 si->si_writeBuf = sockInfo[origFD].si_readBuf;
588 sockInfo[origFD].si_readBuf->fb_refs++;
589 if (whichService >= 0)
590 SliceConnsInc(whichService);
594 /*-----------------------------------------------------------------*/
596 WriteAvailData(int fd)
598 SockInfo *si = &sockInfo[fd];
599 FlowBuf *fb = si->si_writeBuf;
602 /* printf("trying to write fd %d\n", fd); */
603 if (fb->fb_used < 1 || si->si_blocked)
606 /* printf("trying to write %d bytes\n", fb->fb_used); */
607 /* write(STDOUT_FILENO, fb->fb_buf, fb->fb_used); */
608 if ((res = write(fd, fb->fb_buf, fb->fb_used)) > 0) {
610 if (fb->fb_used > 0) {
611 /* couldn't write all - assume blocked */
612 memmove(fb->fb_buf, &fb->fb_buf[res], fb->fb_used);
613 si->si_blocked = TRUE;
614 SetFd(fd, &masterWriteSet);
616 /* printf("wrote %d\n", res); */
620 /* we might have been full but didn't realize it */
621 if (res == -1 && errno == EAGAIN) {
622 si->si_blocked = TRUE;
623 SetFd(fd, &masterWriteSet);
627 /* otherwise, assume the worst */
630 /*-----------------------------------------------------------------*/
631 static OurFDSet socksToCloseVec;
632 static int numSocksToClose;
633 static int whichSocksToClose[TARG_SETSIZE];
634 /*-----------------------------------------------------------------*/
638 if (FD_ISSET(fd, &socksToCloseVec))
640 SetFd(fd, &socksToCloseVec);
641 whichSocksToClose[numSocksToClose] = fd;
644 /*-----------------------------------------------------------------*/
651 if (buf->fb_refs == 0) {
656 /*-----------------------------------------------------------------*/
658 ReallyCloseSocks(void)
662 memset(&socksToCloseVec, 0, sizeof(socksToCloseVec));
664 for (i = 0; i < numSocksToClose; i++) {
665 int fd = whichSocksToClose[i];
667 DecBuf(sockInfo[fd].si_readBuf);
668 DecBuf(sockInfo[fd].si_writeBuf);
669 ClearFd(fd, &masterReadSet);
670 ClearFd(fd, &masterWriteSet);
671 if (sockInfo[fd].si_needsHeaderSince) {
672 sockInfo[fd].si_needsHeaderSince = 0;
675 if (sockInfo[fd].si_whichService >= 0) {
676 SliceConnsDec(sockInfo[fd].si_whichService);
677 sockInfo[fd].si_whichService = -1;
680 if (sockInfo[fd].si_peerFd >= 0) {
681 sockInfo[sockInfo[fd].si_peerFd].si_peerFd = -1;
686 /*-----------------------------------------------------------------*/
688 SocketReadyToRead(int fd)
690 SockInfo *si = &sockInfo[fd];
695 /* if peer is closed, close ourselves */
696 if (si->si_peerFd < 0 && (!si->si_needsHeaderSince)) {
701 if ((fb = si->si_readBuf) == NULL) {
702 fb = si->si_readBuf = xcalloc(1, sizeof(FlowBuf));
704 if (si->si_peerFd >= 0) {
705 sockInfo[si->si_peerFd].si_writeBuf = fb;
710 if (fb->fb_buf == NULL)
711 fb->fb_buf = xmalloc(FB_ALLOCSIZE);
713 /* determine read buffer size - if 0, then block reads and return */
714 if ((spaceLeft = FB_SIZE - fb->fb_used) <= 0) {
715 if (si->si_needsHeaderSince) {
716 write(fd, err400BadRequest, strlen(err400BadRequest));
721 ClearFd(fd, &masterReadSet);
726 /* read as much as allowed, and is available */
727 if ((res = read(fd, &fb->fb_buf[fb->fb_used], spaceLeft)) == 0) {
729 if (fb->fb_used == 0 && si->si_peerFd >= 0) {
730 CloseSock(si->si_peerFd);
738 TRACE("fd=%d errno=%d errstr=%s\n",fd, errno, strerror(errno));
740 if (fb->fb_used == 0 && si->si_peerFd >= 0) {
741 CloseSock(si->si_peerFd);
747 fb->fb_buf[fb->fb_used] = 0; /* terminate it for convenience */
748 // printf("sock %d, read %d, total %d\n", fd, res, fb->fb_used);
750 /* if we need header, check if we've gotten it. if so, do
751 modifications and continue. if not, check if we've read the
752 maximum, and if so, fail */
753 if (si->si_needsHeaderSince) {
757 #define STATUS_REQ "GET /codemux/status.txt"
758 if (strncasecmp(fb->fb_buf, STATUS_REQ, sizeof(STATUS_REQ)-1) == 0) {
764 // printf("trying to find service\n");
765 if (FindService(fb, &whichService, si->si_cliAddr) != SUCCESS)
767 // printf("found service %d\n", whichService);
768 slice = ServiceToSlice(whichService);
770 /* if it needs to be redirected to PLC, let it be handled here */
771 if (whichService == 0 && domainNamePLCNetflow != NULL &&
772 strcmp(slice->si_sliceName, "root") == 0) {
775 static const char* resp302 =
776 "HTTP/1.0 302 Found\r\n"
777 "Location: http://%s\r\n"
778 "Cache-Control: no-cache, no-store\r\n"
779 "Content-type: text/html\r\n"
780 "Connection: close\r\n"
782 "Your request is being redirected to PLC Netflow http://%s\n";
783 len = snprintf(msg, sizeof(msg), resp302,
784 domainNamePLCNetflow, domainNamePLCNetflow);
789 /* no service can have more than some absolute max number of
790 connections. Also, when we're too busy, start enforcing
791 fairness across the servers */
792 if (slice->si_numConns > SERVICE_MAX ||
793 (numTotalSliceConns > FAIRNESS_CUTOFF &&
794 slice->si_numConns > MAX_CONNS/numActiveSlices)) {
795 write(fd, err503TooBusy, strlen(err503TooBusy));
796 TRACE("CloseSock(): fd=%d too busy\n", fd);
801 if (slice->si_xid > 0) {
802 static int first = 1;
803 setsockopt(fd, SOL_SOCKET, SO_SETXID,
804 &slice->si_xid, sizeof(slice->si_xid));
806 /* just to log it for once */
807 fprintf(stderr, "setsockopt() with XID = %d name = %s\n",
808 slice->si_xid, slice->si_sliceName);
813 si->si_needsHeaderSince = 0;
815 if (StartConnect(fd, whichService) != SUCCESS) {
816 write(fd, err503Unavailable, strlen(err503Unavailable));
817 TRACE("CloseSock(): fd=%d StartConnect() failed\n", fd);
824 /* write anything possible */
825 if (WriteAvailData(si->si_peerFd) != SUCCESS) {
826 /* assume the worst and close */
827 TRACE("CloseSock(): fd=%d WriteAvailData() failed errno=%d errstr=%s\n",
828 fd, errno, strerror(errno));
830 if (si->si_peerFd >=0) {
831 CloseSock(si->si_peerFd);
836 /*-----------------------------------------------------------------*/
838 SocketReadyToWrite(int fd)
840 SockInfo *si = &sockInfo[fd];
842 /* unblock it and read what it has */
843 si->si_blocked = FALSE;
844 ClearFd(fd, &masterWriteSet);
845 SetFd(fd, &masterReadSet);
847 /* enable reading on peer just in case it was off */
848 if (si->si_peerFd >= 0)
849 SetFd(si->si_peerFd, &masterReadSet);
851 /* if we have data, write it */
852 if (WriteAvailData(fd) != SUCCESS) {
853 /* assume the worst and close */
854 TRACE("CloseSock(): fd=%d WriteAvailData() failed errno=%d errstr=%s\n",
855 fd, errno, strerror(errno));
857 if (si->si_peerFd >= 0) {
858 CloseSock(si->si_peerFd);
864 /* if peer is closed and we're done writing, we should close */
865 if (si->si_peerFd < 0 && si->si_writeBuf->fb_used == 0) {
869 /*-----------------------------------------------------------------*/
871 CloseReqlessConns(void)
873 static int lastSweep;
877 if (lastSweep == now)
881 if (numTotalSliceConns + numNeedingHeaders > MAX_CONNS ||
882 numNeedingHeaders > TARG_SETSIZE/20) {
883 /* second condition is probably an attack - close aggressively */
886 else if (numTotalSliceConns + numNeedingHeaders > FAIRNESS_CUTOFF ||
887 numNeedingHeaders > TARG_SETSIZE/40) {
888 /* sweep a little aggressively */
891 else if (numNeedingHeaders > TARG_SETSIZE/80) {
892 /* just sweep to close strays */
896 /* too little gained - not worth sweeping */
900 /* if it's too old, close it */
901 for (i = 0; i < highestSetFd+1; i++) {
902 if (sockInfo[i].si_needsHeaderSince &&
903 (now - sockInfo[i].si_needsHeaderSince) > maxAge)
907 /*-----------------------------------------------------------------*/
909 MainLoop(int lisSock)
912 OurFDSet tempReadSet, tempWriteSet;
914 int lastConfCheck = 0;
916 signal(SIGPIPE, SIG_IGN);
921 struct timeval timeout;
925 if (now - lastConfCheck > 300) {
927 GetSliceXids(); /* always call - in case new slices created */
931 /* see if there's any activity */
932 tempReadSet = masterReadSet;
933 tempWriteSet = masterWriteSet;
935 /* trim it down if needed */
936 while (highestSetFd > 1 &&
937 (!FD_ISSET(highestSetFd, &tempReadSet)) &&
938 (!FD_ISSET(highestSetFd, &tempWriteSet)))
942 res = select(highestSetFd+1, (fd_set *) &tempReadSet,
943 (fd_set *) &tempWriteSet, NULL, &timeout);
944 if (res < 0 && errno != EINTR) {
951 /* clear the bit for listen socket to avoid confusion */
952 ClearFd(lisSock, &tempReadSet);
954 ceiling = highestSetFd+1; /* copy it, since it changes during loop */
955 /* pass data back and forth as needed */
956 for (i = 0; i < ceiling; i++) {
957 if (FD_ISSET(i, &tempWriteSet))
958 SocketReadyToWrite(i);
960 for (i = 0; i < ceiling; i++) {
961 if (FD_ISSET(i, &tempReadSet))
962 SocketReadyToRead(i);
965 /* see if we need to close conns w/o requests */
971 /* try accepting new connections */
973 struct sockaddr_in addr;
974 socklen_t lenAddr = sizeof(addr);
975 if ((newSock = accept(lisSock, (struct sockaddr *) &addr,
977 /* make socket non-blocking */
978 if (fcntl(newSock, F_SETFL, O_NONBLOCK) < 0) {
982 memset(&sockInfo[newSock], 0, sizeof(SockInfo));
983 sockInfo[newSock].si_needsHeaderSince = now;
985 sockInfo[newSock].si_peerFd = -1;
986 sockInfo[newSock].si_cliAddr = addr.sin_addr;
987 sockInfo[newSock].si_whichService = -1;
988 SetFd(newSock, &masterReadSet);
990 } while (newSock >= 0);
993 /*-----------------------------------------------------------------*/
1000 pidfile = fopen(PIDFILE, "w");
1001 if (pidfile == NULL) {
1002 fprintf(stderr, "%s creation failed\n", PIDFILE);
1006 if ((pid = fork()) < 0) {
1010 else if (pid != 0) {
1011 /* i'm the parent, writing down the child pid */
1012 fprintf(pidfile, "%u\n", pid);
1017 /* close the pid file */
1020 /* routines for any daemon process
1021 1. create a new session
1022 2. change directory to the root
1023 3. change the file creation permission
1031 /*-----------------------------------------------------------------*/
1035 static const char* logfile = "/var/log/codemux.log";
1038 logfd = open(logfile, O_WRONLY | O_APPEND | O_CREAT, 0600);
1040 fprintf(stderr, "cannot open the logfile err=%s\n",
1045 /* duplicate logfile to stderr */
1046 if (dup2(logfd, STDERR_FILENO) != STDERR_FILENO) {
1047 fprintf(stderr, "cannot open the logfile err=%s\n",
1052 /* set the close-on-exec flag */
1053 if (fcntl(STDERR_FILENO, F_SETFD, 1) != 0) {
1054 fprintf(stderr, "fcntl to set the close-on-exec flag failed err=%s\n",
1061 /*-----------------------------------------------------------------*/
1063 main(int argc, char *argv[])
1068 /* do the daemon stuff */
1069 if (argc <= 1 || strcmp(argv[1], "-d") != 0) {
1070 if (InitDaemon() < 0) {
1071 fprintf(stderr, "codemux daemon_init() failed\n");
1076 /* create the accept socket */
1077 if ((lisSock = CreatePrivateAcceptSocket(DEMUX_PORT, TRUE)) < 0) {
1078 fprintf(stderr, "failed creating accept socket\n");
1081 SetFd(lisSock, &masterReadSet);
1083 /* open the log file */
1084 logFd = OpenLogFile();
1087 /* write down the version */
1088 fprintf(stderr, "CoDemux version %s started\n", CODEMUX_VERSION);
1093 /* this is the parent - just wait */
1094 while (wait3(NULL, 0, NULL) < 1)
1095 ; /* just keep waiting for a real pid */
1104 /*-----------------------------------------------------------------*/