#include #include #include #include #include #include #include #define BUFFER_SIZE 4096 #define BACKLOG_SIZE 50 #define PHP_BIN "/usr/bin/php" #define PHP_MODULE "./JabberExternModule.php" void spawn_php(char *data); int main(int argc, char** argv) { int port, sock, nsock; ssize_t datacount, ndata; size_t datasize = 0; char *data = NULL; struct sockaddr_in saddr; if (argc < 2) { fprintf(stderr,"USAGE : %s \n", argv[0]); return 2; } port = atoi(argv[1]); printf("Daemon serving at port %d\n", port); sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("socket failed to be created"); return 1; } memset(&saddr, 0, sizeof(struct sockaddr_in)); saddr.sin_family = AF_INET; saddr.sin_port = htons(port); inet_aton("0.0.0.0", &saddr.sin_addr); if(bind(sock, (struct sockaddr*)&saddr, sizeof(struct sockaddr_in)) < 0) { perror("socket failed to bind"); return 1; } if (listen(sock, BACKLOG_SIZE) < 0) { perror("socket failed to start listening"); return 1; } printf("Daemon connected, waiting for connections\n"); while ((nsock = accept(sock, NULL, NULL)) >= 0) { printf("Incoming connection accepted\n"); if (!data) { data = (char*)calloc(BUFFER_SIZE, sizeof(char)); datasize = BUFFER_SIZE * sizeof(char); } else { memset(data,0,datasize); } datacount = 0; do { ndata = recv(nsock, data+datacount, datasize, 0); datacount += ndata; if (datacount >= datasize) { data = (char*)realloc(data,datasize+BUFFER_SIZE); memset(data+datasize,0,BUFFER_SIZE); datasize += BUFFER_SIZE; } } while (ndata > 0); /* no need to maintain connection */ close(nsock); if (datacount > 0) spawn_php(data); else perror("Failed getting a command, connection shut down"); printf("Waiting for another job to connect\n"); } perror("Connexion lost, stopping daemon"); return 1; } void spawn_php(char *data) { int cpid = fork(); if (cpid == 0) { execlp(PHP_BIN, "-f", PHP_MODULE, data, NULL); perror("Couldn't spawn child process"); exit(1); } else if (cpid < 0) { fprintf(stderr, "Couldn't fork : restarter will now shut down\n"); exit(1); } }