source: libcaca/trunk/caca/driver_network.c @ 605

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