source: libcaca/trunk/src/cacaserver.c @ 4333

Last change on this file since 4333 was 4333, checked in by Sam Hocevar, 10 years ago

Large source code cleanup, getting rid of spaces, tabs, and svn keywords.

  • Property svn:keywords set to Id
File size: 14.6 KB
Line 
1/*
2 *  cacaserver    Colour ASCII-Art library
3 *  Copyright (c) 2006 Jean-Yves Lamoureux <jylam@lnxscene.org>
4 *                2006-2009 Sam Hocevar <sam@hocevar.net>
5 *                All Rights Reserved
6 *
7 *  This program is free software. It comes without any warranty, to
8 *  the extent permitted by applicable law. You can redistribute it
9 *  and/or modify it under the terms of the Do What The Fuck You Want
10 *  To Public License, Version 2, as published by Sam Hocevar. See
11 *  http://sam.zoy.org/wtfpl/COPYING for more details.
12 */
13
14#include "config.h"
15
16#include <stdio.h>
17#include <string.h>
18#include <stdlib.h>
19#if defined(HAVE_ARPA_INET_H)
20#   include <arpa/inet.h>
21#elif defined(HAVE_WINSOCK2_H)
22#   include <winsock2.h>
23#   include <ws2tcpip.h>
24#   define USE_WINSOCK 1
25#endif
26#if defined(HAVE_NETINET_IN_H)
27#   include <netinet/in.h>
28#endif
29#if defined(HAVE_UNISTD_H)
30#   include <unistd.h>
31#endif
32#include <sys/types.h>
33#include <sys/socket.h>
34#include <fcntl.h>
35#include <signal.h>
36#include <errno.h>
37#include <stdarg.h>
38
39#ifndef USE_WINSOCK
40#   define USE_WINSOCK 0
41#endif
42
43#include "caca.h"
44
45#define BACKLOG 1337     /* Number of pending connections */
46#define INBUFFER 32      /* Size of per-client input buffer */
47#define OUTBUFFER 300000 /* Size of per-client output buffer */
48
49/* Following vars are static */
50#define INIT_PREFIX \
51    "\xff\xfb\x01"     /* WILL ECHO */ \
52    "\xff\xfb\x03"     /* WILL SUPPRESS GO AHEAD */ \
53    "\xff\xfd\x31"     /* DO NAWS */ \
54    "\xff\x1f\xfa____" /* SB NAWS */ \
55    "\xff\xf0"         /* SE */  \
56    "\033]2;caca for the network\x07" /* Change window title */ \
57    "\033[H\033[J" /* Clear screen */
58    /*"\033[?25l"*/ /* Hide cursor */
59
60#define ANSI_PREFIX \
61    "\033[1;1H" /* move(0,0) */ \
62    "\033[1;1H" /* move(0,0) again */
63
64#define ANSI_RESET \
65    "    " /* Garbage */ \
66    "\033[?1049h" /* Clear screen */ \
67    "\033[?1049h" /* Clear screen again */
68
69static char const telnet_commands[16][5] =
70{
71    "SE  ", "NOP ", "DM  ", "BRK ", "IP  ", "AO  ", "AYT ", "EC  ",
72    "EL  ", "GA  ", "SB  ", "WILL", "WONT", "DO  ", "DONT", "IAC "
73};
74
75static char const telnet_options[37][5] =
76{
77    "????", "ECHO", "????", "SUGH", "????", "STTS", "TIMK", "????",
78    "????", "????", "????", "????", "????", "????", "????", "????",
79    "????", "????", "????", "????", "????", "????", "????", "????",
80    "TTYP", "????", "????", "????", "????", "????", "????", "NAWS",
81    "TRSP", "RMFC", "LIMO", "????", "EVAR"
82};
83
84#define COMMAND_NAME(x) (x>=240)?telnet_commands[x-240]:"????"
85#define OPTION_NAME(x) (x<=36)?telnet_options[x]:"????"
86
87struct client
88{
89    int fd;
90    int ready;
91    uint8_t inbuf[INBUFFER];
92    int inbytes;
93    uint8_t outbuf[OUTBUFFER];
94    int start, stop;
95};
96
97struct server
98{
99    unsigned int width, height;
100    unsigned int port;
101    int sockfd;
102    struct sockaddr_in my_addr;
103    socklen_t sin_size;
104
105    /* Input buffer */
106    uint8_t *input;
107    unsigned int read;
108
109    char prefix[sizeof(INIT_PREFIX)];
110
111    caca_canvas_t *canvas;
112    void *buffer;
113    size_t buflen;
114
115    int client_count;
116    struct client *clients;
117
118    RETSIGTYPE (*sigpipe_handler)(int);
119};
120
121static void manage_connections(struct server *server);
122static int send_data(struct server *server, struct client *c);
123ssize_t nonblock_write(int fd, void *buf, size_t len);
124
125int main(void)
126{
127    int i, yes = 1, flags;
128    struct server *server;
129    char *tmp;
130
131#if USE_WINSOCK
132    WORD winsockVersion;
133    WSADATA wsaData;
134    winsockVersion = MAKEWORD(1, 1);
135
136    WSAStartup(winsockVersion, &wsaData);
137#endif
138    server = malloc(sizeof(struct server));
139
140    server->input = malloc(12);
141    server->read = 0;
142
143    server->client_count = 0;
144    server->clients = NULL;
145    server->port = 0xCACA; /* 51914 */
146
147    /* FIXME, handle >255 sizes */
148    memcpy(server->prefix, INIT_PREFIX, sizeof(INIT_PREFIX));
149    tmp = strstr(server->prefix, "____");
150    tmp[0] = (uint8_t) (server->width & 0xff00) >> 8;
151    tmp[1] = (uint8_t) server->width & 0xff;
152    tmp[2] = (uint8_t) (server->height & 0xff00) >> 8;
153    tmp[3] = (uint8_t) server->height & 0xff;
154
155    if((server->sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
156    {
157        perror("socket");
158        return -1;
159    }
160
161    if(setsockopt(server->sockfd, SOL_SOCKET,
162                  SO_REUSEADDR, &yes, sizeof(int)) == -1)
163    {
164        perror("setsockopt SO_REUSEADDR");
165        return -1;
166    }
167
168    server->my_addr.sin_family = AF_INET;
169    server-> my_addr.sin_port = htons(server->port);
170    server->my_addr.sin_addr.s_addr = INADDR_ANY;
171    memset(&(server->my_addr.sin_zero), '\0', 8);
172
173    if(bind(server->sockfd, (struct sockaddr *)&server->my_addr,
174             sizeof(struct sockaddr)) == -1)
175    {
176        perror("bind");
177        return -1;
178    }
179
180    /* Non blocking socket */
181    flags = fcntl(server->sockfd, F_GETFL, 0);
182    fcntl(server->sockfd, F_SETFL, flags | O_NONBLOCK);
183
184    if(listen(server->sockfd, BACKLOG) == -1)
185    {
186        perror("listen");
187        return -1;
188    }
189
190    server->canvas = caca_create_canvas(0, 0);
191    server->buffer = NULL;
192
193    /* Ignore SIGPIPE */
194    server->sigpipe_handler = signal(SIGPIPE, SIG_IGN);
195
196    fprintf(stderr, "initialised network, listening on port %i\n",
197                    server->port);
198
199    /* Main loop */
200    for(;;)
201    {
202restart:
203        /* Manage new connections as this function will be called sometimes
204         * more often than display */
205        manage_connections(server);
206
207        /* Read data from stdin */
208        if(server->read < 12)
209        {
210            read(0, server->input + server->read, 12 - server->read);
211            server->read = 12;
212        }
213
214        while(caca_import_canvas_from_memory(server->canvas, server->input,
215                                             server->read, "caca") < 0)
216        {
217            memmove(server->input, server->input + 1, server->read - 1);
218            read(0, server->input + server->read - 1, 1);
219        }
220
221        for(;;)
222        {
223            ssize_t needed, wanted;
224
225            needed = caca_import_canvas_from_memory(server->canvas,
226                                                    server->input,
227                                                    server->read, "caca");
228            if(needed < 0)
229                goto restart;
230
231            if(needed > 0)
232            {
233                server->read -= needed;
234                memmove(server->input, server->input + needed, server->read);
235                break;
236            }
237
238            server->input = realloc(server->input, server->read + 128);
239            wanted = read(0, server->input + server->read, 128);
240            if(wanted < 0)
241                goto restart;
242            server->read += wanted;
243        }
244
245        /* Free the previous export buffer, if any */
246        if(server->buffer)
247        {
248            free(server->buffer);
249            server->buffer = NULL;
250        }
251
252        /* Get ANSI representation of the image and skip the end-of buffer
253         * linefeed ("\r\n", 2 byte) */
254        server->buffer = caca_export_canvas_to_memory(server->canvas, "utf8cr",
255                                                      &server->buflen);
256        server->buflen -= 2;
257
258        for(i = 0; i < server->client_count; i++)
259        {
260            if(server->clients[i].fd == -1)
261                continue;
262
263            if(send_data(server, &server->clients[i]))
264            {
265                fprintf(stderr, "[%i] dropped connection\n",
266                                server->clients[i].fd);
267                close(server->clients[i].fd);
268                server->clients[i].fd = -1;
269            }
270        }
271    }
272
273    /* Kill all remaining clients */
274    for(i = 0; i < server->client_count; i++)
275    {
276        if(server->clients[i].fd == -1)
277            continue;
278
279        close(server->clients[i].fd);
280        server->clients[i].fd = -1;
281    }
282
283    if(server->buffer)
284        free(server->buffer);
285
286    caca_free_canvas(server->canvas);
287
288    /* Restore SIGPIPE handler */
289    signal(SIGPIPE, server->sigpipe_handler);
290
291    free(server);
292
293#if USE_WINSOCK
294    WSACleanup();
295#endif
296    return 0;
297}
298
299/*
300 * XXX: The following functions are local
301 */
302
303static void manage_connections(struct server *server)
304{
305    int fd, flags;
306    struct sockaddr_in remote_addr;
307    socklen_t len = sizeof(struct sockaddr_in);
308
309    fd = accept(server->sockfd, (struct sockaddr *)&remote_addr, &len);
310    if(fd == -1)
311        return;
312
313    fprintf(stderr, "[%i] connected from %s\n",
314                    fd, inet_ntoa(remote_addr.sin_addr));
315
316    /* Non blocking socket */
317    flags = fcntl(fd, F_SETFL, 0);
318    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
319
320    if(server->clients == NULL)
321    {
322        server->clients = malloc(sizeof(struct client));
323        if(server->clients == NULL)
324            return;
325    }
326    else
327    {
328        server->clients = realloc(server->clients,
329                            (server->client_count+1) * sizeof(struct client));
330    }
331
332    server->clients[server->client_count].fd = fd;
333    server->clients[server->client_count].ready = 0;
334    server->clients[server->client_count].inbytes = 0;
335    server->clients[server->client_count].start = 0;
336    server->clients[server->client_count].stop = 0;
337
338    /* If we already have data to send, send it to the new client */
339    if(send_data(server, &server->clients[server->client_count]))
340    {
341        fprintf(stderr, "[%i] dropped connection\n", fd);
342        close(fd);
343        server->clients[server->client_count].fd = -1;
344        return;
345    }
346
347    server->client_count++;
348}
349
350static int send_data(struct server *server, struct client *c)
351{
352    ssize_t ret;
353
354    /* Not for us */
355    if(c->fd < 0)
356        return -1;
357
358    /* Listen to incoming data */
359    for(;;)
360    {
361        ret = read(c->fd, c->inbuf + c->inbytes, 1);
362        if(ret <= 0)
363            break;
364
365        c->inbytes++;
366
367        /* Check for telnet sequences */
368        if(c->inbuf[0] == 0xff)
369        {
370            if(c->inbytes == 1)
371            {
372                ;
373            }
374            else if(c->inbuf[1] == 0xfd || c->inbuf[1] == 0xfc)
375            {
376                if(c->inbytes == 3)
377                {
378                    fprintf(stderr, "[%i] said: %.02x %.02x %.02x (%s %s %s)\n",
379                            c->fd, c->inbuf[0], c->inbuf[1], c->inbuf[2],
380                            COMMAND_NAME(c->inbuf[0]), COMMAND_NAME(c->inbuf[1]), OPTION_NAME(c->inbuf[2]));
381                    /* Just ignore, lol */
382                    c->inbytes = 0;
383                }
384            }
385            else
386                c->inbytes = 0;
387        }
388        else if(c->inbytes == 1)
389        {
390            if(c->inbuf[0] == 0x03)
391            {
392                fprintf(stderr, "[%i] pressed C-c\n", c->fd);
393                return -1; /* User requested to quit */
394            }
395
396            c->inbytes = 0;
397        }
398    }
399
400    /* Send the telnet initialisation commands */
401    if(!c->ready)
402    {
403        ret = nonblock_write(c->fd, server->prefix, sizeof(INIT_PREFIX));
404        if(ret == -1)
405            return (errno == EAGAIN) ? 0 : -1;
406
407        if(ret < (ssize_t)sizeof(INIT_PREFIX))
408            return 0;
409
410        c->ready = 1;
411    }
412
413    /* No error, there's just nothing to send yet */
414    if(!server->buffer)
415        return 0;
416
417    /* If we have backlog, send the backlog */
418    if(c->stop)
419    {
420        ret = nonblock_write(c->fd, c->outbuf + c->start, c->stop - c->start);
421
422        if(ret == -1)
423        {
424            if(errno == EAGAIN)
425                ret = 0;
426            else
427            {
428                fprintf(stderr, "[%i] failed (%s)\n",
429                        c->fd, strerror(errno));
430                return -1;
431            }
432        }
433
434        if(ret == c->stop - c->start)
435        {
436            /* We got rid of the backlog! */
437            c->start = c->stop = 0;
438        }
439        else
440        {
441            c->start += ret;
442
443            if(c->stop - c->start + strlen(ANSI_PREFIX) + server->buflen
444                > OUTBUFFER)
445            {
446                /* Overflow! Empty buffer and start again */
447                memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
448                c->start = 0;
449                c->stop = strlen(ANSI_RESET);
450                return 0;
451            }
452
453            /* Need to move? */
454            if(c->stop + strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
455            {
456                memmove(c->outbuf, c->outbuf + c->start, c->stop - c->start);
457                c->stop -= c->start;
458                c->start = 0;
459            }
460
461            memcpy(c->outbuf + c->stop, ANSI_PREFIX, strlen(ANSI_PREFIX));
462            c->stop += strlen(ANSI_PREFIX);
463            memcpy(c->outbuf + c->stop, server->buffer, server->buflen);
464            c->stop += server->buflen;
465
466            return 0;
467        }
468    }
469
470    /* We no longer have backlog, send our new data */
471
472    /* Send ANSI prefix */
473    ret = nonblock_write(c->fd, ANSI_PREFIX, strlen(ANSI_PREFIX));
474    if(ret == -1)
475    {
476        if(errno == EAGAIN)
477            ret = 0;
478        else
479        {
480            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
481            return -1;
482        }
483    }
484
485    if(ret < (ssize_t)strlen(ANSI_PREFIX))
486    {
487        if(strlen(ANSI_PREFIX) + server->buflen > OUTBUFFER)
488        {
489            /* Overflow! Empty buffer and start again */
490            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
491            c->start = 0;
492            c->stop = strlen(ANSI_RESET);
493            return 0;
494        }
495
496        memcpy(c->outbuf, ANSI_PREFIX, strlen(ANSI_PREFIX) - ret);
497        c->stop = strlen(ANSI_PREFIX) - ret;
498        memcpy(c->outbuf + c->stop, server->buffer, server->buflen);
499        c->stop += server->buflen;
500
501        return 0;
502    }
503
504    /* Send actual data */
505    ret = nonblock_write(c->fd, server->buffer, server->buflen);
506    if(ret == -1)
507    {
508        if(errno == EAGAIN)
509            ret = 0;
510        else
511        {
512            fprintf(stderr, "[%i] failed (%s)\n", c->fd, strerror(errno));
513            return -1;
514        }
515    }
516
517    if(ret < (int)server->buflen)
518    {
519        if(server->buflen > OUTBUFFER)
520        {
521            /* Overflow! Empty buffer and start again */
522            memcpy(c->outbuf, ANSI_RESET, strlen(ANSI_RESET));
523            c->start = 0;
524            c->stop = strlen(ANSI_RESET);
525            return 0;
526        }
527
528        memcpy(c->outbuf, server->buffer, server->buflen - ret);
529        c->stop = server->buflen - ret;
530
531        return 0;
532    }
533
534    return 0;
535}
536
537ssize_t nonblock_write(int fd, void *buf, size_t len)
538{
539    size_t total = 0;
540    ssize_t ret;
541
542    while(total < len)
543    {
544        do
545        {
546            ret = write(fd, buf, len);
547        }
548        while(ret < 0 && errno == EINTR);
549
550        if(ret < 0)
551            return ret;
552        else if(ret == 0)
553            return total;
554
555        total += len;
556        buf = (void *)((uintptr_t)buf + len);
557    }
558
559    return total;
560}
561
Note: See TracBrowser for help on using the repository browser.