chiark / gitweb /
Build fixes
[disorder] / server / actions.c
CommitLineData
bca4e2b7
RK
1/*
2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2008 Richard Kettlewell
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 * USA
19 */
1e97629d
RK
20/** @file server/actions.c
21 * @brief DisOrder web actions
22 *
23 * Actions are anything that the web interface does beyond passive template
24 * expansion and inspection of state recieved from the server. This means
25 * playing tracks, editing prefs etc but also setting extra headers e.g. to
26 * auto-refresh the playing list.
27 */
bca4e2b7 28
1e97629d 29#include "disorder-cgi.h"
5a7df048
RK
30
31/** @brief Redirect to some other action or URL */
32static void redirect(const char *url) {
33 /* By default use the 'back' argument */
34 if(!url)
71634563 35 url = cgi_get("back");
5a7df048 36 if(url) {
e7ce7665 37 if(strncmp(url, "http", 4))
5a7df048
RK
38 /* If the target is not a full URL assume it's the action */
39 url = cgi_makeurl(config->url, "action", url, (char *)0);
40 } else {
41 /* If back= is not set just go back to the front page */
42 url = config->url;
43 }
44 if(printf("Location: %s\n"
45 "%s\n"
1e97629d 46 "\n", url, dcgi_cookie_header()) < 0)
5a7df048
RK
47 fatal(errno, "error writing to stdout");
48}
49
448d3570
RK
50/* 'playing' and 'manage' just add a Refresh: header */
51static void act_playing(void) {
52 long refresh = config->refresh;
53 long length;
54 time_t now, fin;
55 char *url;
71634563 56 const char *action;
448d3570 57
1e97629d
RK
58 dcgi_lookup(DCGI_PLAYING|DCGI_QUEUE|DCGI_ENABLED|DCGI_RANDOM_ENABLED);
59 if(dcgi_playing
60 && dcgi_playing->state == playing_started /* i.e. not paused */
61 && !disorder_length(dcgi_client, dcgi_playing->track, &length)
448d3570 62 && length
1e97629d 63 && dcgi_playing->sofar >= 0) {
448d3570
RK
64 /* Try to put the next refresh at the start of the next track. */
65 time(&now);
1e97629d 66 fin = now + length - dcgi_playing->sofar + config->gap;
448d3570
RK
67 if(now + refresh > fin)
68 refresh = fin - now;
69 }
1e97629d 70 if(dcgi_queue && dcgi_queue->state == playing_isscratch) {
448d3570
RK
71 /* next track is a scratch, don't leave more than the inter-track gap */
72 if(refresh > config->gap)
73 refresh = config->gap;
74 }
1e97629d
RK
75 if(!dcgi_playing
76 && ((dcgi_queue
77 && dcgi_queue->state != playing_random)
78 || dcgi_random_enabled)
79 && dcgi_enabled) {
448d3570
RK
80 /* no track playing but playing is enabled and there is something coming
81 * up, must be in a gap */
82 if(refresh > config->gap)
83 refresh = config->gap;
84 }
85 if((action = cgi_get("action")))
86 url = cgi_makeurl(config->url, "action", action, (char *)0);
87 else
88 url = config->url;
e7ce7665
RK
89 if(printf("Refresh: %ld;url=%s\n",
90 refresh, url) < 0)
448d3570 91 fatal(errno, "error writing to stdout");
e7ce7665 92 dcgi_expand("playing", 1);
1e97629d
RK
93}
94
95static void act_disable(void) {
96 if(dcgi_client)
97 disorder_disable(dcgi_client);
98 redirect(0);
99}
100
101static void act_enable(void) {
102 if(dcgi_client)
103 disorder_enable(dcgi_client);
104 redirect(0);
105}
106
107static void act_random_disable(void) {
108 if(dcgi_client)
109 disorder_random_disable(dcgi_client);
110 redirect(0);
111}
112
113static void act_random_enable(void) {
114 if(dcgi_client)
115 disorder_random_enable(dcgi_client);
116 redirect(0);
448d3570
RK
117}
118
6d9dd8d9
RK
119static void act_pause(void) {
120 if(dcgi_client)
121 disorder_pause(dcgi_client);
122 redirect(0);
123}
124
125static void act_resume(void) {
126 if(dcgi_client)
127 disorder_resume(dcgi_client);
128 redirect(0);
129}
130
a2c4ad5f
RK
131static void act_remove(void) {
132 const char *id;
133 struct queue_entry *q;
134
135 if(dcgi_client) {
136 if(!(id = cgi_get("id")))
137 error(0, "missing 'id' argument");
138 else if(!(q = dcgi_findtrack(id)))
139 error(0, "unknown queue id %s", id);
140 else switch(q->state) {
141 case playing_isscratch:
142 case playing_failed:
143 case playing_no_player:
144 case playing_ok:
145 case playing_quitting:
146 case playing_scratched:
147 error(0, "does not make sense to scratch %s", id);
148 break;
149 case playing_paused: /* started but paused */
150 case playing_started: /* started to play */
151 disorder_scratch(dcgi_client, id);
152 break;
153 case playing_random: /* unplayed randomly chosen track */
154 case playing_unplayed: /* haven't played this track yet */
155 disorder_remove(dcgi_client, id);
156 break;
157 }
158 }
159 redirect(0);
160}
161
6d9dd8d9
RK
162static void act_move(void) {
163 const char *id, *delta;
164 struct queue_entry *q;
165
166 if(dcgi_client) {
167 if(!(id = cgi_get("id")))
168 error(0, "missing 'id' argument");
169 else if(!(delta = cgi_get("delta")))
170 error(0, "missing 'delta' argument");
171 else if(!(q = dcgi_findtrack(id)))
172 error(0, "unknown queue id %s", id);
173 else switch(q->state) {
174 case playing_random: /* unplayed randomly chosen track */
175 case playing_unplayed: /* haven't played this track yet */
176 disorder_move(dcgi_client, id, atol(delta));
177 break;
178 default:
179 error(0, "does not make sense to scratch %s", id);
180 break;
181 }
182 }
183 redirect(0);
184}
185
186static void act_play(void) {
187 const char *track, *dir;
188 char **tracks;
189 int ntracks, n;
190 struct dcgi_entry *e;
191
192 if(dcgi_client) {
02eaa49d 193 if((track = cgi_get("track"))) {
6d9dd8d9
RK
194 disorder_play(dcgi_client, track);
195 } else if((dir = cgi_get("dir"))) {
196 if(disorder_files(dcgi_client, dir, 0, &tracks, &ntracks))
197 ntracks = 0;
198 e = xmalloc(ntracks * sizeof (struct dcgi_entry));
199 for(n = 0; n < ntracks; ++n) {
200 e[n].track = tracks[n];
201 e[n].sort = trackname_transform("track", tracks[n], "sort");
202 e[n].display = trackname_transform("track", tracks[n], "display");
203 }
204 qsort(e, ntracks, sizeof (struct dcgi_entry), dcgi_compare_entry);
205 for(n = 0; n < ntracks; ++n)
206 disorder_play(dcgi_client, e[n].track);
207 }
208 }
209 redirect(0);
210}
211
212static int clamp(int n, int min, int max) {
213 if(n < min)
214 return min;
215 if(n > max)
216 return max;
217 return n;
218}
219
220static void act_volume(void) {
221 const char *l, *r, *d;
222 int nd;
223
224 if(dcgi_client) {
225 if((d = cgi_get("delta"))) {
226 dcgi_lookup(DCGI_VOLUME);
227 nd = clamp(atoi(d), -255, 255);
228 disorder_set_volume(dcgi_client,
229 clamp(dcgi_volume_left + nd, 0, 255),
230 clamp(dcgi_volume_right + nd, 0, 255));
231 } else if((l = cgi_get("left")) && (r = cgi_get("right")))
232 disorder_set_volume(dcgi_client, atoi(l), atoi(r));
233 }
234 redirect(0);
235}
236
e7ce7665 237/** @brief Expand the login template with @b @@error set to @p error
b7e452c7 238 * @param e Error keyword
e7ce7665 239 */
b7e452c7
RK
240static void login_error(const char *e) {
241 dcgi_error_string = e;
e7ce7665
RK
242 dcgi_expand("login", 1);
243}
244
245/** @brief Log in
246 * @param username Login name
247 * @param password Password
248 * @return 0 on success, non-0 on error
249 *
250 * On error, calls login_error() to expand the login template.
251 */
252static int login_as(const char *username, const char *password) {
253 disorder_client *c;
254
255 if(dcgi_cookie && dcgi_client)
256 disorder_revoke(dcgi_client);
257 /* We'll need a new connection as we are going to stop being guest */
258 c = disorder_new(0);
259 if(disorder_connect_user(c, username, password)) {
260 login_error("loginfailed");
261 return -1;
262 }
263 /* Generate a cookie so we can log in again later */
264 if(disorder_make_cookie(c, &dcgi_cookie)) {
265 login_error("cookiefailed");
266 return -1;
267 }
268 /* Use the new connection henceforth */
269 dcgi_client = c;
270 dcgi_lookup_reset();
271 return 0; /* OK */
272}
273
274static void act_login(void) {
275 const char *username, *password;
276
277 /* We try all this even if not connected since the subsequent connection may
278 * succeed. */
279
280 username = cgi_get("username");
281 password = cgi_get("password");
282 if(!username
283 || !password
284 || !strcmp(username, "guest")/*bodge to avoid guest cookies*/) {
285 /* We're just visiting the login page, not performing an action at all. */
286 dcgi_expand("login", 1);
287 return;
288 }
289 if(!login_as(username, password)) {
290 /* Report the succesful login */
291 dcgi_status_string = "loginok";
2cc4c0ef
RK
292 /* Redirect back to where we came from, if necessary */
293 if(cgi_get("back"))
294 redirect(0);
295 else
296 dcgi_expand("login", 1);
e7ce7665
RK
297 }
298}
299
300static void act_logout(void) {
301 if(dcgi_client) {
302 /* Ask the server to revoke the cookie */
303 if(!disorder_revoke(dcgi_client))
304 dcgi_status_string = "logoutok";
305 else
306 dcgi_error_string = "revokefailed";
307 } else {
308 /* We can't guarantee a logout if we can't connect to the server to revoke
309 * the cookie, so we report an error. We'll still ask the browser to
310 * forget the cookie though. */
311 dcgi_error_string = "connect";
312 }
313 /* Attempt to reconnect without the cookie */
314 dcgi_cookie = 0;
315 dcgi_login();
316 /* Back to login page, hopefuly forcing the browser to forget the cookie. */
317 dcgi_expand("login", 1);
318}
319
320static void act_register(void) {
321 const char *username, *password, *password2, *email;
322 char *confirm, *content_type;
323 const char *text, *encoding, *charset;
324
325 /* If we're not connected then this is a hopeless exercise */
326 if(!dcgi_client) {
327 login_error("connect");
328 return;
329 }
330
331 /* Collect arguments */
332 username = cgi_get("username");
333 password = cgi_get("password1");
334 password2 = cgi_get("password2");
335 email = cgi_get("email");
336
337 /* Verify arguments */
338 if(!username || !*username) {
339 login_error("nousername");
340 return;
341 }
342 if(!password || !*password) {
343 login_error("nopassword");
344 return;
345 }
346 if(!password2 || !*password2 || strcmp(password, password2)) {
347 login_error("passwordmismatch");
348 return;
349 }
350 if(!email || !*email) {
351 login_error("noemail");
352 return;
353 }
354 /* We could well do better address validation but for now we'll just do the
355 * minimum */
356 if(!strchr(email, '@')) {
357 login_error("bademail");
358 return;
359 }
360 if(disorder_register(dcgi_client, username, password, email, &confirm)) {
361 login_error("cannotregister");
362 return;
363 }
364 /* Send the user a mail */
365 /* TODO templatize this */
366 byte_xasprintf((char **)&text,
367 "Welcome to DisOrder. To active your login, please visit this URL:\n"
368 "\n"
369 "%s?c=%s\n", config->url, urlencodestring(confirm));
370 if(!(text = mime_encode_text(text, &charset, &encoding)))
371 fatal(0, "cannot encode email");
372 byte_xasprintf(&content_type, "text/plain;charset=%s",
373 quote822(charset, 0));
374 sendmail("", config->mail_sender, email, "Welcome to DisOrder",
375 encoding, content_type, text); /* TODO error checking */
376 /* We'll go back to the login page with a suitable message */
377 dcgi_status_string = "registered";
378 dcgi_expand("login", 1);
379}
380
381static void act_confirm(void) {
382 const char *confirmation;
383
384 /* If we're not connected then this is a hopeless exercise */
385 if(!dcgi_client) {
386 login_error("connect");
387 return;
388 }
389
390 if(!(confirmation = cgi_get("c"))) {
391 login_error("noconfirm");
392 return;
393 }
394 /* Confirm our registration */
395 if(disorder_confirm(dcgi_client, confirmation)) {
396 login_error("badconfirm");
397 return;
398 }
399 /* Get a cookie */
400 if(disorder_make_cookie(dcgi_client, &dcgi_cookie)) {
401 login_error("cookiefailed");
402 return;
403 }
404 /* Junk cached data */
405 dcgi_lookup_reset();
406 /* Report success */
407 dcgi_status_string = "confirmed";
408 dcgi_expand("login", 1);
409}
410
411static void act_edituser(void) {
412 const char *email = cgi_get("email"), *password = cgi_get("changepassword1");
413 const char *password2 = cgi_get("changepassword2");
414 int newpassword = 0;
415
416 /* If we're not connected then this is a hopeless exercise */
417 if(!dcgi_client) {
418 login_error("connect");
419 return;
420 }
421
422 /* Verify input */
423
424 /* If either password or password2 is set we insist they match. If they
425 * don't we report an error. */
426 if((password && *password) || (password2 && *password2)) {
427 if(!password || !password2 || strcmp(password, password2)) {
428 login_error("passwordmismatch");
429 return;
430 }
431 } else
432 password = password2 = 0;
433 if(email && !strchr(email, '@')) {
434 login_error("bademail");
435 return;
436 }
437
438 /* Commit changes */
439 if(email) {
440 if(disorder_edituser(dcgi_client, disorder_user(dcgi_client),
441 "email", email)) {
442 login_error("badedit");
443 return;
444 }
445 }
446 if(password) {
447 if(disorder_edituser(dcgi_client, disorder_user(dcgi_client),
448 "password", password)) {
449 login_error("badedit");
450 return;
451 }
452 newpassword = 1;
453 }
454
455 if(newpassword) {
456 /* If we changed the password, the cookie is now invalid, so we must log
457 * back in. */
458 if(login_as(disorder_user(dcgi_client), password))
459 return;
460 }
461 /* Report success */
462 dcgi_status_string = "edited";
463 dcgi_expand("login", 1);
464}
465
466static void act_reminder(void) {
467 const char *const username = cgi_get("username");
468
469 /* If we're not connected then this is a hopeless exercise */
470 if(!dcgi_client) {
471 login_error("connect");
472 return;
473 }
474
475 if(!username || !*username) {
476 login_error("nousername");
477 return;
478 }
479 if(disorder_reminder(dcgi_client, username)) {
480 login_error("reminderfailed");
481 return;
482 }
483 /* Report success */
484 dcgi_status_string = "reminded";
485 dcgi_expand("login", 1);
486}
487
02eaa49d
RK
488/** @brief Get the numbered version of an argument
489 * @param argname Base argument name
490 * @param numfile File number
491 * @return cgi_get(NUMFILE_ARGNAME)
492 */
493static const char *numbered_arg(const char *argname, int numfile) {
494 char *fullname;
495
496 byte_xasprintf(&fullname, "%d_%s", numfile, argname);
497 return cgi_get(fullname);
498}
499
500/** @brief Set preferences for file @p numfile
501 * @return 0 on success, -1 if there is no such track number
502 *
503 * The old @b nfiles parameter has been abolished, we just keep look for more
504 * files until we run out.
505 */
506static int process_prefs(int numfile) {
507 const char *file, *name, *value, *part, *parts, *context;
508 char **partslist;
509
510 if(!(file = numbered_arg("track", numfile)))
511 return -1;
512 if(!(parts = cgi_get("parts")))
513 parts = "artist album title";
514 if(!(context = cgi_get("context")))
515 context = "display";
516 partslist = split(parts, 0, 0, 0, 0);
517 while((part = *partslist++)) {
518 if(!(value = numbered_arg(part, numfile)))
519 continue;
520 byte_xasprintf((char **)&name, "trackname_%s_%s", context, part);
521 disorder_set(dcgi_client, file, name, value);
522 }
523 if((value = numbered_arg("random", numfile)))
524 disorder_unset(dcgi_client, file, "pick_at_random");
525 else
526 disorder_set(dcgi_client, file, "pick_at_random", "0");
527 if((value = numbered_arg("tags", numfile))) {
528 if(!*value)
529 disorder_unset(dcgi_client, file, "tags");
530 else
531 disorder_set(dcgi_client, file, "tags", value);
532 }
533 if((value = numbered_arg("weight", numfile))) {
534 if(!*value)
535 disorder_unset(dcgi_client, file, "weight");
536 else
537 disorder_set(dcgi_client, file, "weight", value);
538 }
539 return 0;
540}
541
542static void act_set(void) {
543 int numfile;
544
545 if(dcgi_client) {
546 for(numfile = 0; !process_prefs(numfile); ++numfile)
547 ;
548 }
549 redirect(0);
550}
551
bca4e2b7
RK
552/** @brief Table of actions */
553static const struct action {
554 /** @brief Action name */
555 const char *name;
556 /** @brief Action handler */
557 void (*handler)(void);
02eaa49d
RK
558 /** @brief Union of suitable rights */
559 rights_type rights;
bca4e2b7 560} actions[] = {
02eaa49d
RK
561 { "confirm", act_confirm, 0 },
562 { "disable", act_disable, RIGHT_GLOBAL_PREFS },
563 { "edituser", act_edituser, 0 },
564 { "enable", act_enable, RIGHT_GLOBAL_PREFS },
565 { "login", act_login, 0 },
566 { "logout", act_logout, 0 },
567 { "manage", act_playing, 0 },
568 { "move", act_move, RIGHT_MOVE__MASK },
569 { "pause", act_pause, RIGHT_PAUSE },
570 { "play", act_play, RIGHT_PLAY },
571 { "playing", act_playing, 0 },
572 { "randomdisable", act_random_disable, RIGHT_GLOBAL_PREFS },
573 { "randomenable", act_random_enable, RIGHT_GLOBAL_PREFS },
574 { "register", act_register, 0 },
575 { "reminder", act_reminder, 0 },
576 { "remove", act_remove, RIGHT_MOVE__MASK|RIGHT_SCRATCH__MASK },
577 { "resume", act_resume, RIGHT_PAUSE },
578 { "set", act_set, RIGHT_PREFS },
579 { "volume", act_volume, RIGHT_VOLUME },
bca4e2b7
RK
580};
581
40dcd866
RK
582/** @brief Check that an action name is valid
583 * @param name Action
584 * @return 1 if valid, 0 if not
585 */
586static int dcgi_valid_action(const char *name) {
587 int c;
588
589 /* First character must be letter or digit (this also requires there to _be_
590 * a first character) */
591 if(!isalnum((unsigned char)*name))
592 return 0;
593 /* Only letters, digits, '.' and '-' allowed */
594 while((c = (unsigned char)*name++)) {
595 if(!(isalnum(c)
596 || c == '.'
597 || c == '_'))
598 return 0;
599 }
600 return 1;
601}
602
bca4e2b7
RK
603/** @brief Expand a template
604 * @param name Base name of template, or NULL to consult CGI args
e7ce7665 605 * @param header True to write header
bca4e2b7 606 */
e7ce7665 607void dcgi_expand(const char *name, int header) {
99955407 608 const char *p, *found;
0d0253c9
RK
609
610 /* Parse macros first */
99955407
RK
611 if((found = mx_find("macros.tmpl")))
612 mx_expand_file(found, sink_discard(), 0);
bca4e2b7 613 /* For unknown actions check that they aren't evil */
40dcd866 614 if(!dcgi_valid_action(name))
71634563
RK
615 fatal(0, "invalid action name '%s'", name);
616 byte_xasprintf((char **)&p, "%s.tmpl", name);
99955407
RK
617 if(!(found = mx_find(p)))
618 fatal(errno, "cannot find %s", p);
e7ce7665
RK
619 if(header) {
620 if(printf("Content-Type: text/html\n"
621 "%s\n"
622 "\n", dcgi_cookie_header()) < 0)
623 fatal(errno, "error writing to stdout");
624 }
99955407 625 if(mx_expand_file(found, sink_stdio("stdout", stdout), 0) == -1
bca4e2b7
RK
626 || fflush(stdout) < 0)
627 fatal(errno, "error writing to stdout");
628}
629
630/** @brief Execute a web action
631 * @param action Action to perform, or NULL to consult CGI args
632 *
633 * If no recognized action is specified then 'playing' is assumed.
634 */
1e97629d 635void dcgi_action(const char *action) {
bca4e2b7 636 int n;
bca4e2b7
RK
637
638 /* Consult CGI args if caller had no view */
639 if(!action)
640 action = cgi_get("action");
641 /* Pick a default if nobody cares at all */
642 if(!action) {
643 /* We allow URLs which are just c=... in order to keep confirmation URLs,
644 * which are user-facing, as short as possible. Actually we could lose the
645 * c= for this... */
646 if(cgi_get("c"))
647 action = "confirm";
648 else
649 action = "playing";
5a7df048
RK
650 /* Make sure 'action' is always set */
651 cgi_set("action", action);
bca4e2b7 652 }
02eaa49d
RK
653 if((n = TABLE_FIND(actions, struct action, name, action)) >= 0) {
654 if(actions[n].rights) {
655 /* Some right or other is required */
656 dcgi_lookup(DCGI_RIGHTS);
657 if(!(actions[n].rights & dcgi_rights)) {
2cc4c0ef 658 const char *back = cgi_thisurl(config->url);
02eaa49d 659 /* Failed operations jump you to the login screen with an error
2cc4c0ef
RK
660 * message. On success, the user comes back to the page they were
661 * after. */
662 cgi_clear();
663 cgi_set("back", back);
02eaa49d
RK
664 login_error("noright");
665 return;
666 }
667 }
668 /* It's a known action */
bca4e2b7 669 actions[n].handler();
02eaa49d 670 } else {
bca4e2b7 671 /* Just expand the template */
e7ce7665 672 dcgi_expand(action, 1/*header*/);
448d3570 673 }
bca4e2b7
RK
674}
675
676/** @brief Generate an error page */
0d0253c9
RK
677void dcgi_error(const char *key) {
678 dcgi_error_string = xstrdup(key);
e7ce7665 679 dcgi_expand("error", 1);
bca4e2b7
RK
680}
681
682/*
683Local Variables:
684c-basic-offset:2
685comment-column:40
686fill-column:79
687indent-tabs-mode:nil
688End:
689*/