Use RSA key blinding to protect against timing attacks.
[paraslash.git] / vss.c
1 /*
2  * Copyright (C) 1997-2009 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file vss.c The virtual streaming system.
8  *
9  * This contains the audio streaming code of para_server which is independent
10  * of the current audio format, audio file selector and of the activated
11  * senders.
12  */
13
14 #include <regex.h>
15 #include <dirent.h>
16 #include <osl.h>
17
18 #include "para.h"
19 #include "error.h"
20 #include "portable_io.h"
21 #include "fec.h"
22 #include "string.h"
23 #include "afh.h"
24 #include "afs.h"
25 #include "server.h"
26 #include "net.h"
27 #include "server.cmdline.h"
28 #include "list.h"
29 #include "vss.h"
30 #include "send.h"
31 #include "ipc.h"
32 #include "fd.h"
33 #include "sched.h"
34
35 extern struct misc_meta_data *mmd;
36
37 extern void dccp_send_init(struct sender *);
38 extern void http_send_init(struct sender *);
39 extern void udp_send_init(struct sender *);
40
41 /** The list of supported senders. */
42 struct sender senders[] = {
43         {
44                 .name = "http",
45                 .init = http_send_init,
46         },
47         {
48                 .name = "dccp",
49                 .init = dccp_send_init,
50         },
51         {
52                 .name = "udp",
53                 .init = udp_send_init,
54         },
55         {
56                 .name = NULL,
57         }
58 };
59
60 /** The possible states of the afs socket. */
61 enum afs_socket_status {
62         /** Socket is inactive. */
63         AFS_SOCKET_READY,
64         /** Socket fd was included in the write fd set for select(). */
65         AFS_SOCKET_CHECK_FOR_WRITE,
66         /** vss wrote a request to the socket and waits for reply from afs. */
67         AFS_SOCKET_AFD_PENDING
68 };
69
70 /** The task structure for the virtual streaming system. */
71 struct vss_task {
72         /** Copied from the -announce_time command line option. */
73         struct timeval announce_tv;
74         /** End of the announcing interval. */
75         struct timeval data_send_barrier;
76         /** End of the EOF interval. */
77         struct timeval eof_barrier;
78         /** Only used if --autoplay_delay was given. */
79         struct timeval autoplay_barrier;
80         /** Used for afs-server communication. */
81         int afs_socket;
82         /** The current state of \a afs_socket. */
83         enum afs_socket_status afsss;
84         /** The memory mapped audio file. */
85         char *map;
86         /** Used by the scheduler. */
87         struct task task;
88         /** Pointer to the header of the mapped audio file. */
89         const char *header_buf;
90         /** Length of the audio file header. */
91         size_t header_len;
92         /** Time between audio file headers are sent. */
93         struct timeval header_interval;
94 };
95
96 /**
97  * The list of currently connected fec clients.
98  *
99  * Senders may use \ref vss_add_fec_client() to add entries to the list.
100  */
101 static struct list_head fec_client_list;
102
103 /**
104  * Data associated with one FEC group.
105  *
106  * A FEC group consists of a fixed number of slices and this number is given by
107  * the \a slices_per_group parameter of struct \ref fec_client_parms. Each FEC
108  * group contains a number of chunks of the current audio file.
109  *
110  * FEC slices directly correspond to the data packages sent by the paraslash
111  * senders that use FEC. Each slice is identified by its group number and its
112  * number within the group. All slices have the same size, but the last slice
113  * of the group may not be filled entirely.
114  */
115 struct fec_group {
116         /** The number of the FEC group. */
117         uint32_t num;
118         /** Number of bytes in this group. */
119         uint32_t bytes;
120         /** The first chunk of the current audio file belonging to the group. */
121         uint32_t first_chunk;
122         /** The number of chunks contained in this group. */
123         uint32_t num_chunks;
124         /** When the first chunk was sent. */
125         struct timeval start;
126         /** The group duration divided by the number of slices. */
127         struct timeval slice_duration;
128         /** Group contains the audio file header that occupies that many slices. */
129         uint8_t num_header_slices;
130 };
131
132 /**
133  * Describes one connected FEC client.
134  */
135 struct fec_client {
136         /** If negative, this client is temporarily disabled. */
137         int error;
138         /** Parameters requested by the client. */
139         struct fec_client_parms *fcp;
140         /** Used by the core FEC code. */
141         struct fec_parms *parms;
142         /** The position of this client in the fec client list. */
143         struct list_head node;
144         /** When the first slice for this client was sent. */
145         struct timeval stream_start;
146         /** The first chunk sent to this FEC client. */
147         int first_stream_chunk;
148         /** Describes the current group. */
149         struct fec_group group;
150         /** The current slice. */
151         uint8_t current_slice_num;
152         /** The data to be FEC-encoded (point to a region within the mapped audio file). */
153         const unsigned char **src_data;
154         /** Last time an audio  header was sent. */
155         struct timeval next_header_time;
156         /** Used for the last source pointer of an audio file. */
157         unsigned char *extra_src_buf;
158         /** Extra slices needed to store largest chunk + header. */
159         int num_extra_slices;
160         /** Contains the FEC-encoded data. */
161         unsigned char *enc_buf;
162 };
163
164 /**
165  * Get the chunk time of the current audio file.
166  *
167  * \return A pointer to a struct containing the chunk time, or NULL,
168  * if currently no audio file is selected.
169  */
170 struct timeval *vss_chunk_time(void)
171 {
172         if (mmd->afd.afhi.chunk_tv.tv_sec == 0 &&
173                         mmd->afd.afhi.chunk_tv.tv_usec == 0)
174                 return NULL;
175         return &mmd->afd.afhi.chunk_tv;
176 }
177
178 /**
179  * Write a fec header to a buffer.
180  *
181  * \param buf The buffer to write to.
182  * \param h The fec header to write.
183  */
184 static void write_fec_header(struct fec_client *fc, struct vss_task *vsst)
185 {
186         char *buf = (char *)fc->enc_buf;
187         struct fec_group *g = &fc->group;
188         struct fec_client_parms *p = fc->fcp;
189
190         write_u32(buf, FEC_MAGIC);
191
192         write_u8(buf + 4, p->slices_per_group + fc->num_extra_slices);
193         write_u8(buf + 5, p->data_slices_per_group + fc->num_extra_slices);
194         write_u32(buf + 6, g->num_header_slices? vsst->header_len : 0);
195
196         write_u32(buf + 10, g->num);
197         write_u32(buf + 14, g->bytes);
198
199         write_u8(buf + 18, fc->current_slice_num);
200         write_u16(buf + 20, p->max_slice_bytes - FEC_HEADER_SIZE);
201         write_u8(buf + 22, g->first_chunk? 0 : 1);
202         write_u8(buf + 23, vsst->header_len? 1 : 0);
203         memset(buf + 24, 0, 7);
204 }
205
206 static int need_audio_header(struct fec_client *fc, struct vss_task *vsst)
207 {
208         if (!mmd->current_chunk) {
209                 tv_add(now, &vsst->header_interval, &fc->next_header_time);
210                 return 0;
211         }
212         if (!vsst->header_buf)
213                 return 0;
214         if (!vsst->header_len)
215                 return 0;
216         if (fc->group.num && tv_diff(&fc->next_header_time, now, NULL) > 0)
217                 return 0;
218         tv_add(now, &vsst->header_interval, &fc->next_header_time);
219         return 1;
220 }
221
222 static int num_slices(long unsigned bytes, struct fec_client *fc, uint8_t *result)
223 {
224         unsigned long m = fc->fcp->max_slice_bytes - FEC_HEADER_SIZE;
225         unsigned rv, redundant_slices = fc->fcp->slices_per_group
226                 - fc->fcp->data_slices_per_group;
227
228         if (!m)
229                 return -E_BAD_CT;
230         rv = (bytes + m - 1) / m;
231         if (rv + redundant_slices > 255)
232                 return -E_BAD_CT;
233         *result = rv;
234         return 1;
235 }
236
237 static int setup_next_fec_group(struct fec_client *fc, struct vss_task *vsst)
238 {
239         int ret, i, k, data_slices;
240         size_t len;
241         const char *buf, *start_buf;
242         struct timeval tmp, *chunk_tv = vss_chunk_time();
243         struct fec_group *g = &fc->group;
244         unsigned slice_bytes = fc->fcp->max_slice_bytes - FEC_HEADER_SIZE;
245         uint32_t max_data_size;
246
247         assert(chunk_tv);
248         k = fc->fcp->data_slices_per_group + fc->num_extra_slices;
249         if (fc->first_stream_chunk < 0) {
250                 uint32_t largest = afh_get_largest_chunk_size(&mmd->afd.afhi)
251                         + vsst->header_len;
252                 uint8_t needed, want;
253
254                 ret = num_slices(largest, fc, &needed);
255                 if (ret < 0)
256                         return ret;
257                 if (needed > fc->fcp->data_slices_per_group)
258                         PARA_WARNING_LOG("fec parms insufficient for this audio file\n");
259                 want = PARA_MAX(needed, fc->fcp->data_slices_per_group);
260                 if (want != k) {
261                         fec_free(fc->parms);
262                         fc->src_data = para_realloc(fc->src_data, want * sizeof(char *));
263                         ret = fec_new(want, want + fc->fcp->slices_per_group
264                                 - fc->fcp->data_slices_per_group, &fc->parms);
265                         if (ret < 0)
266                                 return ret;
267                         k = want;
268                         fc->num_extra_slices = 0;
269                         if (k > fc->fcp->data_slices_per_group) {
270                                 fc->num_extra_slices = k - fc->fcp->data_slices_per_group;
271                                 PARA_NOTICE_LOG("using %d extra slices\n",
272                                         fc->num_extra_slices);
273                         }
274                 }
275                 fc->stream_start = *now;
276                 fc->first_stream_chunk = mmd->current_chunk;
277                 g->first_chunk = mmd->current_chunk;
278                 g->num = 0;
279         } else {
280                 g->first_chunk += g->num_chunks;
281                 g->num++;
282         }
283         if (g->first_chunk >= mmd->afd.afhi.chunks_total)
284                 return 0;
285         if (need_audio_header(fc, vsst)) {
286                 ret = num_slices(vsst->header_len, fc, &g->num_header_slices);
287                 if (ret < 0)
288                         return ret;
289         } else
290                 g->num_header_slices = 0;
291         afh_get_chunk(g->first_chunk, &mmd->afd.afhi, vsst->map, &start_buf,
292                 &len);
293         data_slices = k - g->num_header_slices;
294         assert(data_slices);
295         max_data_size = slice_bytes * data_slices;
296         g->bytes = 0;
297         for (i = g->first_chunk; i < mmd->afd.afhi.chunks_total; i++) {
298                 afh_get_chunk(i, &mmd->afd.afhi, vsst->map, &buf, &len);
299                 if (g->bytes + len > max_data_size)
300                         break;
301                 g->bytes += len;
302         }
303         g->num_chunks = i - g->first_chunk;
304         assert(g->num_chunks);
305         fc->current_slice_num = 0;
306
307         /* setup header slices */
308         buf = vsst->header_buf;
309         for (i = 0; i < g->num_header_slices; i++) {
310                 fc->src_data[i] = (const unsigned char *)buf;
311                 buf += slice_bytes;
312         }
313
314         /* setup data slices */
315         buf = start_buf;
316         for (i = g->num_header_slices; i < k; i++) {
317                 if (buf + slice_bytes > vsst->map + mmd->size)
318                         /*
319                          * Can not use the memory mapped audio file for this
320                          * slice as it goes beyond the map. This slice will not
321                          * be fully used.
322                          */
323                         break;
324                 fc->src_data[i] = (const unsigned char *)buf;
325                 buf += slice_bytes;
326         }
327         if (i < k) {
328                 uint32_t payload_size = vsst->map + mmd->size - buf;
329                 memcpy(fc->extra_src_buf, buf, payload_size);
330                 fc->src_data[i] = fc->extra_src_buf;
331                 i++;
332                 /* use arbitrary data for all remaining slices */
333                 buf = vsst->map;
334                 for (; i < k; i++)
335                         fc->src_data[i] = (const unsigned char *)buf;
336         }
337
338         /* setup group timing */
339         tv_scale(g->first_chunk - fc->first_stream_chunk, chunk_tv, &tmp);
340         tv_add(&fc->stream_start, &tmp, &g->start);
341         tv_scale(g->num_chunks, chunk_tv, &tmp); /* group duration */
342         tv_divide(fc->fcp->slices_per_group + fc->num_extra_slices,
343                 &tmp, &g->slice_duration);
344
345         PARA_DEBUG_LOG("FEC group %d: %d chunks (%d - %d), %d header slices, %d data slices\n",
346                 g->num, g->num_chunks, g->first_chunk,
347                 g->first_chunk + g->num_chunks - 1,
348                 g->num_header_slices, data_slices
349         );
350         PARA_DEBUG_LOG("durations (group/chunk/slice): %lu/%lu/%lu\n",
351                 tv2ms(&tmp), tv2ms(chunk_tv), tv2ms(&g->slice_duration));
352         return 1;
353 }
354
355 static int compute_next_fec_slice(struct fec_client *fc, struct vss_task *vsst)
356 {
357         assert(fc->error >= 0);
358         if (fc->first_stream_chunk < 0 || fc->current_slice_num
359                         == fc->fcp->slices_per_group + fc->num_extra_slices) {
360                 int ret = setup_next_fec_group(fc, vsst);
361                 if (ret == 0)
362                         return 0;
363                 if (ret < 0) {
364                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
365                         PARA_ERROR_LOG("FEC client temporarily disabled\n");
366                         fc->error = ret;
367                         return fc->error;
368                 }
369         }
370         write_fec_header(fc, vsst);
371         fec_encode(fc->parms, fc->src_data, fc->enc_buf + FEC_HEADER_SIZE,
372                 fc->current_slice_num,
373                 fc->fcp->max_slice_bytes - FEC_HEADER_SIZE);
374         return 1;
375 }
376
377 /**
378  * Return a buffer that marks the end of the stream.
379  *
380  * \param buf Result pointer.
381  * \return The length of the eof buffer.
382  *
383  * This is used for (multicast) udp streaming where closing the socket on the
384  * sender might not give rise to an eof condition at the peer.
385  */
386 size_t vss_get_fec_eof_packet(const char **buf)
387 {
388         static const char fec_eof_packet[FEC_HEADER_SIZE] = FEC_EOF_PACKET;
389         *buf = fec_eof_packet;
390         return FEC_HEADER_SIZE;
391 }
392
393 /**
394  * Add one entry to the list of active fec clients.
395  *
396  * \param fcp Describes the fec parameters to be used for this client.
397  * \param result An opaque pointer that must be used by remove the client later.
398  *
399  * \return Standard.
400  */
401 int vss_add_fec_client(struct fec_client_parms *fcp, struct fec_client **result)
402 {
403         int ret;
404         struct fec_client *fc;
405
406         if (fcp->max_slice_bytes < FEC_HEADER_SIZE + fcp->data_slices_per_group)
407                 return -ERRNO_TO_PARA_ERROR(EINVAL);
408         fc = para_calloc(sizeof(*fc));
409         fc->fcp = fcp;
410         ret = fec_new(fcp->data_slices_per_group, fcp->slices_per_group,
411                 &fc->parms);
412         if (ret < 0)
413                 goto err;
414         fc->first_stream_chunk = -1; /* stream not yet started */
415         fc->src_data = para_malloc(fc->fcp->slices_per_group * sizeof(char *));
416         fc->enc_buf = para_calloc(fc->fcp->max_slice_bytes);
417         fc->num_extra_slices = 0;
418         fc->extra_src_buf = para_calloc(fc->fcp->max_slice_bytes);
419         fc->next_header_time.tv_sec = 0;
420         para_list_add(&fc->node, &fec_client_list);
421         *result = fc;
422         return 1;
423 err:
424         fec_free(fc->parms);
425         free(fc);
426         *result = NULL;
427         return ret;
428 }
429
430 /**
431  * Remove one entry from the list of active fec clients.
432  *
433  * \param fc The client to be removed.
434  */
435 void vss_del_fec_client(struct fec_client *fc)
436 {
437         list_del(&fc->node);
438         free(fc->src_data);
439         free(fc->enc_buf);
440         free(fc->extra_src_buf);
441         fec_free(fc->parms);
442         free(fc);
443 }
444
445 /*
446  * Compute if/when next slice is due. If it isn't due yet and \a diff is
447  * not \p Null, compute the time difference next - now, where
448  *
449  *      next = stream_start + (first_group_chunk - first_stream_chunk)
450  *              * chunk_time + slice_num * slice_time
451  */
452 static int next_slice_is_due(struct fec_client *fc, struct timeval *diff)
453 {
454         struct timeval tmp, next;
455         int ret;
456
457         if (fc->first_stream_chunk < 0)
458                 return 1;
459         tv_scale(fc->current_slice_num, &fc->group.slice_duration, &tmp);
460         tv_add(&tmp, &fc->group.start, &next);
461         ret = tv_diff(&next, now, diff);
462         return ret < 0? 1 : 0;
463 }
464
465 static void compute_slice_timeout(struct timeval *timeout)
466 {
467         struct fec_client *fc;
468
469         assert(vss_playing());
470         list_for_each_entry(fc, &fec_client_list, node) {
471                 struct timeval diff;
472
473                 if (fc->error < 0)
474                         continue;
475                 if (next_slice_is_due(fc, &diff)) {
476                         timeout->tv_sec = 0;
477                         timeout->tv_usec = 0;
478                         return;
479                 }
480                 /* timeout = min(timeout, diff) */
481                 if (tv_diff(&diff, timeout, NULL) < 0)
482                         *timeout = diff;
483         }
484 }
485
486 static void set_eof_barrier(struct vss_task *vsst)
487 {
488         struct fec_client *fc;
489         struct timeval timeout = {1, 0}, *chunk_tv = vss_chunk_time();
490
491         if (!chunk_tv)
492                 goto out;
493         list_for_each_entry(fc, &fec_client_list, node) {
494                 struct timeval group_duration;
495
496                 if (fc->error < 0)
497                         continue;
498                 tv_scale(fc->group.num_chunks, chunk_tv, &group_duration);
499                 if (tv_diff(&timeout, &group_duration, NULL) < 0)
500                         timeout = group_duration;
501         }
502 out:
503         tv_add(now, &timeout, &vsst->eof_barrier);
504 }
505
506 /**
507  * Check if vss status flag \a P (playing) is set.
508  *
509  * \return Greater than zero if playing, zero otherwise.
510  *
511  */
512 unsigned int vss_playing(void)
513 {
514         return mmd->new_vss_status_flags & VSS_PLAYING;
515 }
516
517 /**
518  * Check if the \a N (next) status flag is set.
519  *
520  * \return Greater than zero if set, zero if not.
521  *
522  */
523 unsigned int vss_next(void)
524 {
525         return mmd->new_vss_status_flags & VSS_NEXT;
526 }
527
528 /**
529  * Check if a reposition request is pending.
530  *
531  * \return Greater than zero if true, zero otherwise.
532  *
533  */
534 unsigned int vss_repos(void)
535 {
536         return mmd->new_vss_status_flags & VSS_REPOS;
537 }
538
539 /**
540  * Check if the vss is currently paused.
541  *
542  * \return Greater than zero if paused, zero otherwise.
543  *
544  */
545 unsigned int vss_paused(void)
546 {
547         return !(mmd->new_vss_status_flags & VSS_NEXT)
548                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
549 }
550
551 /**
552  * Check if the vss is currently stopped.
553  *
554  * \return Greater than zero if paused, zero otherwise.
555  *
556  */
557 unsigned int vss_stopped(void)
558 {
559         return (mmd->new_vss_status_flags & VSS_NEXT)
560                 && !(mmd->new_vss_status_flags & VSS_PLAYING);
561 }
562
563 static int chk_barrier(const char *bname, const struct timeval *barrier,
564                 struct timeval *diff, int print_log)
565 {
566         long ms;
567
568         if (tv_diff(now, barrier, diff) > 0)
569                 return 1;
570         ms = tv2ms(diff);
571         if (print_log && ms)
572                 PARA_DEBUG_LOG("%s barrier: %lims left\n", bname, ms);
573         return -1;
574 }
575
576 /*
577  * != NULL: timeout for next chunk
578  * NULL: nothing to do
579  */
580 static struct timeval *vss_compute_timeout(struct vss_task *vsst)
581 {
582         static struct timeval the_timeout;
583         struct timeval next_chunk;
584
585         if (vss_next() && vsst->map) {
586                 /* only sleep a bit, nec*/
587                 the_timeout.tv_sec = 0;
588                 the_timeout.tv_usec = 100;
589                 return &the_timeout;
590         }
591         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
592                         &the_timeout, 1) < 0)
593                 return &the_timeout;
594         if (chk_barrier("eof", &vsst->eof_barrier, &the_timeout, 1) < 0)
595                 return &the_timeout;
596         if (chk_barrier("data send", &vsst->data_send_barrier,
597                         &the_timeout, 1) < 0)
598                 return &the_timeout;
599         if (!vss_playing() || !vsst->map)
600                 return NULL;
601         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
602                 &mmd->stream_start, &next_chunk);
603         if (chk_barrier("chunk", &next_chunk, &the_timeout, 0) >= 0) {
604                 /* chunk is due or bof */
605                 the_timeout.tv_sec = 0;
606                 the_timeout.tv_usec = 0;
607                 return &the_timeout;
608         }
609         /* compute min of current timeout and next slice time */
610         compute_slice_timeout(&the_timeout);
611         return &the_timeout;
612 }
613
614 static void vss_eof(struct vss_task *vsst)
615 {
616
617         if (!vsst->map)
618                 return;
619         if (mmd->new_vss_status_flags & VSS_NOMORE)
620                 mmd->new_vss_status_flags = VSS_NEXT;
621         set_eof_barrier(vsst);
622         para_munmap(vsst->map, mmd->size);
623         vsst->map = NULL;
624         mmd->chunks_sent = 0;
625         mmd->offset = 0;
626         mmd->afd.afhi.seconds_total = 0;
627         mmd->afd.afhi.chunk_tv.tv_sec = 0;
628         mmd->afd.afhi.chunk_tv.tv_usec = 0;
629         free(mmd->afd.afhi.chunk_table);
630         mmd->afd.afhi.chunk_table = NULL;
631         mmd->mtime = 0;
632         mmd->size = 0;
633         mmd->events++;
634 }
635
636 /**
637  * Get the list of all supported audio formats.
638  *
639  * \return Aa space separated list of all supported audio formats
640  * It is not allocated at runtime, i.e. there is no need to free
641  * the returned string in the caller.
642  */
643 const char *supported_audio_formats(void)
644 {
645         return SUPPORTED_AUDIO_FORMATS;
646 }
647
648 static int need_to_request_new_audio_file(struct vss_task *vsst)
649 {
650         struct timeval diff;
651
652         if (vsst->map) /* have audio file */
653                 return 0;
654         if (!vss_playing()) /* don't need one */
655                 return 0;
656         if (mmd->new_vss_status_flags & VSS_NOMORE)
657                 return 0;
658         if (vsst->afsss == AFS_SOCKET_AFD_PENDING) /* already requested one */
659                 return 0;
660         if (chk_barrier("autoplay_delay", &vsst->autoplay_barrier,
661                         &diff, 1) < 0)
662                 return 0;
663         return 1;
664 }
665
666 /**
667  * Compute the timeout for the main select-loop of the scheduler.
668  *
669  * \param s Pointer to the server scheduler.
670  * \param t Pointer to the vss task structure.
671  *
672  * Before the timeout is computed, the current vss status flags are evaluated
673  * and acted upon by calling appropriate functions from the lower layers.
674  * Possible actions include
675  *
676  *      - request a new audio file from afs,
677  *      - shutdown of all senders (stop/pause command),
678  *      - reposition the stream (ff/jmp command).
679  */
680 static void vss_pre_select(struct sched *s, struct task *t)
681 {
682         int i;
683         struct timeval *tv, diff;
684         struct vss_task *vsst = container_of(t, struct vss_task, task);
685
686         if (!vsst->map || vss_next() || vss_paused() || vss_repos()) {
687                 struct fec_client *fc, *tmp;
688                 for (i = 0; senders[i].name; i++)
689                         if (senders[i].shutdown_clients)
690                                 senders[i].shutdown_clients();
691                 list_for_each_entry_safe(fc, tmp, &fec_client_list, node) {
692                         fc->first_stream_chunk = -1;
693                         fc->error = 0;
694                 }
695                 mmd->stream_start.tv_sec = 0;
696                 mmd->stream_start.tv_usec = 0;
697         }
698         if (vss_next())
699                 vss_eof(vsst);
700         else if (vss_paused()) {
701                 if (mmd->chunks_sent)
702                         set_eof_barrier(vsst);
703                 mmd->chunks_sent = 0;
704         } else if (vss_repos()) {
705                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
706                 set_eof_barrier(vsst);
707                 mmd->chunks_sent = 0;
708                 mmd->current_chunk = mmd->repos_request;
709                 mmd->new_vss_status_flags &= ~VSS_REPOS;
710         }
711         if (need_to_request_new_audio_file(vsst)) {
712                 PARA_DEBUG_LOG("ready and playing, but no audio file\n");
713                 para_fd_set(vsst->afs_socket, &s->wfds, &s->max_fileno);
714                 vsst->afsss = AFS_SOCKET_CHECK_FOR_WRITE;
715         } else
716                 para_fd_set(vsst->afs_socket, &s->rfds, &s->max_fileno);
717         for (i = 0; senders[i].name; i++) {
718                 if (!senders[i].pre_select)
719                         continue;
720                 senders[i].pre_select(&s->max_fileno, &s->rfds, &s->wfds);
721         }
722         tv = vss_compute_timeout(vsst);
723         if (tv && tv_diff(tv, &s->timeout, &diff) < 0)
724                 s->timeout = *tv;
725 }
726
727 static int recv_afs_msg(int afs_socket, int *fd, uint32_t *code, uint32_t *data)
728 {
729         char control[255], buf[8];
730         struct msghdr msg = {.msg_iov = NULL};
731         struct cmsghdr *cmsg;
732         struct iovec iov;
733         int ret = 0;
734
735         *fd = -1;
736         iov.iov_base = buf;
737         iov.iov_len = sizeof(buf);
738         msg.msg_iov = &iov;
739         msg.msg_iovlen = 1;
740         msg.msg_control = control;
741         msg.msg_controllen = sizeof(control);
742         memset(buf, 0, sizeof(buf));
743         ret = recvmsg(afs_socket, &msg, 0);
744         if (ret < 0)
745                 return -ERRNO_TO_PARA_ERROR(errno);
746         if (iov.iov_len != sizeof(buf))
747                 return -E_AFS_SHORT_READ;
748         *code = *(uint32_t*)buf;
749         *data =  *(uint32_t*)(buf + 4);
750         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
751                 if (cmsg->cmsg_level != SOL_SOCKET
752                         || cmsg->cmsg_type != SCM_RIGHTS)
753                         continue;
754                 if ((cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int) != 1)
755                         continue;
756                 *fd = *(int *)CMSG_DATA(cmsg);
757         }
758         return 1;
759 }
760
761 static void recv_afs_result(struct vss_task *vsst)
762 {
763         int ret, passed_fd, shmid;
764         uint32_t afs_code = 0, afs_data = 0;
765         struct stat statbuf;
766
767         vsst->afsss = AFS_SOCKET_READY;
768         ret = recv_afs_msg(vsst->afs_socket, &passed_fd, &afs_code, &afs_data);
769         if (ret < 0)
770                 goto err;
771         PARA_DEBUG_LOG("fd: %d, code: %u, shmid: %u\n", passed_fd, afs_code,
772                 afs_data);
773         ret = -E_NOFD;
774         if (afs_code != NEXT_AUDIO_FILE)
775                 goto err;
776         if (passed_fd < 0)
777                 goto err;
778         shmid = afs_data;
779         ret = load_afd(shmid, &mmd->afd);
780         if (ret < 0)
781                 goto err;
782         shm_destroy(shmid);
783         ret = fstat(passed_fd, &statbuf);
784         if (ret < 0) {
785                 PARA_ERROR_LOG("fstat error:\n");
786                 ret = -ERRNO_TO_PARA_ERROR(errno);
787                 goto err;
788         }
789         mmd->size = statbuf.st_size;
790         mmd->mtime = statbuf.st_mtime;
791         ret = para_mmap(mmd->size, PROT_READ, MAP_PRIVATE, passed_fd,
792                 0, &vsst->map);
793         if (ret < 0)
794                 goto err;
795         close(passed_fd);
796         mmd->chunks_sent = 0;
797         mmd->current_chunk = 0;
798         mmd->offset = 0;
799         mmd->events++;
800         mmd->num_played++;
801         mmd->new_vss_status_flags &= (~VSS_NEXT);
802         afh_get_header(&mmd->afd.afhi, vsst->map, &vsst->header_buf,
803                 &vsst->header_len);
804         return;
805 err:
806         free(mmd->afd.afhi.chunk_table);
807         if (passed_fd >= 0)
808                 close(passed_fd);
809         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
810         mmd->new_vss_status_flags = VSS_NEXT;
811 }
812
813 /**
814  * Main sending function.
815  *
816  * This function gets called from vss_post_select(). It checks whether the next
817  * chunk of data should be pushed out. It obtains a pointer to the data to be
818  * sent out as well as its length from mmd->afd.afhi. This information is then
819  * passed to each supported sender's send() function as well as to the send()
820  * functions of each registered fec client.
821  */
822 static void vss_send(struct vss_task *vsst)
823 {
824         int i, sent_something = 0;
825         struct timeval due;
826         struct fec_client *fc, *tmp_fc;
827
828         if (!vsst->map || !vss_playing())
829                 return;
830         if (chk_barrier("eof", &vsst->eof_barrier, &due, 1) < 0)
831                 return;
832         if (chk_barrier("data send", &vsst->data_send_barrier,
833                         &due, 1) < 0)
834                 return;
835         list_for_each_entry_safe(fc, tmp_fc, &fec_client_list, node) {
836                 if (fc->error < 0)
837                         continue;
838                 if (!next_slice_is_due(fc, NULL))
839                         continue;
840                 if (compute_next_fec_slice(fc, vsst) <= 0)
841                         continue;
842                 PARA_DEBUG_LOG("sending %d:%d (%u bytes)\n", fc->group.num,
843                         fc->current_slice_num, fc->fcp->max_slice_bytes);
844                 fc->fcp->send((char *)fc->enc_buf,
845                         fc->fcp->max_slice_bytes,
846                         fc->fcp->private_data);
847                 fc->current_slice_num++;
848                 sent_something = 1;
849         }
850         if (mmd->current_chunk >= mmd->afd.afhi.chunks_total) { /* eof */
851                 if (!sent_something)
852                         mmd->new_vss_status_flags |= VSS_NEXT;
853                 return;
854         }
855         compute_chunk_time(mmd->chunks_sent, &mmd->afd.afhi.chunk_tv,
856                 &mmd->stream_start, &due);
857         if (tv_diff(&due, now, NULL) <= 0) {
858                 const char *buf;
859                 size_t len;
860
861                 if (!mmd->chunks_sent) {
862                         struct timeval tmp;
863                         mmd->stream_start = *now;
864                         tv_scale(mmd->current_chunk, &mmd->afd.afhi.chunk_tv, &tmp);
865                         mmd->offset = tv2ms(&tmp);
866                         mmd->events++;
867                 }
868                 /*
869                  * We call the send function also in case of empty chunks as
870                  * they might have still some data queued which can be sent in
871                  * this case.
872                  */
873                 afh_get_chunk(mmd->current_chunk, &mmd->afd.afhi, vsst->map,
874                         &buf, &len);
875                 for (i = 0; senders[i].name; i++) {
876                         if (!senders[i].send)
877                                 continue;
878                         senders[i].send(mmd->current_chunk, mmd->chunks_sent,
879                                 buf, len, vsst->header_buf, vsst->header_len);
880                 }
881                 mmd->chunks_sent++;
882                 mmd->current_chunk++;
883         }
884 }
885
886 static void vss_post_select(struct sched *s, struct task *t)
887 {
888         int ret, i;
889         struct vss_task *vsst = container_of(t, struct vss_task, task);
890
891
892         if (mmd->sender_cmd_data.cmd_num >= 0) {
893                 int num = mmd->sender_cmd_data.cmd_num,
894                         sender_num = mmd->sender_cmd_data.sender_num;
895
896                 if (senders[sender_num].client_cmds[num])
897                         senders[sender_num].client_cmds[num](&mmd->sender_cmd_data);
898                 mmd->sender_cmd_data.cmd_num = -1;
899         }
900         if (vsst->afsss != AFS_SOCKET_CHECK_FOR_WRITE) {
901                 if (FD_ISSET(vsst->afs_socket, &s->rfds))
902                         recv_afs_result(vsst);
903         } else if (FD_ISSET(vsst->afs_socket, &s->wfds)) {
904                 PARA_NOTICE_LOG("requesting new fd from afs\n");
905                 ret = send_buffer(vsst->afs_socket, "new");
906                 if (ret < 0)
907                         PARA_CRIT_LOG("%s\n", para_strerror(-ret));
908                 else
909                         vsst->afsss = AFS_SOCKET_AFD_PENDING;
910         }
911         for (i = 0; senders[i].name; i++) {
912                 if (!senders[i].post_select)
913                         continue;
914                 senders[i].post_select(&s->rfds, &s->wfds);
915         }
916         if ((vss_playing() && !(mmd->vss_status_flags & VSS_PLAYING)) ||
917                         (vss_next() && vss_playing()))
918                 tv_add(now, &vsst->announce_tv, &vsst->data_send_barrier);
919         vss_send(vsst);
920 }
921
922 /**
923  * Initialize the virtual streaming system task.
924  *
925  * \param afs_socket The fd for communication with afs.
926  *
927  * This also initializes all supported senders and starts streaming
928  * if the --autoplay command line flag was given.
929  */
930 void init_vss_task(int afs_socket)
931 {
932         static struct vss_task vss_task_struct, *vsst = &vss_task_struct;
933         int i;
934         char *hn = para_hostname(), *home = para_homedir();
935         long unsigned announce_time = conf.announce_time_arg > 0?
936                         conf.announce_time_arg : 300,
937                 autoplay_delay = conf.autoplay_delay_arg > 0?
938                         conf.autoplay_delay_arg : 0;
939         vsst->header_interval.tv_sec = 5; /* should this be configurable? */
940         vsst->afs_socket = afs_socket;
941         vsst->task.pre_select = vss_pre_select;
942         vsst->task.post_select = vss_post_select;
943         ms2tv(announce_time, &vsst->announce_tv);
944         PARA_INFO_LOG("announce timeval: %lums\n", tv2ms(&vsst->announce_tv));
945         INIT_LIST_HEAD(&fec_client_list);
946         for (i = 0; senders[i].name; i++) {
947                 PARA_NOTICE_LOG("initializing %s sender\n", senders[i].name);
948                 senders[i].init(&senders[i]);
949         }
950         free(hn);
951         free(home);
952         mmd->sender_cmd_data.cmd_num = -1;
953         if (conf.autoplay_given) {
954                 struct timeval tmp;
955                 mmd->vss_status_flags |= VSS_PLAYING;
956                 mmd->new_vss_status_flags |= VSS_PLAYING;
957                 ms2tv(autoplay_delay, &tmp);
958                 tv_add(now, &tmp, &vsst->autoplay_barrier);
959                 tv_add(&vsst->autoplay_barrier, &vsst->announce_tv,
960                         &vsst->data_send_barrier);
961         }
962         register_task(&vsst->task);
963 }