Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 5f958e98ed
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 278 lines (243 sloc) 7.737 kb
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
/*
* sup.c
* Multi-threaded chat server
* Author: Eugene Ma
* http://github.com/edma2
*/
#include <stdio.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/wait.h>
#include <netdb.h>
#include <pthread.h>
#include <string.h>

#define NUM_THREADS 4
#define QUEUE_MAX 16

/* Waiting client sockets */
struct {
        pthread_cond_t empty;
        pthread_mutex_t mutex;
        int sockets[QUEUE_MAX];
        int read, write;
} queue;

/* Active client sockets */
typedef struct Node Node;
struct {
        Node *head;
        pthread_mutex_t mutex;
} list;

struct Node {
        Node *next;
        int sock;
};

void queue_init(void);
int queue_add(int sock);
int queue_get(void);

static int queue_size(void);

void list_init(void);
void list_delete(int sock);
Node *list_append(int sock);
int list_broadcast(char *buf, int len, int except);

void *run(void *arg);
void chat_loop(int client);

void logger(const char *format, ...) {
        va_list ap;

        va_start(ap, format);
        fprintf(stderr, "sup: ");
        vfprintf(stderr, format, ap);
        va_end(ap);
        fprintf(stderr, "\n");
}

int main(int argc, char *argv[]) {
        struct addrinfo *res, *ap, hints;
        struct sockaddr sa;
        socklen_t len = sizeof(struct sockaddr);
        char hostname[256];
        int family;
        int listener, client, i;
        pthread_t worker_th;
        void *src;

        if (argc != 3) {
                printf("Usage: %s <ip> <port>\n", argv[0]);
                return -1;
        }

        memset(&hints, 0, sizeof(hints));
        hints.ai_socktype = SOCK_STREAM;
        if (getaddrinfo(argv[1], argv[2], &hints, &res)) {
                perror("getaddrinfo");
                return -1;
        }
        /* Bind socket to a valid socket address */
        for (ap = res; ap != NULL; ap = ap->ai_next) {
                family = ap->ai_family;
                listener = socket(family, ap->ai_socktype, ap->ai_protocol);
                if (listener >= 0
                    && bind(listener, ap->ai_addr, ap->ai_addrlen) >= 0
                    && listen(listener, 5) >= 0)
                        break;
                close(listener);
        }
        freeaddrinfo(res);
        if (ap == NULL) {
                logger("unable to bind address");
                return -1;
        }
        if (family == AF_INET6)
                logger("IPv6 detected!");
        else
                logger("IPv4 only...");
        logger("listening on %s %s", argv[1], argv[2]);

        /* Start thread pool */
        queue_init();
        for (i = 0; i < NUM_THREADS; i++) {
                logger("starting thread %d", i);
                if (pthread_create(&worker_th, NULL, run, NULL) < 0)
                        perror("pthread_create");
                else if (pthread_detach(worker_th) < 0)
                        perror("pthread_detach");
                else
                        continue;
                close(listener);
                return -1;
        }
        /* Accept connections and pass sockets to queue */
        list_init();
        while (1) {
                client = accept(listener, &sa, &len);
                if (client < 0) {
                        perror("accept");
                        break;
                }
                src = (family == AF_INET6) ?
                        (void *)&((struct sockaddr_in6 *)&sa)->sin6_addr :
                        (void *)&((struct sockaddr_in *)&sa)->sin_addr;
                if (inet_ntop(family, src, hostname, sizeof(hostname)) != NULL)
                        logger("new connection from %s!", hostname);
                if (queue_add(client) < 0)
                        close(client);
        }
        close(listener);
        return 0;
}

/* Initialize synchronization variables and reset queue pointers */
void queue_init(void) {
        pthread_mutex_init(&queue.mutex, NULL);
        pthread_cond_init(&queue.empty, NULL);
        queue.read = 0;
        queue.write = 0;
}

/* Get socket from queue */
int queue_get(void) {
        int sock;

        pthread_mutex_lock(&queue.mutex);

        /* Wait until we see an item in the queue */
        while (!queue_size())
                pthread_cond_wait(&queue.empty, &queue.mutex);

        sock = queue.sockets[queue.read];
        queue.read = (queue.read+1)%QUEUE_MAX;
        pthread_mutex_unlock(&queue.mutex);
        return sock;
}

/* Add socket to queue */
int queue_add(int sock) {
        pthread_mutex_lock(&queue.mutex);

        /* Return immediately if queue full */
        if (queue_size() == QUEUE_MAX-1) {
                pthread_mutex_unlock(&queue.mutex);
                return -1;
        }

        /* Add socket to queue and wake up waiters */
        queue.sockets[queue.write] = sock;
        queue.write = (queue.write+1)%QUEUE_MAX;
        pthread_cond_signal(&queue.empty);
        pthread_mutex_unlock(&queue.mutex);
        return 0;
}

/* Return the number of elements in the queue */
static int queue_size(void) {
        return (QUEUE_MAX - queue.read + queue.write)%QUEUE_MAX;
}

/* Initialize synchronization variables and set head to NULL. */
void list_init(void) {
        list.head = NULL;
        pthread_mutex_init(&list.mutex, NULL);
}

/* Append an active socket to the socket list. */
Node *list_append(int sock) {
        Node *p;

        p = malloc(sizeof(Node));
        if (p == NULL)
                return NULL;
        p->sock = sock;
        pthread_mutex_lock(&list.mutex);
        p->next = list.head;
        list.head = p;
        pthread_mutex_unlock(&list.mutex);
        return p;
}

/* Delete a dead socket from the socket list. */
void list_delete(int sock) {
        Node *p, *prev;

        pthread_mutex_lock(&list.mutex);
        for (p = list.head; p != NULL; p = p->next) {
                if (p->sock == sock)
                        break;
                prev = p;
        }
        if (p != NULL) {
                if (p == list.head)
                        list.head = p->next;
                else
                        prev->next = p->next;
                free(p);
        }
        pthread_mutex_unlock(&list.mutex);
}

/* Write message to all sockets except last argument. */
int list_broadcast(char *buf, int len, int except) {
        Node *p;

        pthread_mutex_lock(&list.mutex);
        for (p = list.head; p != NULL; p = p->next) {
                if (p->sock == except)
                        continue;
                if (write(p->sock, buf, len) != len)
                        return -1;
        }
        pthread_mutex_unlock(&list.mutex);
        return 0;
}

/* Fetch sockets from queue and process client requests */
void *run(void *arg) {
        int client;

        while (1) {
                client = queue_get();
                list_append(client);
                chat_loop(client);
                list_delete(client);
                close(client);
        }
        return NULL;
}

/* Broadcast every message received to other clients */
void chat_loop(int client) {
        char buf[1024];
        int bytes_read;

        while (1) {
                bytes_read = read(client, buf, sizeof(buf)-1);
                if (bytes_read < 0) {
                        perror("read");
                        break;
                }
                if (!bytes_read) {
                        logger("Client closed connection!");
                        break;
                }
                buf[bytes_read] = '\0';
                if (list_broadcast(buf, bytes_read+1, client) < 0) {
                        perror("write");
                        break;
                }
        }
}
Something went wrong with that request. Please try again.