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)
460 char lowerBuf[FB_ALLOCSIZE];
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 StrcpyLower(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)) {
514 /* see if URL prefix matches */
515 if ((end = strchr(lowerBuf, '\n')) != NULL)
517 if ((url = GetField(lowerBuf, 1)) == NULL ||
519 /* bad request - let apache handle it ? */
523 url++; /* skip the leading slash */
524 for (i = 1; i < numServices; i++) {
525 if (serviceSig[i].ss_prefix != NULL &&
526 (len = strlen(serviceSig[i].ss_prefix)) > 0 &&
527 strncmp(url, serviceSig[i].ss_prefix, len) == 0 &&
528 (url[len] == ' ' || url[len] == '/')) {
529 int startPos = url - lowerBuf;
530 int stripLen = len + ((url[len] == '/') ? 1 : 0);
531 /* strip out prefix */
532 fb->fb_used -= stripLen;
533 memmove(&buf[startPos], &buf[startPos+stripLen],
534 fb->fb_used + 1 - startPos);
535 /* printf("%s", buf); */
542 /* default to first service */
546 /*-----------------------------------------------------------------*/
548 StartConnect(int origFD, int whichService)
551 struct sockaddr_in dest;
555 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
559 /* make socket non-blocking */
560 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) {
565 /* set addr structure */
566 memset(&dest, 0, sizeof(dest));
567 dest.sin_family = AF_INET;
568 dest.sin_port = htons(serviceSig[whichService].ss_port);
569 dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
571 /* start connection process - we should be told that it's in
573 if (connect(sock, (struct sockaddr *) &dest, sizeof(dest)) != -1 ||
574 errno != EINPROGRESS) {
579 SetFd(sock, &masterWriteSet); /* determine when connect finishes */
580 sockInfo[origFD].si_peerFd = sock;
581 si = &sockInfo[sock];
582 memset(si, 0, sizeof(SockInfo));
583 si->si_peerFd = origFD;
584 si->si_blocked = TRUE; /* still connecting */
585 si->si_whichService = whichService;
586 si->si_writeBuf = sockInfo[origFD].si_readBuf;
587 sockInfo[origFD].si_readBuf->fb_refs++;
588 if (whichService >= 0)
589 SliceConnsInc(whichService);
593 /*-----------------------------------------------------------------*/
595 WriteAvailData(int fd)
597 SockInfo *si = &sockInfo[fd];
598 FlowBuf *fb = si->si_writeBuf;
601 /* printf("trying to write fd %d\n", fd); */
602 if (fb->fb_used < 1 || si->si_blocked)
605 /* printf("trying to write %d bytes\n", fb->fb_used); */
606 /* write(STDOUT_FILENO, fb->fb_buf, fb->fb_used); */
607 if ((res = write(fd, fb->fb_buf, fb->fb_used)) > 0) {
609 if (fb->fb_used > 0) {
610 /* couldn't write all - assume blocked */
611 memmove(fb->fb_buf, &fb->fb_buf[res], fb->fb_used);
612 si->si_blocked = TRUE;
613 SetFd(fd, &masterWriteSet);
615 /* printf("wrote %d\n", res); */
619 /* we might have been full but didn't realize it */
620 if (res == -1 && errno == EAGAIN) {
621 si->si_blocked = TRUE;
622 SetFd(fd, &masterWriteSet);
626 /* otherwise, assume the worst */
629 /*-----------------------------------------------------------------*/
630 static OurFDSet socksToCloseVec;
631 static int numSocksToClose;
632 static int whichSocksToClose[TARG_SETSIZE];
633 /*-----------------------------------------------------------------*/
637 if (FD_ISSET(fd, &socksToCloseVec))
639 SetFd(fd, &socksToCloseVec);
640 whichSocksToClose[numSocksToClose] = fd;
643 /*-----------------------------------------------------------------*/
650 if (buf->fb_refs == 0) {
655 /*-----------------------------------------------------------------*/
657 ReallyCloseSocks(void)
661 memset(&socksToCloseVec, 0, sizeof(socksToCloseVec));
663 for (i = 0; i < numSocksToClose; i++) {
664 int fd = whichSocksToClose[i];
666 DecBuf(sockInfo[fd].si_readBuf);
667 DecBuf(sockInfo[fd].si_writeBuf);
668 ClearFd(fd, &masterReadSet);
669 ClearFd(fd, &masterWriteSet);
670 if (sockInfo[fd].si_needsHeaderSince) {
671 sockInfo[fd].si_needsHeaderSince = 0;
674 if (sockInfo[fd].si_whichService >= 0) {
675 SliceConnsDec(sockInfo[fd].si_whichService);
676 sockInfo[fd].si_whichService = -1;
679 if (sockInfo[fd].si_peerFd >= 0) {
680 sockInfo[sockInfo[fd].si_peerFd].si_peerFd = -1;
685 /*-----------------------------------------------------------------*/
687 SocketReadyToRead(int fd)
689 SockInfo *si = &sockInfo[fd];
694 /* if peer is closed, close ourselves */
695 if (si->si_peerFd < 0 && (!si->si_needsHeaderSince)) {
700 if ((fb = si->si_readBuf) == NULL) {
701 fb = si->si_readBuf = xcalloc(1, sizeof(FlowBuf));
703 if (si->si_peerFd >= 0) {
704 sockInfo[si->si_peerFd].si_writeBuf = fb;
709 if (fb->fb_buf == NULL)
710 fb->fb_buf = xmalloc(FB_ALLOCSIZE);
712 /* determine read buffer size - if 0, then block reads and return */
713 if ((spaceLeft = FB_SIZE - fb->fb_used) <= 0) {
714 if (si->si_needsHeaderSince) {
715 write(fd, err400BadRequest, strlen(err400BadRequest));
720 ClearFd(fd, &masterReadSet);
725 /* read as much as allowed, and is available */
726 if ((res = read(fd, &fb->fb_buf[fb->fb_used], spaceLeft)) == 0) {
728 if (fb->fb_used == 0 && si->si_peerFd >= 0) {
729 CloseSock(si->si_peerFd);
737 TRACE("fd=%d errno=%d errstr=%s\n",fd, errno, strerror(errno));
739 if (fb->fb_used == 0 && si->si_peerFd >= 0) {
740 CloseSock(si->si_peerFd);
746 fb->fb_buf[fb->fb_used] = 0; /* terminate it for convenience */
747 // printf("sock %d, read %d, total %d\n", fd, res, fb->fb_used);
749 /* if we need header, check if we've gotten it. if so, do
750 modifications and continue. if not, check if we've read the
751 maximum, and if so, fail */
752 if (si->si_needsHeaderSince) {
756 #define STATUS_REQ "GET /codemux/status.txt"
757 if (strncasecmp(fb->fb_buf, STATUS_REQ, sizeof(STATUS_REQ)-1) == 0) {
763 // printf("trying to find service\n");
764 if (FindService(fb, &whichService, si->si_cliAddr) != SUCCESS)
766 // printf("found service %d\n", whichService);
767 slice = ServiceToSlice(whichService);
769 /* if it needs to be redirected to PLC, let it be handled here */
770 if (whichService == 0 && domainNamePLCNetflow != NULL &&
771 strcmp(slice->si_sliceName, "root") == 0) {
774 static const char* resp302 =
775 "HTTP/1.0 302 Found\r\n"
776 "Location: http://%s\r\n"
777 "Cache-Control: no-cache, no-store\r\n"
778 "Content-type: text/html\r\n"
779 "Connection: close\r\n"
781 "Your request is being redirected to PLC Netflow http://%s\n";
782 len = snprintf(msg, sizeof(msg), resp302,
783 domainNamePLCNetflow, domainNamePLCNetflow);
788 /* no service can have more than some absolute max number of
789 connections. Also, when we're too busy, start enforcing
790 fairness across the servers */
791 if (slice->si_numConns > SERVICE_MAX ||
792 (numTotalSliceConns > FAIRNESS_CUTOFF &&
793 slice->si_numConns > MAX_CONNS/numActiveSlices)) {
794 write(fd, err503TooBusy, strlen(err503TooBusy));
795 TRACE("CloseSock(): fd=%d too busy\n", fd);
800 if (slice->si_xid > 0) {
801 static int first = 1;
802 setsockopt(fd, SOL_SOCKET, SO_SETXID,
803 &slice->si_xid, sizeof(slice->si_xid));
805 /* just to log it for once */
806 fprintf(stderr, "setsockopt() with XID = %d name = %s\n",
807 slice->si_xid, slice->si_sliceName);
812 si->si_needsHeaderSince = 0;
814 if (StartConnect(fd, whichService) != SUCCESS) {
815 write(fd, err503Unavailable, strlen(err503Unavailable));
816 TRACE("CloseSock(): fd=%d StartConnect() failed\n", fd);
823 /* write anything possible */
824 if (WriteAvailData(si->si_peerFd) != SUCCESS) {
825 /* assume the worst and close */
826 TRACE("CloseSock(): fd=%d WriteAvailData() failed errno=%d errstr=%s\n",
827 fd, errno, strerror(errno));
829 if (si->si_peerFd >=0) {
830 CloseSock(si->si_peerFd);
835 /*-----------------------------------------------------------------*/
837 SocketReadyToWrite(int fd)
839 SockInfo *si = &sockInfo[fd];
841 /* unblock it and read what it has */
842 si->si_blocked = FALSE;
843 ClearFd(fd, &masterWriteSet);
844 SetFd(fd, &masterReadSet);
846 /* enable reading on peer just in case it was off */
847 if (si->si_peerFd >= 0)
848 SetFd(si->si_peerFd, &masterReadSet);
850 /* if we have data, write it */
851 if (WriteAvailData(fd) != SUCCESS) {
852 /* assume the worst and close */
853 TRACE("CloseSock(): fd=%d WriteAvailData() failed errno=%d errstr=%s\n",
854 fd, errno, strerror(errno));
856 if (si->si_peerFd >= 0) {
857 CloseSock(si->si_peerFd);
863 /* if peer is closed and we're done writing, we should close */
864 if (si->si_peerFd < 0 && si->si_writeBuf->fb_used == 0) {
868 /*-----------------------------------------------------------------*/
870 CloseReqlessConns(void)
872 static int lastSweep;
876 if (lastSweep == now)
880 if (numTotalSliceConns + numNeedingHeaders > MAX_CONNS ||
881 numNeedingHeaders > TARG_SETSIZE/20) {
882 /* second condition is probably an attack - close aggressively */
885 else if (numTotalSliceConns + numNeedingHeaders > FAIRNESS_CUTOFF ||
886 numNeedingHeaders > TARG_SETSIZE/40) {
887 /* sweep a little aggressively */
890 else if (numNeedingHeaders > TARG_SETSIZE/80) {
891 /* just sweep to close strays */
895 /* too little gained - not worth sweeping */
899 /* if it's too old, close it */
900 for (i = 0; i < highestSetFd+1; i++) {
901 if (sockInfo[i].si_needsHeaderSince &&
902 (now - sockInfo[i].si_needsHeaderSince) > maxAge)
906 /*-----------------------------------------------------------------*/
908 MainLoop(int lisSock)
911 OurFDSet tempReadSet, tempWriteSet;
913 int lastConfCheck = 0;
915 signal(SIGPIPE, SIG_IGN);
920 struct timeval timeout;
924 if (now - lastConfCheck > 300) {
926 GetSliceXids(); /* always call - in case new slices created */
930 /* see if there's any activity */
931 tempReadSet = masterReadSet;
932 tempWriteSet = masterWriteSet;
934 /* trim it down if needed */
935 while (highestSetFd > 1 &&
936 (!FD_ISSET(highestSetFd, &tempReadSet)) &&
937 (!FD_ISSET(highestSetFd, &tempWriteSet)))
941 res = select(highestSetFd+1, (fd_set *) &tempReadSet,
942 (fd_set *) &tempWriteSet, NULL, &timeout);
943 if (res < 0 && errno != EINTR) {
950 /* clear the bit for listen socket to avoid confusion */
951 ClearFd(lisSock, &tempReadSet);
953 ceiling = highestSetFd+1; /* copy it, since it changes during loop */
954 /* pass data back and forth as needed */
955 for (i = 0; i < ceiling; i++) {
956 if (FD_ISSET(i, &tempWriteSet))
957 SocketReadyToWrite(i);
959 for (i = 0; i < ceiling; i++) {
960 if (FD_ISSET(i, &tempReadSet))
961 SocketReadyToRead(i);
964 /* see if we need to close conns w/o requests */
970 /* try accepting new connections */
972 struct sockaddr_in addr;
973 socklen_t lenAddr = sizeof(addr);
974 if ((newSock = accept(lisSock, (struct sockaddr *) &addr,
976 /* make socket non-blocking */
977 if (fcntl(newSock, F_SETFL, O_NONBLOCK) < 0) {
981 memset(&sockInfo[newSock], 0, sizeof(SockInfo));
982 sockInfo[newSock].si_needsHeaderSince = now;
984 sockInfo[newSock].si_peerFd = -1;
985 sockInfo[newSock].si_cliAddr = addr.sin_addr;
986 sockInfo[newSock].si_whichService = -1;
987 SetFd(newSock, &masterReadSet);
989 } while (newSock >= 0);
992 /*-----------------------------------------------------------------*/
999 pidfile = fopen(PIDFILE, "w");
1000 if (pidfile == NULL) {
1001 fprintf(stderr, "%s creation failed\n", PIDFILE);
1005 if ((pid = fork()) < 0) {
1009 else if (pid != 0) {
1010 /* i'm the parent, writing down the child pid */
1011 fprintf(pidfile, "%u\n", pid);
1016 /* close the pid file */
1019 /* routines for any daemon process
1020 1. create a new session
1021 2. change directory to the root
1022 3. change the file creation permission
1030 /*-----------------------------------------------------------------*/
1034 static const char* logfile = "/var/log/codemux.log";
1037 logfd = open(logfile, O_WRONLY | O_APPEND | O_CREAT, 0600);
1039 fprintf(stderr, "cannot open the logfile err=%s\n",
1044 /* duplicate logfile to stderr */
1045 if (dup2(logfd, STDERR_FILENO) != STDERR_FILENO) {
1046 fprintf(stderr, "cannot open the logfile err=%s\n",
1051 /* set the close-on-exec flag */
1052 if (fcntl(STDERR_FILENO, F_SETFD, 1) != 0) {
1053 fprintf(stderr, "fcntl to set the close-on-exec flag failed err=%s\n",
1060 /*-----------------------------------------------------------------*/
1062 main(int argc, char *argv[])
1068 struct in_addr lisAddress = { .s_addr = htonl(INADDR_ANY) };
1070 while ((opt = getopt(argc, argv, "dl:")) != -1) {
1076 if (inet_pton(AF_INET, optarg, &lisAddress) <= 0) {
1077 fprintf(stderr, "`%s' is not a valid address\n", optarg);
1082 fprintf(stderr, "Usage: %s [-d] [-l <listening address>]\n", argv[0]);
1087 /* do the daemon stuff */
1089 if (InitDaemon() < 0) {
1090 fprintf(stderr, "codemux daemon_init() failed\n");
1095 /* create the accept socket */
1096 if ((lisSock = CreatePrivateAcceptSocket(DEMUX_PORT, TRUE,
1097 &lisAddress)) < 0) {
1098 fprintf(stderr, "failed creating accept socket\n");
1101 SetFd(lisSock, &masterReadSet);
1103 /* open the log file */
1104 logFd = OpenLogFile();
1107 /* write down the version */
1108 fprintf(stderr, "CoDemux version %s started\n", CODEMUX_VERSION);
1113 /* this is the parent - just wait */
1114 while (wait3(NULL, 0, NULL) < 1)
1115 ; /* just keep waiting for a real pid */
1124 /*-----------------------------------------------------------------*/