1 #include <sys/types.h> 2 #include <sys/stat.h> 3 #include <sys/socket.h> 4 #include <netinet/in.h> 5 #include <sys/un.h> 6 #include <arpa/inet.h> 7 #include <netinet/in_systm.h> 8 #include <netinet/ip.h> 9 #include <string.h> 10 #include <stdio.h> 11 #include <errno.h> 12 #include <unistd.h> 13 #include "mbuf.h" 14 #include "log.h" 15 #include "loadalias.h" 16 #include "vars.h" 17 #include "server.h" 18 19 int server = UNKNOWN_SERVER; 20 static struct sockaddr_un ifsun; 21 static char *rm; 22 23 int 24 ServerLocalOpen(const char *name, mode_t mask) 25 { 26 int s; 27 28 ifsun.sun_len = strlen(name); 29 if (ifsun.sun_len > sizeof ifsun.sun_path - 1) { 30 LogPrintf(LogERROR, "Local: %s: Path too long\n", name); 31 return 1; 32 } 33 ifsun.sun_family = AF_LOCAL; 34 strcpy(ifsun.sun_path, name); 35 36 s = socket(PF_LOCAL, SOCK_STREAM, 0); 37 if (s < 0) { 38 LogPrintf(LogERROR, "Local: socket: %s\n", strerror(errno)); 39 return 2; 40 } 41 42 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &s, sizeof s); 43 mask = umask(mask); 44 if (bind(s, (struct sockaddr *) &ifsun, sizeof(ifsun)) < 0) { 45 umask(mask); 46 LogPrintf(LogERROR, "Local: bind: %s\n", strerror(errno)); 47 if (errno == EADDRINUSE && VarTerm) 48 fprintf(VarTerm, "Wait for a while, then try again.\n"); 49 close(s); 50 unlink(name); 51 return 3; 52 } 53 umask(mask); 54 if (listen(s, 5) != 0) { 55 LogPrintf(LogERROR, "Local: Unable to listen to socket - OS overload?\n"); 56 close(s); 57 unlink(name); 58 return 4; 59 } 60 ServerClose(); 61 server = s; 62 rm = ifsun.sun_path; 63 LogPrintf(LogPHASE, "Listening at local socket %s.\n", name); 64 return 0; 65 } 66 67 int 68 ServerTcpOpen(int port) 69 { 70 struct sockaddr_in ifsin; 71 int s; 72 73 s = socket(PF_INET, SOCK_STREAM, 0); 74 if (s < 0) { 75 LogPrintf(LogERROR, "Tcp: socket: %s\n", strerror(errno)); 76 return 5; 77 } 78 ifsin.sin_family = AF_INET; 79 ifsin.sin_addr.s_addr = INADDR_ANY; 80 ifsin.sin_port = htons(port); 81 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &s, sizeof s); 82 if (bind(s, (struct sockaddr *) &ifsin, sizeof(ifsin)) < 0) { 83 LogPrintf(LogERROR, "Tcp: bind: %s\n", strerror(errno)); 84 if (errno == EADDRINUSE && VarTerm) 85 fprintf(VarTerm, "Wait for a while, then try again.\n"); 86 close(s); 87 return 6; 88 } 89 if (listen(s, 5) != 0) { 90 LogPrintf(LogERROR, "Tcp: Unable to listen to socket - OS overload?\n"); 91 close(s); 92 return 7; 93 } 94 ServerClose(); 95 server = s; 96 LogPrintf(LogPHASE, "Listening at port %d.\n", port); 97 return 0; 98 } 99 100 void 101 ServerClose() 102 { 103 if (server >= 0) { 104 close(server); 105 if (rm) { 106 unlink(rm); 107 rm = 0; 108 } 109 } 110 server = -1; 111 } 112 113 int 114 ServerType() 115 { 116 if (server == UNKNOWN_SERVER) 117 return UNKNOWN_SERVER; 118 else if (server == NO_SERVER) 119 return NO_SERVER; 120 else if (rm) 121 return LOCAL_SERVER; 122 else 123 return INET_SERVER; 124 } 125