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

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