summaryrefslogtreecommitdiff
path: root/src/c/driver.c
blob: 5300371d1f4af01c58c1061b0af24c4dff388066 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#include <stdio.h>

#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <pthread.h>

#include "urweb.h"

int lw_port = 8080;
int lw_backlog = 10;
int lw_bufsize = 1024;

typedef struct node {
  int fd;
  struct node *next;
} *node;

static node front = NULL, back = NULL;

static int empty() {
  return front == NULL;
}

static void enqueue(int fd) {
  node n = malloc(sizeof(struct node));

  n->fd = fd;
  n->next = NULL;
  if (back)
    back->next = n;
  else
    front = n;
  back = n;
}

static int dequeue() {
  int ret = front->fd;

  front = front->next;
  if (!front)
    back = NULL;

  return ret;
}

static pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t queue_cond = PTHREAD_COND_INITIALIZER;

#define MAX_RETRIES 5

static void *worker(void *data) {
  int me = *(int *)data;
  lw_context ctx = lw_init(1024, 1024);

  while (1) {
    char buf[lw_bufsize+1], *back = buf, *s;
    int sock;

    pthread_mutex_lock(&queue_mutex);
    while (empty())
      pthread_cond_wait(&queue_cond, &queue_mutex);
    sock = dequeue();
    pthread_mutex_unlock(&queue_mutex);

    printf("Handling connection with thread #%d.\n", me);

    while (1) {
      unsigned retries_left = MAX_RETRIES;
      int r = recv(sock, back, lw_bufsize - (back - buf), 0);

      if (r < 0) {
        fprintf(stderr, "Recv failed\n");
        break;
      }

      if (r == 0) {
        printf("Connection closed.\n");
        break;
      }

      printf("Received %d bytes.\n", r);

      back += r;
      *back = 0;
    
      if (s = strstr(buf, "\r\n\r\n")) {
        char *cmd, *path, *inputs;

        *s = 0;

        printf("Read: %s\n", buf);
      
        if (!(s = strstr(buf, "\r\n"))) {
          fprintf(stderr, "No newline in buf\n");
          break;
        }

        *s = 0;
        cmd = s = buf;
      
        if (!strsep(&s, " ")) {
          fprintf(stderr, "No first space in HTTP command\n");
          break;
        }

        if (strcmp(cmd, "GET")) {
          fprintf(stderr, "Not ready for non-get command: %s\n", cmd);
          break;
        }

        path = s;
        if (!strsep(&s, " ")) {
          fprintf(stderr, "No second space in HTTP command\n");
          break;
        }

        if (inputs = strchr(path, '?')) {
          char *name, *value;
          *inputs++ = 0;

          while (*inputs) {
            name = inputs;
            if (inputs = strchr(inputs, '&'))
              *inputs++ = 0;
            else
              inputs = strchr(name, 0);

            if (value = strchr(name, '=')) {
              *value++ = 0;
              lw_set_input(ctx, name, value);
            }
            else
              lw_set_input(ctx, name, "");
          }
        }

        printf("Serving URI %s....\n", path);

        while (1) {
          failure_kind fk;

          lw_write(ctx, "HTTP/1.1 200 OK\r\n");
          lw_write(ctx, "Content-type: text/html\r\n\r\n");
          lw_write(ctx, "<html>");

          fk = lw_begin(ctx, path);
          if (fk == SUCCESS) {
            lw_write(ctx, "</html>");
            break;
          } else if (fk == BOUNDED_RETRY) {
            if (retries_left) {
              printf("Error triggers bounded retry: %s\n", lw_error_message(ctx));
              --retries_left;
            }
            else {
              printf("Fatal error (out of retries): %s\n", lw_error_message(ctx));

              lw_reset_keep_error_message(ctx);
              lw_write(ctx, "HTTP/1.1 500 Internal Server Error\n\r");
              lw_write(ctx, "Content-type: text/plain\r\n\r\n");
              lw_write(ctx, "Fatal error (out of retries): ");
              lw_write(ctx, lw_error_message(ctx));
              lw_write(ctx, "\n");
            }
          } else if (fk == UNLIMITED_RETRY)
            printf("Error triggers unlimited retry: %s\n", lw_error_message(ctx));
          else if (fk == FATAL) {
            printf("Fatal error: %s\n", lw_error_message(ctx));

            lw_reset_keep_error_message(ctx);
            lw_write(ctx, "HTTP/1.1 500 Internal Server Error\n\r");
            lw_write(ctx, "Content-type: text/plain\r\n\r\n");
            lw_write(ctx, "Fatal error: ");
            lw_write(ctx, lw_error_message(ctx));
            lw_write(ctx, "\n");

            break;
          } else {
            printf("Unknown lw_handle return code!\n");

            lw_reset_keep_request(ctx);
            lw_write(ctx, "HTTP/1.1 500 Internal Server Error\n\r");
            lw_write(ctx, "Content-type: text/plain\r\n\r\n");
            lw_write(ctx, "Unknown lw_handle return code!\n");

            break;
          }

          lw_reset_keep_request(ctx);
        }

        lw_send(ctx, sock);

        printf("Done with client.\n\n");
        break;
      }
    }

    close(sock);
    lw_reset(ctx);
  }
}

int main(int argc, char *argv[]) {
  // The skeleton for this function comes from Beej's sockets tutorial.
  int sockfd;  // listen on sock_fd
  struct sockaddr_in my_addr;
  struct sockaddr_in their_addr; // connector's address information
  int sin_size, yes = 1;
  int nthreads, i, *names;

  if (argc < 2) {
    fprintf(stderr, "No thread count specified\n");
    return 1;
  }

  nthreads = atoi(argv[1]);
  if (nthreads <= 0) {
    fprintf(stderr, "Invalid thread count\n");
    return 1;
  }
  names = calloc(nthreads, sizeof(int));

  sockfd = socket(PF_INET, SOCK_STREAM, 0); // do some error checking!

  if (sockfd < 0) {
    fprintf(stderr, "Listener socket creation failed\n");
    return 1;
  }

  if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) {
    fprintf(stderr, "Listener socket option setting failed\n");
    return 1;
  }

  my_addr.sin_family = AF_INET;         // host byte order
  my_addr.sin_port = htons(lw_port);    // short, network byte order
  my_addr.sin_addr.s_addr = INADDR_ANY; // auto-fill with my IP
  memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero);

  if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) < 0) {
    fprintf(stderr, "Listener socket bind failed\n");
    return 1;
  }

  if (listen(sockfd, lw_backlog) < 0) {
    fprintf(stderr, "Socket listen failed\n");
    return 1;
  }

  sin_size = sizeof their_addr;

  printf("Listening on port %d....\n", lw_port);

  for (i = 0; i < nthreads; ++i) {
    pthread_t thread;    
    names[i] = i;
    if (pthread_create(&thread, NULL, worker, &names[i])) {
      fprintf(stderr, "Error creating worker thread #%d\n", i);
      return 1;
    }
  }

  while (1) {
    int new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);

    if (new_fd < 0) {
      fprintf(stderr, "Socket accept failed\n");
      return 1;
    }

    printf("Accepted connection.\n");

    pthread_mutex_lock(&queue_mutex);
    enqueue(new_fd);
    pthread_cond_broadcast(&queue_cond);
    pthread_mutex_unlock(&queue_mutex);
  }
}