audiod: fix mode cycling
[paraslash.git] / mysql_selector.c
1 /*
2  * Copyright (C) 1999-2007 Andre Noll <maan@systemlinux.org>
3  *
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  *
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  *
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 /** \file mysql_selector.c para_server's mysql-based audio file selector */
20
21 /** \cond some internal constants */
22 #define MEDIUM_BLOB_SIZE 16777220 /*  (2**24 + 4) */
23 #define BLOB_SIZE 65539 /* (2**16 + 3) */
24 /** \endcond */
25 #include "server.cmdline.h"
26 #include "server.h"
27 #include "vss.h"
28 #include "db.h"
29 #include <mysql/mysql.h>
30 #include <mysql/mysql_version.h>
31 #include <regex.h>
32 #include "error.h"
33 #include "net.h"
34 #include "string.h"
35 #include "user_list.h"
36 #include "mysql_selector_command_list.h"
37
38 /** pointer to the shared memory area */
39 extern struct misc_meta_data *mmd;
40
41 static void *mysql_ptr = NULL;
42
43 /**
44  * contains name/replacement pairs used by s_a_r_list()
45  *
46  * \sa s_a_r()
47  */
48 struct para_macro {
49         /** the name of the macro */
50         const char *name;
51         /** the replacement text */
52         const char *replacement;
53 };
54
55 static struct para_macro macro_list[] = {
56         {       .name = "IS_N_SET",
57                 .replacement = "(data.%s != '1')"
58         }, {
59                 .name = "IS_SET",
60                 .replacement = "(data.%s = '1')"
61         }, {
62                 .name = "PICID",
63                 .replacement = "%sdata.Pic_Id"
64         }, {
65                 .name = "NAME_LIKE",
66                 .replacement = "(data.name like '%s')"
67         }, {
68                 .name = "LASTPLAYED",
69                 .replacement = "%sFLOOR((UNIX_TIMESTAMP(now())"
70                         "-UNIX_TIMESTAMP(data.Lastplayed))/60)"
71         }, {
72                 .name = "NUMPLAYED",
73                 .replacement = "%sdata.Numplayed"
74         }, {
75                 .name = NULL,
76         }
77 };
78
79 /**
80  * simple search and replace routine
81  *
82  * \param src source string
83  * \param macro_name the name of the macro
84  * \param replacement the replacement format string
85  *
86  * In \p src, replace each occurence of \p macro_name(arg) by the string
87  * determined by the \p replacement format string. \p replacement may (but
88  * needs not) contain a single string conversion specifier (%s) which gets
89  * replaced by \p arg.
90  *
91  * \return A string in which all matches in \p src are replaced, or \p NULL if
92  * an syntax error was encountered. Caller must free the result.
93  *
94  * \sa regcomp(3)
95  */
96 __must_check __malloc static char *s_a_r(const char *src, const char* macro_name,
97                 const char *replacement)
98 {
99         regex_t preg;
100         size_t  nmatch = 1;
101         regmatch_t pmatch[1];
102         int eflags = 0;
103         char *dest = NULL;
104         const char *bufptr = src;
105
106         if (!macro_name || !replacement || !src)
107                 return para_strdup(src);
108         regcomp(&preg, macro_name, 0);
109         while (regexec(&preg,  bufptr, nmatch, pmatch, eflags)
110                         != REG_NOMATCH) {
111                 char *tmp, *arg, *o_bracket, *c_bracket;
112
113                 o_bracket = strchr(bufptr + pmatch[0].rm_so, '(');
114                 c_bracket = o_bracket? strchr(o_bracket, ')') : NULL;
115                 if (!c_bracket)
116                         goto out;
117                 tmp = para_strdup(bufptr);
118                 tmp[pmatch[0].rm_so] = '\0';
119                 dest = para_strcat(dest, tmp);
120                 free(tmp);
121
122                 arg = para_strdup(o_bracket + 1);
123                 arg[c_bracket - o_bracket - 1] = '\0';
124                 tmp = make_message(replacement, arg);
125                 free(arg);
126                 dest = para_strcat(dest, tmp);
127                 free(tmp);
128                 bufptr = c_bracket;
129                 bufptr++;
130         }
131         dest = para_strcat(dest, bufptr);
132 //      PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
133 out:
134         regfree(&preg);
135         return dest;
136 }
137
138 /**
139  * replace a string according to a list of macros
140  *
141  * \param macro_list the array containing a macro/replacement pairs.
142  * \param src the source string
143  *
144  * This function just calls s_a_r() for each element of \p macro_list.
145  *
146  * \return \p NULL if one of the underlying calls to \p s_a_r returned \p NULL.
147  * Otherwise the completely expanded version of \p src is returned.
148  */
149 __must_check __malloc static char *s_a_r_list(struct para_macro *macro_list, char *src)
150 {
151         struct para_macro *mp = macro_list;
152         char *ret = NULL, *tmp = para_strdup(src);
153
154         while (mp->name) {
155                 ret = s_a_r(tmp, mp->name, mp->replacement);
156                 free(tmp);
157                 if (!ret) /* syntax error */
158                         return NULL;
159                 tmp = ret;
160                 mp++;
161         }
162         //PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
163         return ret;
164 }
165
166 static int real_query(const char *query)
167 {
168         if (!mysql_ptr)
169                 return -E_NOTCONN;
170         PARA_DEBUG_LOG("%s\n", query);
171         if (mysql_real_query(mysql_ptr, query, strlen(query))) {
172                 PARA_ERROR_LOG("real_query error (%s)\n",
173                         mysql_error(mysql_ptr));
174                 return -E_QFAILED;
175         }
176         return 1;
177 }
178
179 /*
180  * Use open connection given by mysql_ptr to query server. Returns a
181  * result pointer on succes and NULL on errors
182  */
183 static struct MYSQL_RES *get_result(const char *query)
184 {
185         void *result;
186
187         if (real_query(query) < 0)
188                 return NULL;
189         result = mysql_store_result(mysql_ptr);
190         if (!result)
191                 PARA_ERROR_LOG("%s", "store_result error\n");
192         return result;
193 }
194 /*
195  * write input from fd to dynamically allocated char array,
196  * but maximal max_size byte. Return size.
197  */
198 static int fd2buf(int fd, char **buf_ptr, size_t max_size)
199 {
200         const size_t chunk_size = 1024;
201         size_t size = 2048;
202         char *buf = para_malloc(size * sizeof(char)), *p = buf;
203         int ret;
204
205         while ((ret = recv_bin_buffer(fd, p, chunk_size)) > 0) {
206                 p += ret;
207                 if ((p - buf) + chunk_size >= size) {
208                         char *tmp;
209
210                         size *= 2;
211                         if (size > max_size) {
212                                 ret = -E_TOOBIG;
213                                 goto out;
214                         }
215                         tmp = para_realloc(buf, size);
216                         p = (p - buf) + tmp;
217                         buf = tmp;
218                 }
219         }
220         if (ret < 0)
221                 goto out;
222         *buf_ptr = buf;
223         ret = p - buf;
224 out:
225         if (ret < 0 && buf)
226                 free(buf);
227         return ret;
228 }
229
230 static char *escape_blob(const char* old, int size)
231 {
232         char *new;
233
234         if (!mysql_ptr || size < 0)
235                 return NULL;
236         new = para_malloc(2 * size * sizeof(char) + 1);
237         mysql_real_escape_string(mysql_ptr, new, old, size);
238         return new;
239 }
240
241 static char *escape_str(const char* old)
242 {
243         return escape_blob(old, strlen(old));
244 }
245
246 static char *escaped_basename(const char *name)
247 {
248         char *esc, *bn = para_basename(name);
249
250         if (!bn)
251                 return NULL;
252         esc = escape_str(bn);
253         free(bn);
254         return esc;
255 }
256
257 /*
258  * new attribute
259  */
260 int com_na(__a_unused int fd, int argc, char *argv[])
261 {
262         char *q, *tmp;
263         int ret;
264
265         if (argc < 2)
266                 return -E_MYSQL_SYNTAX;
267         tmp = escape_str(argv[1]);
268         if (!tmp)
269                 return -E_ESCAPE;
270         q = make_message("alter table data add %s char(1) "
271                 "not null default 0", tmp);
272         free(tmp);
273         ret = real_query(q);
274         free(q);
275         return ret;
276 }
277
278 /*
279  * delete attribute
280  */
281 int com_da(__a_unused int fd, int argc, char *argv[])
282 {
283         char *q, *tmp;
284         int ret;
285
286         if (argc < 2)
287                 return -E_MYSQL_SYNTAX;
288         tmp = escape_str(argv[1]);
289         if (!tmp)
290                 return -E_ESCAPE;
291         q = make_message("alter table data drop %s", tmp);
292         free(tmp);
293         ret = real_query(q);
294         free(q);
295         return ret;
296 }
297
298 /* stradd/pic_add */
299 static int com_stradd_picadd(int fd, int argc, char *argv[])
300 {
301         char *blob = NULL, *esc_blob = NULL, *q = NULL, *tmp = NULL;
302         const char *fmt, *del_fmt;
303         int ret, stradd = strcmp(argv[0], "picadd");
304         size_t size;
305
306         if (argc < 2)
307                 return -E_MYSQL_SYNTAX;
308         if (strlen(argv[1]) >= MAXLINE - 1)
309                 return -E_NAMETOOLONG;
310         if (!mysql_ptr)
311                 return -E_NOTCONN;
312         if (stradd) {
313                 size = BLOB_SIZE;
314                 fmt = "insert into streams (name, def) values ('%s','%s')";
315                 del_fmt="delete from streams where name='%s'";
316         } else {
317                 size = MEDIUM_BLOB_SIZE;
318                 fmt = "insert into pics (name, pic) values ('%s','%s')";
319                 del_fmt="delete from pics where pic='%s'";
320         }
321         tmp = escape_str(argv[1]);
322         if (!tmp)
323                 return -E_ESCAPE;
324         q = make_message(del_fmt, tmp);
325         free(tmp);
326         ret = real_query(q);
327         free(q);
328         if (ret < 0)
329                 return ret;
330         if ((ret = send_buffer(fd, AWAITING_DATA_MSG) < 0))
331                 return ret;
332         if ((ret = fd2buf(fd, &blob, size)) < 0)
333                 return ret;
334         size = ret;
335         if (stradd)
336                 blob[size] = '\0';
337         ret = -E_ESCAPE;
338         esc_blob = escape_blob(blob, size);
339         if (!esc_blob)
340                 goto out;
341         tmp = escape_str(argv[1]);
342         if (!tmp)
343                 goto out;
344         q = make_message(fmt, tmp, esc_blob);
345         ret = real_query(q);
346 out:
347         free(blob);
348         free(esc_blob);
349         free(tmp);
350         free(q);
351         return ret;
352 }
353
354 /* stradd */
355 int com_stradd(int fd, int argc, char *argv[])
356 {
357         return com_stradd_picadd(fd, argc, argv);
358 }
359
360 /* pic_add */
361 int com_picadd(int fd, int argc, char *argv[])
362 {
363         return com_stradd_picadd(fd, argc, argv);
364 }
365
366 /*
367  * print results to fd
368  */
369 static int print_results(int fd, void *result,
370                 unsigned int top, unsigned int left,
371                 unsigned int bottom, unsigned int right)
372 {
373         unsigned int i,j;
374         int ret;
375         MYSQL_ROW row;
376
377         for (i = top; i <= bottom; i++) {
378                 row = mysql_fetch_row(result);
379                 if (!row || !row[0])
380                         return -E_NOROW;
381                 for (j = left; j <= right; j++) {
382                         ret = send_va_buffer(fd, j == left? "%s" : "\t%s",
383                                         row[j]?  row[j] : "NULL");
384                         if (ret < 0)
385                                 return ret;
386                 }
387                 ret = send_buffer(fd, "\n");
388                 if (ret < 0)
389                         return ret;
390         }
391         return 0;
392 }
393
394 /*
395  * verbatim
396  */
397 int com_verb(int fd, int argc, char *argv[])
398 {
399         void *result = NULL;
400         int ret;
401         unsigned int num_rows, num_fields;
402         char *tmp;
403
404         if (argc < 2)
405                 return -E_MYSQL_SYNTAX;
406         tmp = escape_str(argv[1]);
407         if (!tmp)
408                 return -E_ESCAPE;
409         result = get_result(tmp);
410         free(tmp);
411         if (!result)
412                 /* return success, because it's ok to have no results */
413                 return 1;
414         num_fields = mysql_field_count(mysql_ptr);
415         num_rows = mysql_num_rows(result);
416         ret = 1;
417         if (num_fields && num_rows)
418                 ret = print_results(fd, result, 0, 0, num_rows - 1,
419                         num_fields - 1);
420         mysql_free_result(result);
421         return ret;
422 }
423
424 /* returns NULL on errors or if there are no atts defined yet */
425 static void *get_all_attributes(void)
426 {
427         void *result = get_result("desc data");
428         unsigned int num_rows;
429
430         if (!result)
431                 return NULL;
432         num_rows = mysql_num_rows(result);
433         if (num_rows < 5) {
434                 mysql_free_result(result);
435                 return NULL;
436         }
437         mysql_data_seek(result, 4); /* skip Lastplayed, Numplayed... */
438         return result;
439 }
440
441 /*
442  * list all attributes
443  */
444 int com_laa(int fd, int argc, __a_unused char *argv[])
445 {
446         void *result;
447         int ret;
448
449         if (argc != 1)
450                 return -E_MYSQL_SYNTAX;
451         result = get_all_attributes();
452         if (!result)
453                 return -E_NOATTS;
454         ret = print_results(fd, result, 0, 0, mysql_num_rows(result) - 5, 0);
455         mysql_free_result(result);
456         return ret;
457 }
458
459 /*
460  * history
461  */
462 int com_hist(int fd, int argc, char *argv[]) {
463         int ret;
464         void *result = NULL;
465         char *q, *atts;
466         unsigned int num_rows;
467
468         if (argc > 3)
469                 return -E_MYSQL_SYNTAX;
470         if (argc > 1) {
471                 char *tmp = escape_str(argv[1]);
472                 if (!tmp)
473                         return -E_ESCAPE;
474                 atts = make_message("where %s = '1'", tmp);
475                 free(tmp);
476         } else
477                 atts = para_strdup(NULL);
478
479         q = make_message("select name, to_days(now()) - to_days(lastplayed) from "
480                 "data %s order by lastplayed", atts);
481         free(atts);
482         result = get_result(q);
483         free(q);
484         if (!result)
485                 return -E_NORESULT;
486         num_rows = mysql_num_rows(result);
487         ret = 1;
488         if (num_rows)
489                 ret = print_results(fd, result, 0, 0, num_rows - 1, 1);
490         mysql_free_result(result);
491         return ret;
492 }
493
494 /*
495  * get last num audio files
496  */
497 int com_last(int fd, int argc, char *argv[])
498 {
499         void *result = NULL;
500         char *q;
501         int num, ret;
502
503         if (argc < 2)
504                 num = 10;
505         else
506                 num = atoi(argv[1]);
507         if (!num)
508                 return -E_MYSQL_SYNTAX;
509         q = make_message("select name from data order by lastplayed desc "
510                 "limit %u", num);
511         result = get_result(q);
512         free(q);
513         if (!result)
514                 return -E_NORESULT;
515         ret = print_results(fd, result, 0, 0, mysql_num_rows(result) - 1, 0);
516         mysql_free_result(result);
517         return ret;
518 }
519
520 int com_mbox(int fd, int argc, char *argv[])
521 {
522         void *result;
523         MYSQL_ROW row;
524         int ret;
525         unsigned int num_rows, num_fields;
526         char *query = para_strdup("select concat('From foo@localhost ', "
527                 "date_format(Lastplayed, '%a %b %e %T %Y'), "
528                 "'\nReceived: from\nTo: bar\n");
529
530         ret = -E_NOATTS;
531         result = get_all_attributes();
532         if (!result)
533                 goto out;
534         ret = -E_NOROW;
535         while ((row = mysql_fetch_row(result))) {
536                 char *tmp;
537
538                 if (!row[0])
539                         goto out;
540                 tmp = make_message("%s X-Attribute-%s: ', %s, '\n", query,
541                         row[0], row[0]);
542                 free(query);
543                 query = tmp;
544         }
545         query = para_strcat(query,
546                 "From: a\n"
547                 "Subject: "
548                 "', name, '"
549                 "\n\n\n"
550                 "') from data"
551         );
552         if (argc >= 2) {
553                 char *esc = escape_str(argv[1]), *tmp;
554                 ret = -E_ESCAPE;
555                 if (!esc)
556                         goto out;
557                 tmp = make_message("%s where name LIKE '%s'", query, esc);
558                 free(esc);
559                 free(query);
560                 query = tmp;
561         }
562         mysql_free_result(result);
563         ret = -E_NORESULT;
564         result = get_result(query);
565         if (!result)
566                 goto out;
567         ret = -E_EMPTY_RESULT;
568         num_fields = mysql_field_count(mysql_ptr);
569         num_rows = mysql_num_rows(result);
570         if (!num_fields || !num_rows)
571                 goto out;
572         ret = print_results(fd, result, 0, 0, num_rows - 1, num_fields - 1);
573 out:
574         free(query);
575         if (result)
576                 mysql_free_result(result);
577         return ret;
578 }
579
580 /* get attributes by name. If verbose is not 0, get_a writes a string
581  * into atts of the form 'att1="0",att2="1"', which is used in com_cam
582  * for contructing a mysql update query.
583  * never returns NULL in *NON VERBOSE* mode
584  */
585 static char *get_atts(char *name, int verbose)
586 {
587         char *atts = NULL, *buf, *ebn;
588         void *result = NULL, *result2 = NULL;
589         MYSQL_ROW row, row2;
590         int i, ret;
591         unsigned int num_fields;
592
593         ret = -E_NOATTS;
594         result2 = get_all_attributes();
595         if (!result2)
596                 goto out;
597         ret = -E_ESCAPE;
598         if (!(ebn = escaped_basename(name)))
599                 goto out;
600         buf = make_message("select * from data where name='%s'", ebn);
601         free(ebn);
602         ret = -E_NORESULT;
603         result = get_result(buf);
604         free(buf);
605         if (!result)
606                 goto out;
607         ret = -E_EMPTY_RESULT;
608         num_fields = mysql_num_fields(result);
609         if (num_fields < 5)
610                 goto out;
611         mysql_data_seek(result2, 4); /* skip Lastplayed, Numplayed... */
612         row = mysql_fetch_row(result);
613         ret = -E_NOROW;
614         if (!row)
615                 goto out;
616         for (i = 4; i < num_fields; i++) {
617                 int is_set = row[i] && !strcmp(row[i], "1");
618                 row2 = mysql_fetch_row(result2);
619                 if (!row2 || !row2[0])
620                         goto out;
621                 if (atts && (verbose || is_set))
622                         atts = para_strcat(atts, verbose? "," : " ");
623                 if (is_set || verbose)
624                         atts = para_strcat(atts, row2[0]);
625                 if (verbose)
626                         atts = para_strcat(atts, is_set? "=\"1\"" : "=\"0\"");
627         }
628         ret = 1;
629 out:
630         if (result2)
631                 mysql_free_result(result2);
632         if (result)
633                 mysql_free_result(result);
634         if (!atts && !verbose)
635                 atts = para_strdup("(none)");
636         return atts;
637 }
638
639 /* never returns NULL in verbose mode */
640 static char *get_meta(char *name, int verbose)
641 {
642         MYSQL_ROW row;
643         void *result = NULL;
644         char *ebn, *q, *ret = NULL;
645         const char *verbose_fmt =
646                 "select concat('lastplayed: ', "
647                 "(to_days(now()) - to_days(lastplayed)),"
648                 "' day(s). numplayed: ', numplayed, "
649                 "', pic: ', pic_id) "
650                 "from data where name = '%s'";
651         /* is that really needed? */
652         const char *fmt = "select concat('lastplayed=\\'', lastplayed, "
653                 "'\\', numplayed=\\'', numplayed, "
654                 "'\\', pic_id=\\'', pic_id, '\\'') "
655                 "from data where name = '%s'";
656
657         if (!(ebn = escaped_basename(name)))
658                 goto out;
659         q = make_message(verbose? verbose_fmt : fmt, ebn);
660         free(ebn);
661         result = get_result(q);
662         free(q);
663         if (!result)
664                 goto out;
665         row = mysql_fetch_row(result);
666         if (!row || !row[0])
667                 goto out;
668         ret = para_strdup(row[0]);
669 out:
670         if (result)
671                 mysql_free_result(result);
672         if (!ret && verbose)
673                 ret = para_strdup("(not yet played)");
674         return ret;
675 }
676
677 static char *get_dir(char *name)
678 {
679         char *ret = NULL, *q, *ebn;
680         void *result;
681         MYSQL_ROW row;
682
683         if (!(ebn = escaped_basename(name)))
684                 return NULL;
685         q = make_message("select dir from dir where name = '%s'", ebn);
686         free(ebn);
687         result = get_result(q);
688         free(q);
689         if (!result)
690                 return NULL;
691         row = mysql_fetch_row(result);
692         if (row && row[0])
693                 ret = para_strdup(row[0]);
694         mysql_free_result(result);
695         return ret;
696 }
697
698 /* never returns NULL */
699 static char *get_current_stream(void)
700 {
701         char *ret;
702         MYSQL_ROW row;
703         void *result = get_result("select def from streams where "
704                 "name = 'current_stream'");
705
706         if (!result)
707                 goto err_out;
708         row = mysql_fetch_row(result);
709         if (!row || !row[0])
710                 goto err_out;
711         ret = para_strdup(row[0]);
712         mysql_free_result(result);
713         return ret;
714 err_out:
715         if (result)
716                 mysql_free_result(result);
717         return para_strdup("(none)");
718 }
719
720 /*
721  * Read stream definition of stream streamname and construct mysql
722  * query. Return NULL on errors. If streamname is NULL, use current
723  * stream. If that is also NULL, use query that selects everything.
724  * If filename is NULL, query will list everything, otherwise only
725  * the score of given file.
726  */
727 static char *get_query(char *streamname, char *filename, int with_path)
728 {
729         char *accept_opts = NULL, *deny_opts = NULL, *score = NULL;
730         char *where_clause, *order, *query;
731         char command[255] = ""; /* buffer for sscanf */
732         void *result;
733         MYSQL_ROW row;
734         char *end, *tmp;
735         char *select_clause = NULL;
736         if (!streamname)
737                 tmp = get_current_stream();
738         else {
739                 tmp = escape_str(streamname);
740                 if (!tmp)
741                         return NULL;
742         }
743         if (!strcmp(tmp, "(none)")) {
744                 free(tmp);
745                 if (filename) {
746                         char *ret, *ebn = escaped_basename(filename);
747                         if (!ebn)
748                                 return NULL;
749                         ret = make_message("select to_days(now()) - "
750                                 "to_days(lastplayed) from data "
751                                 "where name = '%s'", ebn);
752                         free(ebn);
753                         return ret;
754                 }
755                 if (with_path)
756                         return make_message(
757                                 "select concat(dir.dir, '/', dir.name) "
758                                 "from data, dir where dir.name = data.name "
759                                 "order by data.lastplayed"
760                         );
761                 return make_message(
762                         "select name from data where name is not NULL "
763                         "order by lastplayed"
764                 );
765         }
766         free(tmp);
767         query = make_message("select def from streams where name = '%s'",
768                 streamname);
769         result = get_result(query);
770         free(query);
771         query = NULL;
772         if (!result)
773                 goto out;
774         row = mysql_fetch_row(result);
775         if (!row || !row[0])
776                 goto out;
777         end = row[0];
778         while (*end) {
779                 int n;
780                 char *arg, *line = end;
781
782                 if (!(end = strchr(line, '\n')))
783                         break;
784                 *end = '\0';
785                 end++;
786                 if (sscanf(line, "%200s%n", command, &n) < 1)
787                         continue;
788                 arg = line + n;
789                 if (!strcmp(command, "accept:")) {
790                         char *tmp2 = s_a_r_list(macro_list, arg);
791                         if (accept_opts)
792                                 accept_opts = para_strcat(
793                                         accept_opts, " or ");
794                         accept_opts = para_strcat(accept_opts, tmp2);
795                         free(tmp2);
796                         continue;
797                 }
798                 if (!strcmp(command, "deny:")) {
799                         char *tmp2 = s_a_r_list(macro_list, arg);
800                         if (deny_opts)
801                                 deny_opts = para_strcat(deny_opts, " or ");
802                         deny_opts = para_strcat(deny_opts, tmp2);
803                         free(tmp2);
804                         continue;
805                 }
806                 if (!score && !strcmp(command, "score:"))
807                         score = s_a_r_list(macro_list, arg);
808         }
809         if (!score) {
810                 score = s_a_r_list(macro_list, conf.mysql_default_score_arg);
811                 if (!score)
812                         goto out;
813         }
814         if (filename) {
815                 char *ebn = escaped_basename(filename);
816                 if (!ebn)
817                         goto out;
818                 select_clause = make_message("select %s from data ", score);
819                 free(score);
820                 where_clause = make_message( "where name = '%s' ", ebn);
821                 free(ebn);
822                 order = para_strdup("");
823                 goto write_query;
824         }
825         select_clause = para_strdup(with_path?
826                 "select concat(dir.dir, '/', dir.name) from data, dir "
827                 "where dir.name = data.name "
828                 :
829                 "select name from data where name is not NULL");
830         order = make_message("order by -(%s)", score);
831         free(score);
832         if (accept_opts && deny_opts) {
833                 where_clause = make_message("and ((%s) and not (%s)) ",
834                         accept_opts, deny_opts);
835                 goto write_query;
836         }
837         if (accept_opts && !deny_opts) {
838                 where_clause = make_message("and (%s) ", accept_opts);
839                 goto write_query;
840         }
841         if (!accept_opts && deny_opts) {
842                 where_clause = make_message("and not (%s) ", deny_opts);
843                 goto write_query;
844         }
845         where_clause = para_strdup("");
846 write_query:
847         query = make_message("%s %s %s", select_clause, where_clause, order);
848         free(order);
849         free(select_clause);
850         free(where_clause);
851 out:
852         if (accept_opts)
853                 free(accept_opts);
854         if (deny_opts)
855                 free(deny_opts);
856         if (result)
857                 mysql_free_result(result);
858         return query;
859 }
860
861
862
863 /*
864  * This is called from server and from some commands. Name must not be NULL
865  * Never returns NULL.
866  */
867 static char *get_selector_info(char *name)
868 {
869         char *meta, *atts, *info, *dir, *query, *stream;
870         void *result = NULL;
871         MYSQL_ROW row = NULL;
872
873         if (!name)
874                 return para_strdup("(none)");
875         stream = get_current_stream();
876         meta = get_meta(name, 1);
877         atts = get_atts(name, 0);
878         dir = get_dir(name);
879         /* get score */
880         query = get_query(stream, name, 0); /* FIXME: pass stream == NULL instead? */
881         if (!query)
882                 goto write;
883         result = get_result(query);
884         free(query);
885         if (result)
886                 row = mysql_fetch_row(result);
887 write:
888         info = make_message("dbinfo1:dir: %s\n"
889                 "dbinfo2:stream: %s, %s, score: %s\n"
890                 "dbinfo3:%s\n",
891                 dir? dir : "(not contained in table)",
892                 stream, meta, 
893                 (result && row && row[0])? row[0] : "(no score)",
894                 atts);
895         free(dir);
896         free(meta);
897         free(atts);
898         free(stream);
899         if (result)
900                 mysql_free_result(result);
901         return info;
902 }
903
904
905 /* might return NULL */
906 static char *get_current_audio_file(void)
907 {
908         char *name;
909         mmd_lock();
910         name = para_basename(mmd->filename);
911         mmd_unlock();
912         return name;
913 }
914
915 /* list attributes / print database info */
916 static int com_la_info(int fd, int argc, char *argv[])
917 {
918         char *name = NULL, *meta = NULL, *atts = NULL, *dir = NULL;
919         int ret, com_la = strcmp(argv[0], "info");
920
921         if (argc < 2) {
922                 ret = -E_GET_AUDIO_FILE;
923                 if (!(name = get_current_audio_file()))
924                         goto out;
925                 ret = send_va_buffer(fd, "%s\n", name);
926                 if (ret < 0)
927                         goto out;
928         } else {
929                 ret = -E_ESCAPE;
930                 if (!(name = escaped_basename(argv[1])))
931                         goto out;
932         }
933         meta = get_meta(name, 1);
934         atts = get_atts(name, 0);
935         dir = get_dir(name);
936         if (com_la)
937                 ret = send_va_buffer(fd, "%s\n", atts);
938         else
939                 ret = send_va_buffer(fd, "dir: %s\n" "%s\n" "attributes: %s\n",
940                         dir? dir : "(not contained in table)", meta, atts);
941 out:
942         free(meta);
943         free(atts);
944         free(dir);
945         free(name);
946         return ret;
947 }
948
949 /* list attributes */
950 int com_la(int fd, int argc, char *argv[])
951 {
952         return com_la_info(fd, argc, argv);
953 }
954
955 /* print database info */
956 int com_info(int fd, int argc, char *argv[])
957 {
958         return com_la_info(fd, argc, argv);
959 }
960
961 static int change_stream(const char *stream)
962 {
963         char *query;
964         int ret;
965         query = make_message("update streams set def='%s' "
966                 "where name = 'current_stream'", stream);
967         ret = real_query(query);
968         free(query);
969         return ret;
970 }
971
972 static int get_pic_id_by_name(char *name)
973 {
974         char *q, *ebn;
975         void *result = NULL;
976         long unsigned ret;
977         MYSQL_ROW row;
978
979         if (!(ebn = escaped_basename(name)))
980                 return -E_ESCAPE;
981         q = make_message("select pic_id from data where name = '%s'", ebn);
982         free(ebn);
983         result = get_result(q);
984         free(q);
985         if (!result)
986                 return -E_NORESULT;
987         row = mysql_fetch_row(result);
988         ret = -E_NOROW;
989         if (row && row[0])
990                 ret = atol(row[0]);
991         mysql_free_result(result);
992         return ret;
993 }
994
995 static int remove_entry(const char *name)
996 {
997         char *q, *ebn = escaped_basename(name);
998         int ret = -E_ESCAPE;
999
1000         if (!ebn)
1001                 goto out;
1002         q = make_message("delete from data where name = '%s'", ebn);
1003         real_query(q); /* ignore errors */
1004         free(q);
1005         q = make_message("delete from dir where name = '%s'", ebn);
1006         real_query(q); /* ignore errors */
1007         free(q);
1008         ret = 1;
1009 out:
1010         free(ebn);
1011         return ret;
1012 }
1013
1014 static int add_entry(const char *name)
1015 {
1016         char *q, *dn, *ebn = NULL, *edn = NULL;
1017         int ret;
1018
1019         if (!name || !*name)
1020                 return -E_MYSQL_SYNTAX;
1021         ebn = escaped_basename(name);
1022         if (!ebn)
1023                 return -E_ESCAPE;
1024         ret = -E_MYSQL_SYNTAX;
1025         dn = para_dirname(name);
1026         if (!dn)
1027                 goto out;
1028         ret = -E_ESCAPE;
1029         edn = escape_str(dn);
1030         free(dn);
1031         if (!edn || !*edn)
1032                 goto out;
1033         q = make_message("insert into data (name, pic_id) values "
1034                         "('%s', '%s')", ebn, "1");
1035         ret = real_query(q);
1036 //      ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1037         free(q);
1038         if (ret < 0)
1039                 goto out;
1040         q = make_message("insert into dir (name, dir) values "
1041                         "('%s', '%s')", ebn, edn);
1042 //      ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1043         ret = real_query(q);
1044         free(q);
1045 out:
1046         if (ebn)
1047                 free(ebn);
1048         if (edn)
1049                 free(edn);
1050         return ret;
1051 }
1052
1053 /*
1054  * remove/add entries
1055  */
1056 static int com_rm_ne(__a_unused int fd, int argc, char *argv[])
1057 {
1058         int ne = !strcmp(argv[0], "ne");
1059         int i, ret;
1060         if (argc < 2)
1061                 return -E_MYSQL_SYNTAX;
1062         for (i = 1; i < argc; i++) {
1063                 ret = remove_entry(argv[i]);
1064                 if (ret < 0)
1065                         return ret;
1066                 if (!ne)
1067                         continue;
1068                 ret = add_entry(argv[i]);
1069                 if (ret < 0)
1070                         return ret;
1071         }
1072         return 1;
1073 }
1074
1075 /*
1076  * rm
1077  */
1078 int com_rm(int fd, int argc, char *argv[])
1079 {
1080         return com_rm_ne(fd, argc, argv);
1081 }
1082
1083 /*
1084  * ne
1085  */
1086 int com_ne(int fd, int argc, char *argv[])
1087 {
1088         return com_ne(fd, argc, argv);
1089 }
1090
1091 /*
1092  * mv: rename entry
1093  */
1094 int com_mv(__a_unused int fd, int argc, char *argv[])
1095 {
1096         char *q, *dn, *ebn1 = NULL, *ebn2 = NULL, *edn = NULL;
1097         int ret;
1098
1099         if (argc != 3)
1100                 return -E_MYSQL_SYNTAX;
1101         ret = -E_ESCAPE;
1102         ebn1 = escaped_basename(argv[1]);
1103         ebn2 = escaped_basename(argv[2]);
1104         if (!ebn1 || !ebn2 || !*ebn1 || !*ebn2)
1105                 goto out;
1106         ret = -E_MYSQL_SYNTAX;
1107         if (!strcmp(ebn1, ebn2))
1108                 goto update_dir;
1109         remove_entry(argv[2]); /* no need to escape, ignore error */
1110         q = make_message("update data set name = '%s' where name = '%s'",
1111                 ebn2, ebn1);
1112         ret = real_query(q);
1113         free(q);
1114         if (ret < 0)
1115                 goto out;
1116         ret = -E_AUDIO_FILE;
1117         if (!mysql_affected_rows(mysql_ptr))
1118                 goto out;
1119         q = make_message("update dir set name = '%s' where name = '%s'",
1120                 ebn2, ebn1);
1121         ret = real_query(q);
1122         free(q);
1123         if (ret < 0)
1124                 goto out;
1125 update_dir:
1126         ret = 1;
1127         dn = para_dirname(argv[2]);
1128         if (!dn)
1129                 goto out;
1130         ret = -E_ESCAPE;
1131         edn = escape_str(dn);
1132         free(dn);
1133         if (!edn)
1134                 goto out;
1135         ret = 1;
1136         if (!*edn)
1137                 goto out;
1138         q = make_message("update dir set dir = '%s' where name = '%s'",
1139                 edn, ebn2);
1140         ret = real_query(q);
1141         free(q);
1142 out:
1143         free(edn);
1144         free(ebn1);
1145         free(ebn2);
1146         return ret;
1147 }
1148
1149 /*
1150  * set field
1151  */
1152 static int com_set(__a_unused int fd, int argc, char *argv[])
1153 {
1154         char *q, *ebn;
1155         long unsigned id;
1156         int i, ret;
1157         const char *field = strcmp(argv[0], "picass")? "numplayed" : "pic_id";
1158
1159         if (argc < 3)
1160                 return -E_MYSQL_SYNTAX;
1161         id = atol(argv[1]);
1162         for (i = 2; i < argc; i++) {
1163                 ebn = escaped_basename(argv[i]);
1164                 if (!ebn)
1165                         return -E_ESCAPE;
1166                 q = make_message("update data set %s = %lu "
1167                                 "where name = '%s'", field, id, ebn);
1168                 free(ebn);
1169                 ret = real_query(q);
1170                 free(q);
1171                 if (ret < 0)
1172                         return ret;
1173         }
1174         return 1;
1175 }
1176
1177 /*
1178  * snp: set numplayed
1179  */
1180 int com_picass(int fd, int argc, char *argv[])
1181 {
1182         return com_set(fd, argc, argv);
1183 }
1184
1185 /*
1186  * snp: set numplayed
1187  */
1188 int com_snp(int fd, int argc, char *argv[])
1189 {
1190         return com_set(fd, argc, argv);
1191 }
1192
1193 /*
1194  * picch: change entry's name in pics table
1195  */
1196 int com_picch(__a_unused int fd, int argc, char *argv[])
1197 {
1198         int ret;
1199         long unsigned id;
1200         char *q, *tmp;
1201
1202         if (argc != 3)
1203                 return -E_MYSQL_SYNTAX;
1204         id = atol(argv[1]);
1205         ret = -E_ESCAPE;
1206         tmp = escape_str(argv[2]);
1207         if (!tmp)
1208                 return -E_ESCAPE;
1209         q = make_message("update pics set name = '%s' where id = %lu", tmp, id);
1210         free(tmp);
1211         ret = real_query(q);
1212         free(q);
1213         return ret;
1214 }
1215
1216 /*
1217  * piclist: print list of pics in db
1218  */
1219 int com_piclist(__a_unused int fd, int argc, __a_unused char *argv[])
1220 {
1221         void *result = NULL;
1222         MYSQL_ROW row;
1223         unsigned long *length;
1224         int ret;
1225
1226         if (argc != 1)
1227                 return -E_MYSQL_SYNTAX;
1228         result = get_result("select id,name,pic from pics order by id");
1229         if (!result)
1230                 return -E_NORESULT;
1231         while ((row = mysql_fetch_row(result))) {
1232                 length = mysql_fetch_lengths(result);
1233                 if (!row || !row[0] || !row[1] || !row[2])
1234                         continue;
1235                 ret = send_va_buffer(fd, "%s\t%lu\t%s\n", row[0], length[2], row[1]);
1236                 if (ret < 0)
1237                         goto out;
1238         }
1239         ret = 1;
1240 out:
1241         mysql_free_result(result);
1242         return ret;
1243 }
1244
1245 /*
1246  * picdel: delete picture from database
1247  */
1248 int com_picdel(int fd, int argc, char *argv[])
1249 {
1250         char *q;
1251         long unsigned id;
1252         my_ulonglong aff;
1253         int i, ret;
1254
1255         if (argc < 2)
1256                 return -E_MYSQL_SYNTAX;
1257         for (i = 1; i < argc; i++) {
1258                 id = atol(argv[i]);
1259                 q = make_message("delete from pics where id = %lu", id);
1260                 ret = real_query(q);
1261                 free(q);
1262                 if (ret < 0)
1263                         return ret;
1264                 aff = mysql_affected_rows(mysql_ptr);
1265                 if (!aff) {
1266                         ret = send_va_buffer(fd, "No such id: %lu\n", id);
1267                         if (ret < 0)
1268                                 return ret;
1269                         continue;
1270                 }
1271                 q = make_message("update data set pic_id = 1 where pic_id = %lu", id);
1272                 ret = real_query(q);
1273                 free(q);
1274         }
1275         return 1;
1276 }
1277 /*
1278  * pic: get picture by name or by number
1279  */
1280 int com_pic(int fd, int argc, char *argv[])
1281 {
1282         void *result = NULL;
1283         MYSQL_ROW row;
1284         unsigned long *length, id;
1285         int ret;
1286         char *q, *name = NULL;
1287
1288         if (argc < 2) {
1289                 ret = -E_GET_AUDIO_FILE;
1290                 name = get_current_audio_file();
1291         } else {
1292                 ret = -E_ESCAPE;
1293                 name = escaped_basename(argv[1]);
1294         }
1295         if (!name)
1296                 return ret;
1297         if (*name == '#')
1298                 id = atoi(name + 1);
1299         else
1300                 id = get_pic_id_by_name(name);
1301         free(name);
1302         if (id <= 0)
1303                 return id;
1304         q = make_message("select pic from pics where id = '%lu'", id);
1305         result = get_result(q);
1306         free(q);
1307         if (!result)
1308                 return -E_NORESULT;
1309         row = mysql_fetch_row(result);
1310         ret = -E_NOROW;
1311         if (!row || !row[0])
1312                 goto out;
1313         length = mysql_fetch_lengths(result);
1314         ret = send_bin_buffer(fd, row[0], *length);
1315 out:
1316         mysql_free_result(result);
1317         return ret;
1318 }
1319
1320 /* strdel */
1321 int com_strdel(__a_unused int fd, int argc, char *argv[])
1322 {
1323         char *q, *tmp;
1324         int ret;
1325
1326         if (argc < 2)
1327                 return -E_MYSQL_SYNTAX;
1328         tmp = escape_str(argv[1]);
1329         if (!tmp)
1330                 return -E_ESCAPE;
1331         q = make_message("delete from streams where name='%s'", tmp);
1332         free(tmp);
1333         ret = real_query(q);
1334         free(q);
1335         return ret;
1336 }
1337
1338 /*
1339  * ls
1340  */
1341 int com_ls(int fd, int argc, char *argv[])
1342 {
1343         char *q;
1344         void *result;
1345         int ret;
1346         unsigned int num_rows;
1347
1348         if (argc > 2)
1349                 return -E_MYSQL_SYNTAX;
1350         if (argc > 1) {
1351                 char *tmp = escape_str(argv[1]);
1352                 if (!tmp)
1353                         return -E_ESCAPE;
1354                 q = make_message("select name from data where name like '%s'",
1355                         tmp);
1356                 free(tmp);
1357         } else
1358                 q = para_strdup("select name from data");
1359         result = get_result(q);
1360         free(q);
1361         if (!result)
1362                 return -E_NORESULT;
1363         num_rows = mysql_num_rows(result);
1364         ret = 1;
1365         if (num_rows)
1366                 ret = print_results(fd, result, 0, 0, num_rows - 1, 0);
1367         mysql_free_result(result);
1368         return ret;
1369 }
1370
1371 /*
1372  * summary
1373  */
1374 int com_summary(__a_unused int fd, int argc, __a_unused char *argv[])
1375 {
1376         MYSQL_ROW row;
1377         MYSQL_ROW row2;
1378         void *result;
1379         void *result2 = NULL;
1380         const char *fmt = "select count(name) from data where %s='1'";
1381         int ret = -E_NORESULT;
1382
1383         if (argc != 1)
1384                 return -E_MYSQL_SYNTAX;
1385         result = get_all_attributes();
1386         if (!result)
1387                 goto out;
1388         while ((row = mysql_fetch_row(result))) {
1389                 char *buf;
1390
1391                 ret = -E_NOROW;
1392                 if (!row[0])
1393                         goto out;
1394                 ret = -E_NORESULT;
1395                 buf = make_message(fmt, row[0]);
1396                 result2 = get_result(buf);
1397                 free(buf);
1398                 if (!result2)
1399                         goto out;
1400                 ret = -E_NOROW;
1401                 row2 = mysql_fetch_row(result2);
1402                 if (!row2 || !row2[0])
1403                         goto out;
1404                 ret = send_va_buffer(fd, "%s\t%s\n", row[0], row2[0]);
1405                 if (ret < 0)
1406                         goto out;
1407         }
1408         ret = 1;
1409 out:
1410         if (result2)
1411                 mysql_free_result(result2);
1412         if (result)
1413                 mysql_free_result(result);
1414         return ret;
1415 }
1416
1417 static int get_numplayed(char *name)
1418 {
1419         void *result;
1420         MYSQL_ROW row;
1421         const char *fmt = "select numplayed from data where name = '%s'";
1422         char *buf = make_message(fmt, name);
1423         int ret = -E_NORESULT;
1424
1425         result = get_result(buf);
1426         free(buf);
1427         if (!result)
1428                 goto out;
1429         ret = -E_NOROW;
1430         row = mysql_fetch_row(result);
1431         if (!row || !row[0])
1432                 goto out;
1433         ret = atoi(row[0]);
1434 out:
1435         if (result)
1436                 mysql_free_result(result);
1437         return ret;
1438 }
1439
1440 static int update_audio_file(char *name)
1441 {
1442         int ret;
1443         const char *fmt1 = "update data set lastplayed = now() where name = '%s'";
1444         const char *fmt2 = "update data set numplayed = %i where name = '%s'";
1445         char *q;
1446         char *ebn = escaped_basename(name);
1447
1448         ret = -E_ESCAPE;
1449         if (!ebn)
1450                 goto out;
1451         q = make_message(fmt1, ebn);
1452         ret = real_query(q);
1453         free(q);
1454         if (ret < 0)
1455                 goto out;
1456         ret = get_numplayed(ebn);
1457         if (ret < 0)
1458                 goto out;
1459         q = make_message(fmt2, ret + 1, ebn);
1460         ret = real_query(q);
1461         free(q);
1462 out:
1463         free(ebn);
1464         return ret;
1465 }
1466
1467 /* If called as child, mmd_lock must be held */
1468 static void update_mmd(char *info)
1469 {
1470         PARA_DEBUG_LOG("%s", "updating shared memory area\n");
1471         strncpy(mmd->selector_info, info, MMD_INFO_SIZE - 1);
1472         mmd->selector_info[MMD_INFO_SIZE - 1] = '\0';
1473 }
1474
1475 static void update_audio_file_server_handler(char *name)
1476 {
1477         char *info;
1478         info = get_selector_info(name);
1479         update_mmd(info);
1480         free(info);
1481         update_audio_file(name);
1482 }
1483
1484 int com_us(__a_unused int fd, int argc, char *argv[])
1485 {
1486         char *tmp;
1487         int ret;
1488
1489         if (argc != 2)
1490                 return -E_MYSQL_SYNTAX;
1491         tmp = escape_str(argv[1]);
1492         if (!tmp)
1493                 return -E_ESCAPE;
1494         ret = update_audio_file(argv[1]);
1495         free(tmp);
1496         return ret;
1497 }
1498
1499 static void refresh_selector_info(void)
1500 {
1501         char *name = get_current_audio_file();
1502         char *info;
1503
1504         if (!name)
1505                 return;
1506         info = get_selector_info(name);
1507         free(name);
1508         mmd_lock();
1509         update_mmd(info);
1510         mmd_unlock();
1511         free(info);
1512 }
1513
1514 /* select previous / next stream */
1515 static int com_ps_ns(__a_unused int fd, int argc, char *argv[])
1516 {
1517         char *query, *stream = get_current_stream();
1518         void *result = get_result("select name from streams");
1519         MYSQL_ROW row;
1520         int match = -1, ret, i;
1521         unsigned int num_rows;
1522
1523         if (argc != 1)
1524                 return -E_MYSQL_SYNTAX;
1525         ret = -E_NORESULT;
1526         if (!result)
1527                 goto out;
1528         num_rows = mysql_num_rows(result);
1529         ret = -E_EMPTY_RESULT;
1530         if (num_rows < 2)
1531                 goto out;
1532         ret = -E_NOROW;
1533         for (i = 0; i < num_rows; i++) {
1534                 row = mysql_fetch_row(result);
1535                 if (!row || !row[0])
1536                         goto out;
1537                 if (!strcmp(row[0], "current_stream"))
1538                         continue;
1539                 if (!strcmp(row[0], stream)) {
1540                         match = i;
1541                         break;
1542                 }
1543         }
1544         ret = -E_NO_STREAM;
1545         if (match < 0)
1546                 goto out;
1547         if (!strcmp(argv[0], "ps"))
1548                 i = match > 0? match - 1 : num_rows - 1;
1549         else
1550                 i = match < num_rows - 1? match + 1 : 0;
1551         ret = -E_NOROW;
1552         mysql_data_seek(result, i);
1553         row = mysql_fetch_row(result);
1554         if (!row || !row[0])
1555                 goto out;
1556         if (!strcmp(row[0], "current_stream")) {
1557                 if (!strcmp(argv[0], "ps")) {
1558                         i = match - 2;
1559                         i = i < 0? i + num_rows : i;
1560                 } else {
1561                         i = match + 2;
1562                         i = i > num_rows - 1? i - num_rows : i;
1563                 }
1564                 mysql_data_seek(result, i);
1565                 row = mysql_fetch_row(result);
1566                 if (!row || !row[0])
1567                         goto out;
1568         }
1569         query = make_message("update streams set def='%s' where name = "
1570                 "'current_stream'", row[0]);
1571         ret = real_query(query);
1572         free(query);
1573         refresh_selector_info();
1574 out:
1575         free(stream);
1576         if (result)
1577                 mysql_free_result(result);
1578         return ret;
1579 }
1580
1581 /* select previous stream */
1582 int com_ps(int fd, int argc, char *argv[])
1583 {
1584         return com_ps_ns(fd, argc, argv);
1585 }
1586
1587 /* select next stream */
1588 int com_ns(int fd, int argc, char *argv[])
1589 {
1590         return com_ps_ns(fd, argc, argv);
1591 }
1592
1593 /* streams */
1594 int com_streams(int fd, int argc, __a_unused char *argv[])
1595 {
1596         unsigned int num_rows;
1597         int i, ret = -E_NORESULT;
1598         void *result;
1599         MYSQL_ROW row;
1600
1601         if (argc > 1 && strcmp(argv[1], "current_stream"))
1602                 return -E_MYSQL_SYNTAX;
1603         if (argc > 1) {
1604                 char *cs = get_current_stream();
1605                 ret = send_va_buffer(fd, "%s\n", cs);
1606                 free(cs);
1607                 return ret;
1608         }
1609         result = get_result("select name from streams");
1610         if (!result)
1611                 goto out;
1612         num_rows = mysql_num_rows(result);
1613         ret = 1;
1614         if (!num_rows)
1615                 goto out;
1616         ret = -E_NOROW;
1617         for (i = 0; i < num_rows; i++) {
1618                 row = mysql_fetch_row(result);
1619                 if (!row || !row[0])
1620                         goto out;
1621                 if (strcmp(row[0], "current_stream"))
1622                         send_va_buffer(fd, "%s\n", row[0]);
1623         }
1624         ret = 1;
1625 out:
1626         if (result)
1627                 mysql_free_result(result);
1628         return ret;
1629 }
1630
1631 /* query stream definition */
1632 int com_strq(int fd, int argc, char *argv[])
1633 {
1634         MYSQL_ROW row;
1635         char *query, *name;
1636         void *result;
1637         int ret;
1638
1639         if (argc < 2) {
1640                 ret = -E_GET_STREAM;
1641                 name = get_current_stream();
1642         } else {
1643                 ret = -E_ESCAPE;
1644                 name = escaped_basename(argv[1]);
1645         }
1646         if (!name)
1647                 return ret;
1648         ret = -E_NORESULT;
1649         query = make_message("select def from streams where name='%s'", name);
1650         free(name);
1651         result = get_result(query);
1652         free(query);
1653         if (!result)
1654                 goto out;
1655         ret = -E_NOROW;
1656         row = mysql_fetch_row(result);
1657         if (!row || !row[0])
1658                 goto out;
1659         /* no '\n' needed */
1660         ret = send_buffer(fd, row[0]);
1661 out:
1662         if (result)
1663                 mysql_free_result(result);
1664         return ret;
1665 }
1666
1667 /* change stream / change stream and play */
1668 static int com_cs_csp(int fd, int argc, char *argv[])
1669 {
1670         int ret, stream_change;
1671         char *query, *stream = NULL;
1672         char *old_stream = get_current_stream();
1673         int csp = !strcmp(argv[0], "csp");
1674
1675         ret = -E_MYSQL_SYNTAX;
1676         if (argc > 2)
1677                 goto out;
1678         if (argc == 1) {
1679                 if (csp)
1680                         goto out;
1681                 ret = send_va_buffer(fd, "%s\n", old_stream);
1682                 goto out;
1683         }
1684         ret = -E_GET_QUERY;
1685         /* test if stream is valid, no need to escape argv[1] */
1686         query = get_query(argv[1], NULL, 0);
1687         if (!query)
1688                 goto out;
1689         free(query);
1690         /* stream is ok */
1691         stream = escape_str(argv[1]);
1692         if (!stream)
1693                 goto out;
1694         stream_change = strcmp(stream, old_stream);
1695         if (stream_change) {
1696                 ret = change_stream(stream);
1697                 if (ret < 0)
1698                         goto out;
1699                 refresh_selector_info();
1700         }
1701         if (csp) {
1702                 mmd_lock();
1703                 mmd->new_vss_status_flags |= VSS_PLAYING;
1704                 if (stream_change)
1705                         mmd->new_vss_status_flags |= VSS_NEXT;
1706                 mmd_unlock();
1707         }
1708         ret = 1;
1709 out:
1710         free(old_stream);
1711         free(stream);
1712         return ret;
1713 }
1714
1715 /* change stream */
1716 int com_cs(int fd, int argc, char *argv[])
1717 {
1718         return com_cs_csp(fd, argc, argv);
1719 }
1720
1721 /* change stream and play */
1722 int com_csp(int fd, int argc, char *argv[])
1723 {
1724         return com_cs_csp(fd, argc, argv);
1725 }
1726
1727 /* score list / skip */
1728 static int com_sl_skip(int fd, int argc, char *argv[])
1729 {
1730         void *result = NULL;
1731         MYSQL_ROW row;
1732         int ret, i, skip = !strcmp(argv[0], "skip");
1733         char *query, *stream, *tmp;
1734         unsigned int num_rows, num;
1735
1736         if (argc < 2)
1737                 return -E_MYSQL_SYNTAX;
1738         num = atoi(argv[1]);
1739         if (!num)
1740                 return -E_MYSQL_SYNTAX;
1741         if (argc == 2) {
1742                 stream = get_current_stream();
1743                 if (!stream)
1744                         return -E_GET_STREAM;
1745         } else {
1746                 stream = escape_str(argv[2]);
1747                 if (!stream)
1748                         return -E_ESCAPE;
1749         }
1750         tmp = get_query(stream, NULL, 0);
1751         free(stream);
1752         if (!tmp)
1753                 return -E_GET_QUERY;
1754         query = make_message("%s limit %d", tmp, num);
1755         free(tmp);
1756         ret = -E_NORESULT;
1757         result = get_result(query);
1758         free(query);
1759         if (!result)
1760                 goto out;
1761         ret = -E_EMPTY_RESULT;
1762         num_rows = mysql_num_rows(result);
1763         if (!num_rows)
1764                 goto out;
1765         for (i = 0; i < num_rows && i < num; i++) {
1766                 row = mysql_fetch_row(result);
1767                 if (skip) {
1768                         send_va_buffer(fd, "Skipping %s\n", row[0]);
1769                         update_audio_file(row[0]);
1770                 } else
1771                         send_va_buffer(fd, "%s\n", row[0]? row[0]: "BUG");
1772         }
1773         ret = 1;
1774 out:
1775         if (result)
1776                 mysql_free_result(result);
1777         return ret;
1778 }
1779
1780 /* score list */
1781 int com_sl(int fd, int argc, char *argv[])
1782 {
1783         return com_sl_skip(fd, argc, argv);
1784 }
1785
1786 /* skip */
1787 int com_skip(int fd, int argc, char *argv[])
1788 {
1789         return com_sl_skip(fd, argc, argv);
1790 }
1791
1792 /*
1793  * update attributes of name
1794  */
1795 static int update_atts(int fd, char *name, char *atts)
1796 {
1797         int ret;
1798         char *ebn, *q, *old, *new = NULL;
1799
1800         if (!mysql_ptr)
1801                 return -E_NOTCONN;
1802         ebn = escaped_basename(name);
1803         if (!ebn)
1804                 return -E_ESCAPE;
1805         q = make_message("update data set %s where name = '%s'", atts, ebn);
1806         old = get_atts(ebn, 0);
1807         send_va_buffer(fd, "old: %s\n", old);
1808         free(old);
1809         ret = real_query(q);
1810         free(q);
1811         if (ret < 0)
1812                 goto out;
1813         new = get_atts(ebn, 0);
1814         ret = send_va_buffer(fd, "new: %s\n", new);
1815         free(new);
1816 out:
1817         free(ebn);
1818         return ret;
1819 }
1820
1821 /*
1822  * set attributes
1823  */
1824 int com_sa(int fd, int argc, char *argv[])
1825 {
1826         int i, ret;
1827         char *atts = NULL, *name;
1828
1829         if (argc < 2)
1830                 return -E_MYSQL_SYNTAX;
1831         for (i = 1; i < argc; i++) {
1832                 int unset = 0;
1833                 char *esc, *tmp, *p =argv[i];
1834                 int len = strlen(p);
1835
1836                 if (!len)
1837                         continue;
1838                 switch (p[len - 1]) {
1839                         case '+':
1840                                 unset = 0;
1841                                 break;
1842                         case '-':
1843                                 unset = 1;
1844                                 break;
1845                         default:
1846                                 goto no_more_atts;
1847                 }
1848                 p[len - 1] = '\0';
1849                 esc = escape_str(p);
1850                 if (!esc)
1851                         return -E_ESCAPE;
1852                 tmp = make_message("%s%s='%s'", atts? "," : "", esc,
1853                         unset? "0" : "1");
1854                 free(esc);
1855                 atts = para_strcat(atts, tmp);
1856                 free(tmp);
1857         }
1858 no_more_atts:
1859         if (!atts)
1860                 return -E_NOATTS;
1861         if (i >= argc) { /* no name given, use current af */
1862                 ret = -E_GET_AUDIO_FILE;
1863                 if (!(name = get_current_audio_file()))
1864                         goto out;
1865                 ret = update_atts(fd, name, atts);
1866                 free(name);
1867         } else {
1868                 ret = 1;
1869                 for (; argv[i] && ret >= 0; i++)
1870                         ret = update_atts(fd, argv[i], atts);
1871         }
1872         refresh_selector_info();
1873 out:
1874         free(atts);
1875         return ret;
1876 }
1877
1878 /*
1879  * copy attributes
1880  */
1881 int com_cam(int fd, int argc, char *argv[])
1882 {
1883         char *name = NULL, *meta = NULL, *atts = NULL;
1884         int i, ret;
1885
1886         if (argc < 3)
1887                 return -E_MYSQL_SYNTAX;
1888         if (!(name = escaped_basename(argv[1])))
1889                 return -E_ESCAPE;
1890         ret = -E_NOATTS;
1891         if (!(atts = get_atts(name, 1)))
1892                 goto out;
1893         ret = -E_META;
1894         if (!(meta = get_meta(name, 0)))
1895                 goto out;
1896         for (i = 2; i < argc; i++) {
1897                 char *ebn, *q;
1898                 ret = -E_ESCAPE;
1899                 if (!(ebn = escaped_basename(argv[i])))
1900                         goto out;
1901                 ret = send_va_buffer(fd, "updating %s\n", ebn);
1902                 if (ret < 0) {
1903                         free(ebn);
1904                         goto out;
1905                 }
1906                 q = make_message("update data set %s where name = '%s'",
1907                         meta, ebn);
1908                 if ((ret = update_atts(fd, ebn, atts)) >= 0)
1909                         ret = real_query(q);
1910                 free(ebn);
1911                 free(q);
1912                 if (ret < 0)
1913                         goto out;
1914         }
1915         ret = 1;
1916 out:
1917         if (name)
1918                 free(name);
1919         if (meta)
1920                 free(meta);
1921         if (atts)
1922                 free(atts);
1923         return ret;
1924 }
1925
1926 /*
1927  * verify / clean
1928  */
1929 static int com_vrfy_clean(int fd, int argc, __a_unused char *argv[])
1930 {
1931         char *query;
1932         int ret, vrfy_mode = strcmp(argv[0], "clean");
1933         void *result = NULL;
1934         unsigned int num_rows;
1935         MYSQL_ROW row;
1936         char *escaped_name;
1937
1938         if (argc != 1)
1939                 return -E_MYSQL_SYNTAX;
1940         ret = -E_NORESULT;
1941         result = get_result("select data.name from data left join dir on "
1942                 "dir.name = data.name where dir.name is NULL");
1943         if (!result)
1944                 goto out;
1945         num_rows = mysql_num_rows(result);
1946         if (!num_rows) {
1947                 ret = send_buffer(fd, "No invalid entries\n");
1948                 goto out;
1949         }
1950         if (vrfy_mode) {
1951                 send_va_buffer(fd, "found %i invalid entr%s\n", num_rows,
1952                         num_rows == 1? "y" : "ies");
1953                 ret = print_results(fd, result, 0, 0, num_rows - 1, 0);
1954                 goto out;
1955         }
1956         while ((row = mysql_fetch_row(result))) {
1957                 ret = -E_NOROW;
1958                 if (!row[0])
1959                         goto out;
1960                 ret = -E_ESCAPE;
1961                 escaped_name = escape_str(row[0]);
1962                 if (!escaped_name)
1963                         goto out;
1964                 send_va_buffer(fd, "deleting %s\n", escaped_name);
1965                 query = make_message("delete from data where name = '%s'",
1966                         escaped_name);
1967                 ret = real_query(query);
1968                 free(query);
1969                 if (ret < 0)
1970                         goto out;
1971         }
1972
1973 out:
1974         if (result)
1975                 mysql_free_result(result);
1976         return ret;
1977 }
1978
1979 /*
1980  * verify
1981  */
1982 int com_vrfy(int fd, int argc, char **argv)
1983 {
1984         return com_vrfy_clean(fd, argc, argv);
1985 }
1986
1987 /*
1988  * clean
1989  */
1990 int com_clean(int fd, int argc, char **argv)
1991 {
1992         return com_vrfy_clean(fd, argc, argv);
1993 }
1994
1995 static FILE *out_file;
1996
1997 static int mysql_write_tmp_file(const char *dir, const char *name)
1998 {
1999         int ret = -E_TMPFILE;
2000         char *msg = make_message("%s\t%s\n", dir, name);
2001         if (fputs(msg, out_file) != EOF)
2002                 ret = 1;
2003         free(msg);
2004         return ret;
2005 }
2006
2007 /*
2008  * update database
2009  */
2010 int com_upd(int fd, int argc, __a_unused char *argv[])
2011 {
2012         char *tempname = NULL, *query = NULL;
2013         int ret, out_fd = -1, num = 0;
2014         void *result = NULL;
2015         unsigned int num_rows;
2016         MYSQL_ROW row;
2017
2018         if (argc != 1)
2019                 return -E_MYSQL_SYNTAX;
2020         out_file = NULL;
2021         tempname = para_strdup("/tmp/mysql.tmp.XXXXXX");
2022         ret = para_mkstemp(tempname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
2023         if (ret < 0)
2024                 goto out;
2025         out_fd = ret;
2026         out_file = fdopen(out_fd, "w");
2027         if (!out_file) {
2028                 close(out_fd);
2029                 goto out;
2030         }
2031         if (find_audio_files(conf.mysql_audio_file_dir_arg, mysql_write_tmp_file) < 0)
2032                 goto out;
2033         num = ftell(out_file);
2034         /*
2035          * we have to make sure the file hit the disk before we call
2036          * real_query
2037          */
2038         fclose(out_file);
2039         out_file = NULL;
2040         PARA_DEBUG_LOG("wrote tempfile %s (%d bytes)\n", tempname, num);
2041         if (!num)
2042                 goto out;
2043         if ((ret = real_query("delete from dir")) < 0)
2044                 goto out;
2045         query = make_message("load data infile '%s' ignore into table dir "
2046                 "fields terminated by '\t' lines terminated by '\n' "
2047                 "(dir, name)", tempname);
2048         ret = real_query(query);
2049         free(query);
2050         if (ret < 0)
2051                 goto out;
2052         result = get_result("select dir.name from dir left join data on "
2053                 "data.name = dir.name where data.name is NULL");
2054         ret = -E_NORESULT;
2055         if (!result)
2056                 goto out;
2057         num_rows = mysql_num_rows(result);
2058         if (!num_rows) {
2059                 ret = send_buffer(fd, "no new entries\n");
2060                 goto out;
2061         }
2062         while ((row = mysql_fetch_row(result))) {
2063                 char *erow;
2064                 ret = -E_NOROW;
2065                 if (!row[0])
2066                         goto out;
2067                 send_va_buffer(fd, "new entry: %s\n", row[0]);
2068                 erow = escape_str(row[0]);
2069                 if (!erow)
2070                         goto out;
2071                 query = make_message("insert into data (name, pic_id) values "
2072                         "('%s','%s')", erow, "1");
2073                 free(erow);
2074                 ret = real_query(query);
2075                 free(query);
2076                 if (ret < 0)
2077                         goto out;
2078         }
2079         ret = 1;
2080 out:
2081         if (out_fd >= 0)
2082                 unlink(tempname);
2083         free(tempname);
2084         if (out_file)
2085                 fclose(out_file);
2086         if (result)
2087                 mysql_free_result(result);
2088         return ret;
2089 }
2090
2091 static char **server_get_audio_file_list(unsigned int num)
2092 {
2093         char **list = para_malloc((num + 1) * sizeof(char *));
2094         char *tmp, *query, *stream = get_current_stream();
2095         void *result = NULL;
2096         unsigned int num_rows;
2097         int i = 0;
2098         MYSQL_ROW row;
2099
2100         tmp = get_query(stream, NULL, 1);
2101         free(stream);
2102         if (!tmp)
2103                 goto err_out;
2104         query = make_message("%s limit %d", tmp, num);
2105         free(tmp);
2106         result = get_result(query);
2107         free(query);
2108         if (!result)
2109                 goto err_out;
2110         num_rows = mysql_num_rows(result);
2111         if (!num_rows)
2112                 goto err_out;
2113         for (i = 0; i < num_rows && i < num; i++) {
2114                 row = mysql_fetch_row(result);
2115                 if (!row || !row[0])
2116                         goto err_out;
2117                 list[i] = para_strdup(row[0]);
2118         }
2119         list[i] = NULL;
2120         goto success;
2121 err_out:
2122         while (i > 0) {
2123                 i--;
2124                 free(list[i]);
2125         }
2126         free(list);
2127         list = NULL;
2128 success:
2129         if (result)
2130                 mysql_free_result(result);
2131         return list;
2132 }
2133
2134 /*
2135  * connect to mysql server, return mysql pointer on success, -E_NOTCONN
2136  * on errors. Called from parent on startup and also from com_cdb().
2137  */
2138 static int init_mysql_server(void)
2139 {
2140         char *u = conf.mysql_user_arg? conf.mysql_user_arg : para_logname();
2141
2142         mysql_ptr = mysql_init(NULL);
2143         if (!mysql_ptr) {
2144                 PARA_CRIT_LOG("%s", "mysql init error\n");
2145                 return -E_NOTCONN;
2146         }
2147         PARA_DEBUG_LOG("connecting: %s@%s:%d\n", u, conf.mysql_host_arg,
2148                 conf.mysql_port_arg);
2149         if (!conf.mysql_user_arg)
2150                 free(u);
2151         /*
2152          * If host is NULL a connection to the local host is assumed,
2153          * If user is NULL, the current user is assumed
2154          */
2155         if (!(mysql_ptr = mysql_real_connect(mysql_ptr,
2156                         conf.mysql_host_arg,
2157                         conf.mysql_user_arg,
2158                         conf.mysql_passwd_arg,
2159                         conf.mysql_database_arg,
2160                         conf.mysql_port_arg, NULL, 0))) {
2161                 PARA_CRIT_LOG("%s", "connect error\n");
2162                 return -E_NOTCONN;
2163         }
2164         PARA_INFO_LOG("%s", "success\n");
2165         return 1;
2166 }
2167
2168 /* mmd lock must be held */
2169 static void write_msg2mmd(int success)
2170 {
2171         sprintf(mmd->selector_info, "dbinfo1:%s\ndbinfo2:mysql-%s\ndbinfo3:\n",
2172                 success < 0? PARA_STRERROR(-success) :
2173                         "successfully connected to mysql server",
2174                 success < 0? "" : mysql_get_server_info(mysql_ptr));
2175 }
2176
2177 /* create database */
2178 int com_cdb(int fd, int argc, char *argv[])
2179 {
2180         char *query;
2181         int ret;
2182
2183         if (mysql_ptr) {
2184                 PARA_INFO_LOG("%s", "closing database\n");
2185                 mysql_close(mysql_ptr);
2186         }
2187         /* dont use any database */
2188         conf.mysql_database_arg = NULL; /* leak? */
2189         ret = -E_MYSQL_INIT;
2190         if (init_mysql_server() < 0 || !mysql_ptr)
2191                 goto out;
2192         if (argc < 2)
2193                 conf.mysql_database_arg = para_strdup("paraslash");
2194         else {
2195                 ret = -E_ESCAPE;
2196                 conf.mysql_database_arg = escape_str(argv[1]);
2197                 if (!conf.mysql_database_arg)
2198                         goto out;
2199         }
2200         query = make_message("create database %s", conf.mysql_database_arg);
2201         ret = real_query(query);
2202         free(query);
2203         if (ret < 0)
2204                 goto out;
2205         /* reconnect with database just created */
2206         mysql_close(mysql_ptr);
2207         ret = -E_MYSQL_INIT;
2208         if (init_mysql_server() < 0 || !mysql_ptr)
2209                 goto out;
2210         mmd_lock();
2211         write_msg2mmd(1);
2212         mmd_unlock();
2213         ret = -E_QFAILED;
2214         if (real_query("create table data (name varchar(255) binary not null "
2215                         "primary key, "
2216                         "lastplayed datetime not null default "
2217                                 "'1970-01-01', "
2218                         "numplayed int not null default 0, "
2219                         "pic_id bigint unsigned not null default 1)") < 0)
2220                 goto out;
2221         if (real_query("create table dir (name varchar(255) binary not null "
2222                         "primary key, dir varchar(255) default null)") < 0)
2223                 goto out;
2224         if (real_query("create table pics ("
2225                         "id bigint(20) unsigned not null primary key "
2226                         "auto_increment, "
2227                         "name varchar(255) binary not null, "
2228                         "pic mediumblob not null)") < 0)
2229                 goto out;
2230         if (real_query("create table streams ("
2231                         "name varchar(255) binary not null primary key, "
2232                         "def blob not null)") < 0)
2233                 goto out;
2234         if (real_query("insert into streams (name, def) values "
2235                         "('current_stream', '(none)')") < 0)
2236                 goto out;
2237         ret = send_va_buffer(fd, "successfully created database %s\n",
2238                 conf.mysql_database_arg);
2239 out:
2240         return ret;
2241 }
2242
2243 static void shutdown_connection(void)
2244 {
2245         if (mysql_ptr) {
2246                 PARA_NOTICE_LOG("%s", "shutting down mysql connection\n");
2247                 mysql_close(mysql_ptr);
2248                 mysql_ptr = NULL;
2249         }
2250 }
2251
2252 /**
2253  * the init function of the mysql-based audio file selector
2254  *
2255  * \param db pointer to the struct to initialize
2256  *
2257  * Check the command line options and initialize all function pointers of \a
2258  * db.  Connect to the mysql server and initialize the info string.
2259  *
2260  * \return This function returns success even if it could not connect
2261  * to the mysql server. This is because the connect is expected to fail
2262  * if there the paraslash database is not yet created. This gives the
2263  * user a chance to send the "cdb" to create the database.
2264  *
2265  * \sa struct audio_file_selector, misc_meta_data::selector_info,
2266  * random_selector.c
2267  */
2268 int mysql_selector_init(struct audio_file_selector *db)
2269 {
2270         int ret;
2271
2272         if (!conf.mysql_passwd_given)
2273                 return -E_NO_MYSQL_PASSWD;
2274         if (!conf.mysql_audio_file_dir_given)
2275                 return -E_NO_AF_DIR;
2276         db->name = "mysql";
2277         db->cmd_list = mysql_selector_cmds;
2278         db->get_audio_file_list = server_get_audio_file_list;
2279         db->update_audio_file = update_audio_file_server_handler;
2280         db->shutdown = shutdown_connection;
2281         ret = init_mysql_server();
2282         if (ret < 0)
2283                 PARA_WARNING_LOG("%s\n", PARA_STRERROR(-ret));
2284         write_msg2mmd(ret);
2285         return 1;       /* return success even if connect failed to give the
2286                          * user the chance to exec com_cdb
2287                          */
2288 }