9 #include <sys/socket.h>
10 #include <sys/select.h>
11 #include <netinet/in.h>
15 static const char *guess_repo_name(const char *path);
16 static int parse_args(int argc, char **argv);
18 static const char *repo_name;
20 static int port = 64357;
22 static struct client *clients;
24 const char *repo_path;
27 int main(int argc, char **argv)
29 struct sockaddr_in addr;
31 if(parse_args(argc, argv) == -1) {
35 if(repo_init(repo_path) == -1) {
41 if(!(repo_name = guess_repo_name(repo_path))) {
46 printf("Serving %s from %s\n", repo_name, repo_path);
48 if(!(lis = socket(PF_INET, SOCK_STREAM, 0))) {
49 fprintf(stderr, "failed to create socket: %s\n", strerror(errno));
53 memset(&addr, 0, sizeof addr);
54 addr.sin_family = AF_INET;
55 addr.sin_port = htons(port);
56 addr.sin_addr.s_addr = INADDR_ANY;
58 if(bind(lis, (struct sockaddr*)&addr, sizeof addr) == -1) {
59 fprintf(stderr, "failed to bind listening socket to port %d\n", port);
67 struct client *c, dummy;
75 if(c->s > max_fd) max_fd = c->s;
79 if((res = select(max_fd + 1, &rdset, 0, 0, 0)) == -1 && errno != EINTR) {
80 perror("select failed");
84 if(res <= 0) continue;
89 if(FD_ISSET(c->next->s, &rdset)) {
90 if(handle_client(c->next) == -1) {
91 struct client *tmp = c->next;
100 clients = dummy.next;
102 if(FD_ISSET(lis, &rdset)) {
103 if((s = accept(lis, 0, 0)) == -1) {
104 perror("failed to accept connection");
107 if(!(c = calloc(1, sizeof *c))) {
108 perror("failed to allocate memory for client structure");
116 send_string(c, "reposerve-0.1 protocol:0\n");
123 static const char *guess_repo_name(const char *path)
125 static char pathbuf[PATH_MAX];
129 if(!realpath(path, pathbuf)) {
132 len = strlen(pathbuf);
134 if(len > 0 && pathbuf[len - 1] == '/') {
137 if(len <= 0) goto fail;
139 if((last_slash = strrchr(pathbuf, '/'))) {
140 return last_slash + 1;
145 fprintf(stderr, "failed to resolve path %s while determining the repo name. Please specify an explicit name with -id\n", repo_path);
149 static void print_usage(const char *argv0)
151 printf("Usage: %s [options] [repo path]\n", argv0);
152 printf("options:\n");
153 printf(" -id <name>: repo identifier (defaults to directory name)\n");
154 printf(" -h,-help: print help and exit\n");
157 static int parse_args(int argc, char **argv)
161 for(i=1; i<argc; i++) {
162 if(argv[i][0] == '-') {
163 if(strcmp(argv[i], "-id") == 0) {
164 repo_name = argv[++i];
165 } else if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0) {
166 print_usage(argv[0]);
169 fprintf(stderr, "invalid option: %s\n", argv[i]);
174 fprintf(stderr, "unexpected argument: %s\n", argv[i]);
181 if(!repo_path) repo_path = ".";