command_util.sh: Make it read the function prototype from the source file
[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 {
464         int ret;
465         void *result = NULL;
466         char *q, *atts;
467         unsigned int num_rows;
468
469         if (argc > 3)
470                 return -E_MYSQL_SYNTAX;
471         if (argc > 1) {
472                 char *tmp = escape_str(argv[1]);
473                 if (!tmp)
474                         return -E_ESCAPE;
475                 atts = make_message("where %s = '1'", tmp);
476                 free(tmp);
477         } else
478                 atts = para_strdup(NULL);
479
480         q = make_message("select name, to_days(now()) - to_days(lastplayed) from "
481                 "data %s order by lastplayed", atts);
482         free(atts);
483         result = get_result(q);
484         free(q);
485         if (!result)
486                 return -E_NORESULT;
487         num_rows = mysql_num_rows(result);
488         ret = 1;
489         if (num_rows)
490                 ret = print_results(fd, result, 0, 0, num_rows - 1, 1);
491         mysql_free_result(result);
492         return ret;
493 }
494
495 /*
496  * get last num audio files
497  */
498 int com_last(int fd, int argc, char *argv[])
499 {
500         void *result = NULL;
501         char *q;
502         int num, ret;
503
504         if (argc < 2)
505                 num = 10;
506         else
507                 num = atoi(argv[1]);
508         if (!num)
509                 return -E_MYSQL_SYNTAX;
510         q = make_message("select name from data order by lastplayed desc "
511                 "limit %u", num);
512         result = get_result(q);
513         free(q);
514         if (!result)
515                 return -E_NORESULT;
516         ret = print_results(fd, result, 0, 0, mysql_num_rows(result) - 1, 0);
517         mysql_free_result(result);
518         return ret;
519 }
520
521 int com_mbox(int fd, int argc, char *argv[])
522 {
523         void *result;
524         MYSQL_ROW row;
525         int ret;
526         unsigned int num_rows, num_fields;
527         char *query = para_strdup("select concat('From foo@localhost ', "
528                 "date_format(Lastplayed, '%a %b %e %T %Y'), "
529                 "'\nReceived: from\nTo: bar\n");
530
531         ret = -E_NOATTS;
532         result = get_all_attributes();
533         if (!result)
534                 goto out;
535         ret = -E_NOROW;
536         while ((row = mysql_fetch_row(result))) {
537                 char *tmp;
538
539                 if (!row[0])
540                         goto out;
541                 tmp = make_message("%s X-Attribute-%s: ', %s, '\n", query,
542                         row[0], row[0]);
543                 free(query);
544                 query = tmp;
545         }
546         query = para_strcat(query,
547                 "From: a\n"
548                 "Subject: "
549                 "', name, '"
550                 "\n\n\n"
551                 "') from data"
552         );
553         if (argc >= 2) {
554                 char *esc = escape_str(argv[1]), *tmp;
555                 ret = -E_ESCAPE;
556                 if (!esc)
557                         goto out;
558                 tmp = make_message("%s where name LIKE '%s'", query, esc);
559                 free(esc);
560                 free(query);
561                 query = tmp;
562         }
563         mysql_free_result(result);
564         ret = -E_NORESULT;
565         result = get_result(query);
566         if (!result)
567                 goto out;
568         ret = -E_EMPTY_RESULT;
569         num_fields = mysql_field_count(mysql_ptr);
570         num_rows = mysql_num_rows(result);
571         if (!num_fields || !num_rows)
572                 goto out;
573         ret = print_results(fd, result, 0, 0, num_rows - 1, num_fields - 1);
574 out:
575         free(query);
576         if (result)
577                 mysql_free_result(result);
578         return ret;
579 }
580
581 /* get attributes by name. If verbose is not 0, get_a writes a string
582  * into atts of the form 'att1="0",att2="1"', which is used in com_cam
583  * for contructing a mysql update query.
584  * never returns NULL in *NON VERBOSE* mode
585  */
586 static char *get_atts(char *name, int verbose)
587 {
588         char *atts = NULL, *buf, *ebn;
589         void *result = NULL, *result2 = NULL;
590         MYSQL_ROW row, row2;
591         int i, ret;
592         unsigned int num_fields;
593
594         ret = -E_NOATTS;
595         result2 = get_all_attributes();
596         if (!result2)
597                 goto out;
598         ret = -E_ESCAPE;
599         if (!(ebn = escaped_basename(name)))
600                 goto out;
601         buf = make_message("select * from data where name='%s'", ebn);
602         free(ebn);
603         ret = -E_NORESULT;
604         result = get_result(buf);
605         free(buf);
606         if (!result)
607                 goto out;
608         ret = -E_EMPTY_RESULT;
609         num_fields = mysql_num_fields(result);
610         if (num_fields < 5)
611                 goto out;
612         mysql_data_seek(result2, 4); /* skip Lastplayed, Numplayed... */
613         row = mysql_fetch_row(result);
614         ret = -E_NOROW;
615         if (!row)
616                 goto out;
617         for (i = 4; i < num_fields; i++) {
618                 int is_set = row[i] && !strcmp(row[i], "1");
619                 row2 = mysql_fetch_row(result2);
620                 if (!row2 || !row2[0])
621                         goto out;
622                 if (atts && (verbose || is_set))
623                         atts = para_strcat(atts, verbose? "," : " ");
624                 if (is_set || verbose)
625                         atts = para_strcat(atts, row2[0]);
626                 if (verbose)
627                         atts = para_strcat(atts, is_set? "=\"1\"" : "=\"0\"");
628         }
629         ret = 1;
630 out:
631         if (result2)
632                 mysql_free_result(result2);
633         if (result)
634                 mysql_free_result(result);
635         if (!atts && !verbose)
636                 atts = para_strdup("(none)");
637         return atts;
638 }
639
640 /* never returns NULL in verbose mode */
641 static char *get_meta(char *name, int verbose)
642 {
643         MYSQL_ROW row;
644         void *result = NULL;
645         char *ebn, *q, *ret = NULL;
646         const char *verbose_fmt =
647                 "select concat('lastplayed: ', "
648                 "(to_days(now()) - to_days(lastplayed)),"
649                 "' day(s). numplayed: ', numplayed, "
650                 "', pic: ', pic_id) "
651                 "from data where name = '%s'";
652         /* is that really needed? */
653         const char *fmt = "select concat('lastplayed=\\'', lastplayed, "
654                 "'\\', numplayed=\\'', numplayed, "
655                 "'\\', pic_id=\\'', pic_id, '\\'') "
656                 "from data where name = '%s'";
657
658         if (!(ebn = escaped_basename(name)))
659                 goto out;
660         q = make_message(verbose? verbose_fmt : fmt, ebn);
661         free(ebn);
662         result = get_result(q);
663         free(q);
664         if (!result)
665                 goto out;
666         row = mysql_fetch_row(result);
667         if (!row || !row[0])
668                 goto out;
669         ret = para_strdup(row[0]);
670 out:
671         if (result)
672                 mysql_free_result(result);
673         if (!ret && verbose)
674                 ret = para_strdup("(not yet played)");
675         return ret;
676 }
677
678 static char *get_dir(char *name)
679 {
680         char *ret = NULL, *q, *ebn;
681         void *result;
682         MYSQL_ROW row;
683
684         if (!(ebn = escaped_basename(name)))
685                 return NULL;
686         q = make_message("select dir from dir where name = '%s'", ebn);
687         free(ebn);
688         result = get_result(q);
689         free(q);
690         if (!result)
691                 return NULL;
692         row = mysql_fetch_row(result);
693         if (row && row[0])
694                 ret = para_strdup(row[0]);
695         mysql_free_result(result);
696         return ret;
697 }
698
699 /* never returns NULL */
700 static char *get_current_stream(void)
701 {
702         char *ret;
703         MYSQL_ROW row;
704         void *result = get_result("select def from streams where "
705                 "name = 'current_stream'");
706
707         if (!result)
708                 goto err_out;
709         row = mysql_fetch_row(result);
710         if (!row || !row[0])
711                 goto err_out;
712         ret = para_strdup(row[0]);
713         mysql_free_result(result);
714         return ret;
715 err_out:
716         if (result)
717                 mysql_free_result(result);
718         return para_strdup("(none)");
719 }
720
721 /*
722  * Read stream definition of stream streamname and construct mysql
723  * query. Return NULL on errors. If streamname is NULL, use current
724  * stream. If that is also NULL, use query that selects everything.
725  * If filename is NULL, query will list everything, otherwise only
726  * the score of given file.
727  */
728 static char *get_query(char *streamname, char *filename, int with_path)
729 {
730         char *accept_opts = NULL, *deny_opts = NULL, *score = NULL;
731         char *where_clause, *order, *query;
732         char command[255] = ""; /* buffer for sscanf */
733         void *result;
734         MYSQL_ROW row;
735         char *end, *tmp;
736         char *select_clause = NULL;
737         if (!streamname)
738                 tmp = get_current_stream();
739         else {
740                 tmp = escape_str(streamname);
741                 if (!tmp)
742                         return NULL;
743         }
744         if (!strcmp(tmp, "(none)")) {
745                 free(tmp);
746                 if (filename) {
747                         char *ret, *ebn = escaped_basename(filename);
748                         if (!ebn)
749                                 return NULL;
750                         ret = make_message("select to_days(now()) - "
751                                 "to_days(lastplayed) from data "
752                                 "where name = '%s'", ebn);
753                         free(ebn);
754                         return ret;
755                 }
756                 if (with_path)
757                         return make_message(
758                                 "select concat(dir.dir, '/', dir.name) "
759                                 "from data, dir where dir.name = data.name "
760                                 "order by data.lastplayed"
761                         );
762                 return make_message(
763                         "select name from data where name is not NULL "
764                         "order by lastplayed"
765                 );
766         }
767         free(tmp);
768         query = make_message("select def from streams where name = '%s'",
769                 streamname);
770         result = get_result(query);
771         free(query);
772         query = NULL;
773         if (!result)
774                 goto out;
775         row = mysql_fetch_row(result);
776         if (!row || !row[0])
777                 goto out;
778         end = row[0];
779         while (*end) {
780                 int n;
781                 char *arg, *line = end;
782
783                 if (!(end = strchr(line, '\n')))
784                         break;
785                 *end = '\0';
786                 end++;
787                 if (sscanf(line, "%200s%n", command, &n) < 1)
788                         continue;
789                 arg = line + n;
790                 if (!strcmp(command, "accept:")) {
791                         char *tmp2 = s_a_r_list(macro_list, arg);
792                         if (accept_opts)
793                                 accept_opts = para_strcat(
794                                         accept_opts, " or ");
795                         accept_opts = para_strcat(accept_opts, tmp2);
796                         free(tmp2);
797                         continue;
798                 }
799                 if (!strcmp(command, "deny:")) {
800                         char *tmp2 = s_a_r_list(macro_list, arg);
801                         if (deny_opts)
802                                 deny_opts = para_strcat(deny_opts, " or ");
803                         deny_opts = para_strcat(deny_opts, tmp2);
804                         free(tmp2);
805                         continue;
806                 }
807                 if (!score && !strcmp(command, "score:"))
808                         score = s_a_r_list(macro_list, arg);
809         }
810         if (!score) {
811                 score = s_a_r_list(macro_list, conf.mysql_default_score_arg);
812                 if (!score)
813                         goto out;
814         }
815         if (filename) {
816                 char *ebn = escaped_basename(filename);
817                 if (!ebn)
818                         goto out;
819                 select_clause = make_message("select %s from data ", score);
820                 free(score);
821                 where_clause = make_message( "where name = '%s' ", ebn);
822                 free(ebn);
823                 order = para_strdup("");
824                 goto write_query;
825         }
826         select_clause = para_strdup(with_path?
827                 "select concat(dir.dir, '/', dir.name) from data, dir "
828                 "where dir.name = data.name "
829                 :
830                 "select name from data where name is not NULL");
831         order = make_message("order by -(%s)", score);
832         free(score);
833         if (accept_opts && deny_opts) {
834                 where_clause = make_message("and ((%s) and not (%s)) ",
835                         accept_opts, deny_opts);
836                 goto write_query;
837         }
838         if (accept_opts && !deny_opts) {
839                 where_clause = make_message("and (%s) ", accept_opts);
840                 goto write_query;
841         }
842         if (!accept_opts && deny_opts) {
843                 where_clause = make_message("and not (%s) ", deny_opts);
844                 goto write_query;
845         }
846         where_clause = para_strdup("");
847 write_query:
848         query = make_message("%s %s %s", select_clause, where_clause, order);
849         free(order);
850         free(select_clause);
851         free(where_clause);
852 out:
853         if (accept_opts)
854                 free(accept_opts);
855         if (deny_opts)
856                 free(deny_opts);
857         if (result)
858                 mysql_free_result(result);
859         return query;
860 }
861
862
863
864 /*
865  * This is called from server and from some commands. Name must not be NULL
866  * Never returns NULL.
867  */
868 static char *get_selector_info(char *name)
869 {
870         char *meta, *atts, *info, *dir, *query, *stream;
871         void *result = NULL;
872         MYSQL_ROW row = NULL;
873
874         if (!name)
875                 return para_strdup("(none)");
876         stream = get_current_stream();
877         meta = get_meta(name, 1);
878         atts = get_atts(name, 0);
879         dir = get_dir(name);
880         /* get score */
881         query = get_query(stream, name, 0); /* FIXME: pass stream == NULL instead? */
882         if (!query)
883                 goto write;
884         result = get_result(query);
885         free(query);
886         if (result)
887                 row = mysql_fetch_row(result);
888 write:
889         info = make_message("dbinfo1:dir: %s\n"
890                 "dbinfo2:stream: %s, %s, score: %s\n"
891                 "dbinfo3:%s\n",
892                 dir? dir : "(not contained in table)",
893                 stream, meta, 
894                 (result && row && row[0])? row[0] : "(no score)",
895                 atts);
896         free(dir);
897         free(meta);
898         free(atts);
899         free(stream);
900         if (result)
901                 mysql_free_result(result);
902         return info;
903 }
904
905
906 /* might return NULL */
907 static char *get_current_audio_file(void)
908 {
909         char *name;
910         mmd_lock();
911         name = para_basename(mmd->filename);
912         mmd_unlock();
913         return name;
914 }
915
916 /* list attributes / print database info */
917 static int com_la_info(int fd, int argc, char *argv[])
918 {
919         char *name = NULL, *meta = NULL, *atts = NULL, *dir = NULL;
920         int ret, com_la = strcmp(argv[0], "info");
921
922         if (argc < 2) {
923                 ret = -E_GET_AUDIO_FILE;
924                 if (!(name = get_current_audio_file()))
925                         goto out;
926                 ret = send_va_buffer(fd, "%s\n", name);
927                 if (ret < 0)
928                         goto out;
929         } else {
930                 ret = -E_ESCAPE;
931                 if (!(name = escaped_basename(argv[1])))
932                         goto out;
933         }
934         meta = get_meta(name, 1);
935         atts = get_atts(name, 0);
936         dir = get_dir(name);
937         if (com_la)
938                 ret = send_va_buffer(fd, "%s\n", atts);
939         else
940                 ret = send_va_buffer(fd, "dir: %s\n" "%s\n" "attributes: %s\n",
941                         dir? dir : "(not contained in table)", meta, atts);
942 out:
943         free(meta);
944         free(atts);
945         free(dir);
946         free(name);
947         return ret;
948 }
949
950 /* list attributes */
951 int com_la(int fd, int argc, char *argv[])
952 {
953         return com_la_info(fd, argc, argv);
954 }
955
956 /* print database info */
957 int com_info(int fd, int argc, char *argv[])
958 {
959         return com_la_info(fd, argc, argv);
960 }
961
962 static int change_stream(const char *stream)
963 {
964         char *query;
965         int ret;
966         query = make_message("update streams set def='%s' "
967                 "where name = 'current_stream'", stream);
968         ret = real_query(query);
969         free(query);
970         return ret;
971 }
972
973 static int get_pic_id_by_name(char *name)
974 {
975         char *q, *ebn;
976         void *result = NULL;
977         long unsigned ret;
978         MYSQL_ROW row;
979
980         if (!(ebn = escaped_basename(name)))
981                 return -E_ESCAPE;
982         q = make_message("select pic_id from data where name = '%s'", ebn);
983         free(ebn);
984         result = get_result(q);
985         free(q);
986         if (!result)
987                 return -E_NORESULT;
988         row = mysql_fetch_row(result);
989         ret = -E_NOROW;
990         if (row && row[0])
991                 ret = atol(row[0]);
992         mysql_free_result(result);
993         return ret;
994 }
995
996 static int remove_entry(const char *name)
997 {
998         char *q, *ebn = escaped_basename(name);
999         int ret = -E_ESCAPE;
1000
1001         if (!ebn)
1002                 goto out;
1003         q = make_message("delete from data where name = '%s'", ebn);
1004         real_query(q); /* ignore errors */
1005         free(q);
1006         q = make_message("delete from dir where name = '%s'", ebn);
1007         real_query(q); /* ignore errors */
1008         free(q);
1009         ret = 1;
1010 out:
1011         free(ebn);
1012         return ret;
1013 }
1014
1015 static int add_entry(const char *name)
1016 {
1017         char *q, *dn, *ebn = NULL, *edn = NULL;
1018         int ret;
1019
1020         if (!name || !*name)
1021                 return -E_MYSQL_SYNTAX;
1022         ebn = escaped_basename(name);
1023         if (!ebn)
1024                 return -E_ESCAPE;
1025         ret = -E_MYSQL_SYNTAX;
1026         dn = para_dirname(name);
1027         if (!dn)
1028                 goto out;
1029         ret = -E_ESCAPE;
1030         edn = escape_str(dn);
1031         free(dn);
1032         if (!edn || !*edn)
1033                 goto out;
1034         q = make_message("insert into data (name, pic_id) values "
1035                         "('%s', '%s')", ebn, "1");
1036         ret = real_query(q);
1037 //      ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1038         free(q);
1039         if (ret < 0)
1040                 goto out;
1041         q = make_message("insert into dir (name, dir) values "
1042                         "('%s', '%s')", ebn, edn);
1043 //      ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1044         ret = real_query(q);
1045         free(q);
1046 out:
1047         if (ebn)
1048                 free(ebn);
1049         if (edn)
1050                 free(edn);
1051         return ret;
1052 }
1053
1054 /*
1055  * remove/add entries
1056  */
1057 static int com_rm_ne(__a_unused int fd, int argc, char *argv[])
1058 {
1059         int ne = !strcmp(argv[0], "ne");
1060         int i, ret;
1061         if (argc < 2)
1062                 return -E_MYSQL_SYNTAX;
1063         for (i = 1; i < argc; i++) {
1064                 ret = remove_entry(argv[i]);
1065                 if (ret < 0)
1066                         return ret;
1067                 if (!ne)
1068                         continue;
1069                 ret = add_entry(argv[i]);
1070                 if (ret < 0)
1071                         return ret;
1072         }
1073         return 1;
1074 }
1075
1076 /*
1077  * rm
1078  */
1079 int com_rm(int fd, int argc, char *argv[])
1080 {
1081         return com_rm_ne(fd, argc, argv);
1082 }
1083
1084 /*
1085  * ne
1086  */
1087 int com_ne(int fd, int argc, char *argv[])
1088 {
1089         return com_ne(fd, argc, argv);
1090 }
1091
1092 /*
1093  * mv: rename entry
1094  */
1095 int com_mv(__a_unused int fd, int argc, char *argv[])
1096 {
1097         char *q, *dn, *ebn1 = NULL, *ebn2 = NULL, *edn = NULL;
1098         int ret;
1099
1100         if (argc != 3)
1101                 return -E_MYSQL_SYNTAX;
1102         ret = -E_ESCAPE;
1103         ebn1 = escaped_basename(argv[1]);
1104         ebn2 = escaped_basename(argv[2]);
1105         if (!ebn1 || !ebn2 || !*ebn1 || !*ebn2)
1106                 goto out;
1107         ret = -E_MYSQL_SYNTAX;
1108         if (!strcmp(ebn1, ebn2))
1109                 goto update_dir;
1110         remove_entry(argv[2]); /* no need to escape, ignore error */
1111         q = make_message("update data set name = '%s' where name = '%s'",
1112                 ebn2, ebn1);
1113         ret = real_query(q);
1114         free(q);
1115         if (ret < 0)
1116                 goto out;
1117         ret = -E_AUDIO_FILE;
1118         if (!mysql_affected_rows(mysql_ptr))
1119                 goto out;
1120         q = make_message("update dir set name = '%s' where name = '%s'",
1121                 ebn2, ebn1);
1122         ret = real_query(q);
1123         free(q);
1124         if (ret < 0)
1125                 goto out;
1126 update_dir:
1127         ret = 1;
1128         dn = para_dirname(argv[2]);
1129         if (!dn)
1130                 goto out;
1131         ret = -E_ESCAPE;
1132         edn = escape_str(dn);
1133         free(dn);
1134         if (!edn)
1135                 goto out;
1136         ret = 1;
1137         if (!*edn)
1138                 goto out;
1139         q = make_message("update dir set dir = '%s' where name = '%s'",
1140                 edn, ebn2);
1141         ret = real_query(q);
1142         free(q);
1143 out:
1144         free(edn);
1145         free(ebn1);
1146         free(ebn2);
1147         return ret;
1148 }
1149
1150 /*
1151  * set field
1152  */
1153 static int com_set(__a_unused int fd, int argc, char *argv[])
1154 {
1155         char *q, *ebn;
1156         long unsigned id;
1157         int i, ret;
1158         const char *field = strcmp(argv[0], "picass")? "numplayed" : "pic_id";
1159
1160         if (argc < 3)
1161                 return -E_MYSQL_SYNTAX;
1162         id = atol(argv[1]);
1163         for (i = 2; i < argc; i++) {
1164                 ebn = escaped_basename(argv[i]);
1165                 if (!ebn)
1166                         return -E_ESCAPE;
1167                 q = make_message("update data set %s = %lu "
1168                                 "where name = '%s'", field, id, ebn);
1169                 free(ebn);
1170                 ret = real_query(q);
1171                 free(q);
1172                 if (ret < 0)
1173                         return ret;
1174         }
1175         return 1;
1176 }
1177
1178 /*
1179  * snp: set numplayed
1180  */
1181 int com_picass(int fd, int argc, char *argv[])
1182 {
1183         return com_set(fd, argc, argv);
1184 }
1185
1186 /*
1187  * snp: set numplayed
1188  */
1189 int com_snp(int fd, int argc, char *argv[])
1190 {
1191         return com_set(fd, argc, argv);
1192 }
1193
1194 /*
1195  * picch: change entry's name in pics table
1196  */
1197 int com_picch(__a_unused int fd, int argc, char *argv[])
1198 {
1199         int ret;
1200         long unsigned id;
1201         char *q, *tmp;
1202
1203         if (argc != 3)
1204                 return -E_MYSQL_SYNTAX;
1205         id = atol(argv[1]);
1206         ret = -E_ESCAPE;
1207         tmp = escape_str(argv[2]);
1208         if (!tmp)
1209                 return -E_ESCAPE;
1210         q = make_message("update pics set name = '%s' where id = %lu", tmp, id);
1211         free(tmp);
1212         ret = real_query(q);
1213         free(q);
1214         return ret;
1215 }
1216
1217 /*
1218  * piclist: print list of pics in db
1219  */
1220 int com_piclist(__a_unused int fd, int argc, __a_unused char *argv[])
1221 {
1222         void *result = NULL;
1223         MYSQL_ROW row;
1224         unsigned long *length;
1225         int ret;
1226
1227         if (argc != 1)
1228                 return -E_MYSQL_SYNTAX;
1229         result = get_result("select id,name,pic from pics order by id");
1230         if (!result)
1231                 return -E_NORESULT;
1232         while ((row = mysql_fetch_row(result))) {
1233                 length = mysql_fetch_lengths(result);
1234                 if (!row || !row[0] || !row[1] || !row[2])
1235                         continue;
1236                 ret = send_va_buffer(fd, "%s\t%lu\t%s\n", row[0], length[2], row[1]);
1237                 if (ret < 0)
1238                         goto out;
1239         }
1240         ret = 1;
1241 out:
1242         mysql_free_result(result);
1243         return ret;
1244 }
1245
1246 /*
1247  * picdel: delete picture from database
1248  */
1249 int com_picdel(int fd, int argc, char *argv[])
1250 {
1251         char *q;
1252         long unsigned id;
1253         my_ulonglong aff;
1254         int i, ret;
1255
1256         if (argc < 2)
1257                 return -E_MYSQL_SYNTAX;
1258         for (i = 1; i < argc; i++) {
1259                 id = atol(argv[i]);
1260                 q = make_message("delete from pics where id = %lu", id);
1261                 ret = real_query(q);
1262                 free(q);
1263                 if (ret < 0)
1264                         return ret;
1265                 aff = mysql_affected_rows(mysql_ptr);
1266                 if (!aff) {
1267                         ret = send_va_buffer(fd, "No such id: %lu\n", id);
1268                         if (ret < 0)
1269                                 return ret;
1270                         continue;
1271                 }
1272                 q = make_message("update data set pic_id = 1 where pic_id = %lu", id);
1273                 ret = real_query(q);
1274                 free(q);
1275         }
1276         return 1;
1277 }
1278 /*
1279  * pic: get picture by name or by number
1280  */
1281 int com_pic(int fd, int argc, char *argv[])
1282 {
1283         void *result = NULL;
1284         MYSQL_ROW row;
1285         unsigned long *length, id;
1286         int ret;
1287         char *q, *name = NULL;
1288
1289         if (argc < 2) {
1290                 ret = -E_GET_AUDIO_FILE;
1291                 name = get_current_audio_file();
1292         } else {
1293                 ret = -E_ESCAPE;
1294                 name = escaped_basename(argv[1]);
1295         }
1296         if (!name)
1297                 return ret;
1298         if (*name == '#')
1299                 id = atoi(name + 1);
1300         else
1301                 id = get_pic_id_by_name(name);
1302         free(name);
1303         if (id <= 0)
1304                 return id;
1305         q = make_message("select pic from pics where id = '%lu'", id);
1306         result = get_result(q);
1307         free(q);
1308         if (!result)
1309                 return -E_NORESULT;
1310         row = mysql_fetch_row(result);
1311         ret = -E_NOROW;
1312         if (!row || !row[0])
1313                 goto out;
1314         length = mysql_fetch_lengths(result);
1315         ret = send_bin_buffer(fd, row[0], *length);
1316 out:
1317         mysql_free_result(result);
1318         return ret;
1319 }
1320
1321 /* strdel */
1322 int com_strdel(__a_unused int fd, int argc, char *argv[])
1323 {
1324         char *q, *tmp;
1325         int ret;
1326
1327         if (argc < 2)
1328                 return -E_MYSQL_SYNTAX;
1329         tmp = escape_str(argv[1]);
1330         if (!tmp)
1331                 return -E_ESCAPE;
1332         q = make_message("delete from streams where name='%s'", tmp);
1333         free(tmp);
1334         ret = real_query(q);
1335         free(q);
1336         return ret;
1337 }
1338
1339 /*
1340  * ls
1341  */
1342 int com_ls(int fd, int argc, char *argv[])
1343 {
1344         char *q;
1345         void *result;
1346         int ret;
1347         unsigned int num_rows;
1348
1349         if (argc > 2)
1350                 return -E_MYSQL_SYNTAX;
1351         if (argc > 1) {
1352                 char *tmp = escape_str(argv[1]);
1353                 if (!tmp)
1354                         return -E_ESCAPE;
1355                 q = make_message("select name from data where name like '%s'",
1356                         tmp);
1357                 free(tmp);
1358         } else
1359                 q = para_strdup("select name from data");
1360         result = get_result(q);
1361         free(q);
1362         if (!result)
1363                 return -E_NORESULT;
1364         num_rows = mysql_num_rows(result);
1365         ret = 1;
1366         if (num_rows)
1367                 ret = print_results(fd, result, 0, 0, num_rows - 1, 0);
1368         mysql_free_result(result);
1369         return ret;
1370 }
1371
1372 /*
1373  * summary
1374  */
1375 int com_summary(__a_unused int fd, int argc, __a_unused char *argv[])
1376 {
1377         MYSQL_ROW row;
1378         MYSQL_ROW row2;
1379         void *result;
1380         void *result2 = NULL;
1381         const char *fmt = "select count(name) from data where %s='1'";
1382         int ret = -E_NORESULT;
1383
1384         if (argc != 1)
1385                 return -E_MYSQL_SYNTAX;
1386         result = get_all_attributes();
1387         if (!result)
1388                 goto out;
1389         while ((row = mysql_fetch_row(result))) {
1390                 char *buf;
1391
1392                 ret = -E_NOROW;
1393                 if (!row[0])
1394                         goto out;
1395                 ret = -E_NORESULT;
1396                 buf = make_message(fmt, row[0]);
1397                 result2 = get_result(buf);
1398                 free(buf);
1399                 if (!result2)
1400                         goto out;
1401                 ret = -E_NOROW;
1402                 row2 = mysql_fetch_row(result2);
1403                 if (!row2 || !row2[0])
1404                         goto out;
1405                 ret = send_va_buffer(fd, "%s\t%s\n", row[0], row2[0]);
1406                 if (ret < 0)
1407                         goto out;
1408         }
1409         ret = 1;
1410 out:
1411         if (result2)
1412                 mysql_free_result(result2);
1413         if (result)
1414                 mysql_free_result(result);
1415         return ret;
1416 }
1417
1418 static int get_numplayed(char *name)
1419 {
1420         void *result;
1421         MYSQL_ROW row;
1422         const char *fmt = "select numplayed from data where name = '%s'";
1423         char *buf = make_message(fmt, name);
1424         int ret = -E_NORESULT;
1425
1426         result = get_result(buf);
1427         free(buf);
1428         if (!result)
1429                 goto out;
1430         ret = -E_NOROW;
1431         row = mysql_fetch_row(result);
1432         if (!row || !row[0])
1433                 goto out;
1434         ret = atoi(row[0]);
1435 out:
1436         if (result)
1437                 mysql_free_result(result);
1438         return ret;
1439 }
1440
1441 static int update_audio_file(char *name)
1442 {
1443         int ret;
1444         const char *fmt1 = "update data set lastplayed = now() where name = '%s'";
1445         const char *fmt2 = "update data set numplayed = %i where name = '%s'";
1446         char *q;
1447         char *ebn = escaped_basename(name);
1448
1449         ret = -E_ESCAPE;
1450         if (!ebn)
1451                 goto out;
1452         q = make_message(fmt1, ebn);
1453         ret = real_query(q);
1454         free(q);
1455         if (ret < 0)
1456                 goto out;
1457         ret = get_numplayed(ebn);
1458         if (ret < 0)
1459                 goto out;
1460         q = make_message(fmt2, ret + 1, ebn);
1461         ret = real_query(q);
1462         free(q);
1463 out:
1464         free(ebn);
1465         return ret;
1466 }
1467
1468 /* If called as child, mmd_lock must be held */
1469 static void update_mmd(char *info)
1470 {
1471         PARA_DEBUG_LOG("%s", "updating shared memory area\n");
1472         strncpy(mmd->selector_info, info, MMD_INFO_SIZE - 1);
1473         mmd->selector_info[MMD_INFO_SIZE - 1] = '\0';
1474 }
1475
1476 static void update_audio_file_server_handler(char *name)
1477 {
1478         char *info;
1479         info = get_selector_info(name);
1480         update_mmd(info);
1481         free(info);
1482         update_audio_file(name);
1483 }
1484
1485 int com_us(__a_unused int fd, int argc, char *argv[])
1486 {
1487         char *tmp;
1488         int ret;
1489
1490         if (argc != 2)
1491                 return -E_MYSQL_SYNTAX;
1492         tmp = escape_str(argv[1]);
1493         if (!tmp)
1494                 return -E_ESCAPE;
1495         ret = update_audio_file(argv[1]);
1496         free(tmp);
1497         return ret;
1498 }
1499
1500 static void refresh_selector_info(void)
1501 {
1502         char *name = get_current_audio_file();
1503         char *info;
1504
1505         if (!name)
1506                 return;
1507         info = get_selector_info(name);
1508         free(name);
1509         mmd_lock();
1510         update_mmd(info);
1511         mmd_unlock();
1512         free(info);
1513 }
1514
1515 /* select previous / next stream */
1516 static int com_ps_ns(__a_unused int fd, int argc, char *argv[])
1517 {
1518         char *query, *stream = get_current_stream();
1519         void *result = get_result("select name from streams");
1520         MYSQL_ROW row;
1521         int match = -1, ret, i;
1522         unsigned int num_rows;
1523
1524         if (argc != 1)
1525                 return -E_MYSQL_SYNTAX;
1526         ret = -E_NORESULT;
1527         if (!result)
1528                 goto out;
1529         num_rows = mysql_num_rows(result);
1530         ret = -E_EMPTY_RESULT;
1531         if (num_rows < 2)
1532                 goto out;
1533         ret = -E_NOROW;
1534         for (i = 0; i < num_rows; i++) {
1535                 row = mysql_fetch_row(result);
1536                 if (!row || !row[0])
1537                         goto out;
1538                 if (!strcmp(row[0], "current_stream"))
1539                         continue;
1540                 if (!strcmp(row[0], stream)) {
1541                         match = i;
1542                         break;
1543                 }
1544         }
1545         ret = -E_NO_STREAM;
1546         if (match < 0)
1547                 goto out;
1548         if (!strcmp(argv[0], "ps"))
1549                 i = match > 0? match - 1 : num_rows - 1;
1550         else
1551                 i = match < num_rows - 1? match + 1 : 0;
1552         ret = -E_NOROW;
1553         mysql_data_seek(result, i);
1554         row = mysql_fetch_row(result);
1555         if (!row || !row[0])
1556                 goto out;
1557         if (!strcmp(row[0], "current_stream")) {
1558                 if (!strcmp(argv[0], "ps")) {
1559                         i = match - 2;
1560                         i = i < 0? i + num_rows : i;
1561                 } else {
1562                         i = match + 2;
1563                         i = i > num_rows - 1? i - num_rows : i;
1564                 }
1565                 mysql_data_seek(result, i);
1566                 row = mysql_fetch_row(result);
1567                 if (!row || !row[0])
1568                         goto out;
1569         }
1570         query = make_message("update streams set def='%s' where name = "
1571                 "'current_stream'", row[0]);
1572         ret = real_query(query);
1573         free(query);
1574         refresh_selector_info();
1575 out:
1576         free(stream);
1577         if (result)
1578                 mysql_free_result(result);
1579         return ret;
1580 }
1581
1582 /* select previous stream */
1583 int com_ps(int fd, int argc, char *argv[])
1584 {
1585         return com_ps_ns(fd, argc, argv);
1586 }
1587
1588 /* select next stream */
1589 int com_ns(int fd, int argc, char *argv[])
1590 {
1591         return com_ps_ns(fd, argc, argv);
1592 }
1593
1594 /* streams */
1595 int com_streams(int fd, int argc, __a_unused char *argv[])
1596 {
1597         unsigned int num_rows;
1598         int i, ret = -E_NORESULT;
1599         void *result;
1600         MYSQL_ROW row;
1601
1602         if (argc > 1 && strcmp(argv[1], "current_stream"))
1603                 return -E_MYSQL_SYNTAX;
1604         if (argc > 1) {
1605                 char *cs = get_current_stream();
1606                 ret = send_va_buffer(fd, "%s\n", cs);
1607                 free(cs);
1608                 return ret;
1609         }
1610         result = get_result("select name from streams");
1611         if (!result)
1612                 goto out;
1613         num_rows = mysql_num_rows(result);
1614         ret = 1;
1615         if (!num_rows)
1616                 goto out;
1617         ret = -E_NOROW;
1618         for (i = 0; i < num_rows; i++) {
1619                 row = mysql_fetch_row(result);
1620                 if (!row || !row[0])
1621                         goto out;
1622                 if (strcmp(row[0], "current_stream"))
1623                         send_va_buffer(fd, "%s\n", row[0]);
1624         }
1625         ret = 1;
1626 out:
1627         if (result)
1628                 mysql_free_result(result);
1629         return ret;
1630 }
1631
1632 /* query stream definition */
1633 int com_strq(int fd, int argc, char *argv[])
1634 {
1635         MYSQL_ROW row;
1636         char *query, *name;
1637         void *result;
1638         int ret;
1639
1640         if (argc < 2) {
1641                 ret = -E_GET_STREAM;
1642                 name = get_current_stream();
1643         } else {
1644                 ret = -E_ESCAPE;
1645                 name = escaped_basename(argv[1]);
1646         }
1647         if (!name)
1648                 return ret;
1649         ret = -E_NORESULT;
1650         query = make_message("select def from streams where name='%s'", name);
1651         free(name);
1652         result = get_result(query);
1653         free(query);
1654         if (!result)
1655                 goto out;
1656         ret = -E_NOROW;
1657         row = mysql_fetch_row(result);
1658         if (!row || !row[0])
1659                 goto out;
1660         /* no '\n' needed */
1661         ret = send_buffer(fd, row[0]);
1662 out:
1663         if (result)
1664                 mysql_free_result(result);
1665         return ret;
1666 }
1667
1668 /* change stream / change stream and play */
1669 static int com_cs_csp(int fd, int argc, char *argv[])
1670 {
1671         int ret, stream_change;
1672         char *query, *stream = NULL;
1673         char *old_stream = get_current_stream();
1674         int csp = !strcmp(argv[0], "csp");
1675
1676         ret = -E_MYSQL_SYNTAX;
1677         if (argc > 2)
1678                 goto out;
1679         if (argc == 1) {
1680                 if (csp)
1681                         goto out;
1682                 ret = send_va_buffer(fd, "%s\n", old_stream);
1683                 goto out;
1684         }
1685         ret = -E_GET_QUERY;
1686         /* test if stream is valid, no need to escape argv[1] */
1687         query = get_query(argv[1], NULL, 0);
1688         if (!query)
1689                 goto out;
1690         free(query);
1691         /* stream is ok */
1692         stream = escape_str(argv[1]);
1693         if (!stream)
1694                 goto out;
1695         stream_change = strcmp(stream, old_stream);
1696         if (stream_change) {
1697                 ret = change_stream(stream);
1698                 if (ret < 0)
1699                         goto out;
1700                 refresh_selector_info();
1701         }
1702         if (csp) {
1703                 mmd_lock();
1704                 mmd->new_vss_status_flags |= VSS_PLAYING;
1705                 if (stream_change)
1706                         mmd->new_vss_status_flags |= VSS_NEXT;
1707                 mmd_unlock();
1708         }
1709         ret = 1;
1710 out:
1711         free(old_stream);
1712         free(stream);
1713         return ret;
1714 }
1715
1716 /* change stream */
1717 int com_cs(int fd, int argc, char *argv[])
1718 {
1719         return com_cs_csp(fd, argc, argv);
1720 }
1721
1722 /* change stream and play */
1723 int com_csp(int fd, int argc, char *argv[])
1724 {
1725         return com_cs_csp(fd, argc, argv);
1726 }
1727
1728 /* score list / skip */
1729 static int com_sl_skip(int fd, int argc, char *argv[])
1730 {
1731         void *result = NULL;
1732         MYSQL_ROW row;
1733         int ret, i, skip = !strcmp(argv[0], "skip");
1734         char *query, *stream, *tmp;
1735         unsigned int num_rows, num;
1736
1737         if (argc < 2)
1738                 return -E_MYSQL_SYNTAX;
1739         num = atoi(argv[1]);
1740         if (!num)
1741                 return -E_MYSQL_SYNTAX;
1742         if (argc == 2) {
1743                 stream = get_current_stream();
1744                 if (!stream)
1745                         return -E_GET_STREAM;
1746         } else {
1747                 stream = escape_str(argv[2]);
1748                 if (!stream)
1749                         return -E_ESCAPE;
1750         }
1751         tmp = get_query(stream, NULL, 0);
1752         free(stream);
1753         if (!tmp)
1754                 return -E_GET_QUERY;
1755         query = make_message("%s limit %d", tmp, num);
1756         free(tmp);
1757         ret = -E_NORESULT;
1758         result = get_result(query);
1759         free(query);
1760         if (!result)
1761                 goto out;
1762         ret = -E_EMPTY_RESULT;
1763         num_rows = mysql_num_rows(result);
1764         if (!num_rows)
1765                 goto out;
1766         for (i = 0; i < num_rows && i < num; i++) {
1767                 row = mysql_fetch_row(result);
1768                 if (skip) {
1769                         send_va_buffer(fd, "Skipping %s\n", row[0]);
1770                         update_audio_file(row[0]);
1771                 } else
1772                         send_va_buffer(fd, "%s\n", row[0]? row[0]: "BUG");
1773         }
1774         ret = 1;
1775 out:
1776         if (result)
1777                 mysql_free_result(result);
1778         return ret;
1779 }
1780
1781 /* score list */
1782 int com_sl(int fd, int argc, char *argv[])
1783 {
1784         return com_sl_skip(fd, argc, argv);
1785 }
1786
1787 /* skip */
1788 int com_skip(int fd, int argc, char *argv[])
1789 {
1790         return com_sl_skip(fd, argc, argv);
1791 }
1792
1793 /*
1794  * update attributes of name
1795  */
1796 static int update_atts(int fd, char *name, char *atts)
1797 {
1798         int ret;
1799         char *ebn, *q, *old, *new = NULL;
1800
1801         if (!mysql_ptr)
1802                 return -E_NOTCONN;
1803         ebn = escaped_basename(name);
1804         if (!ebn)
1805                 return -E_ESCAPE;
1806         q = make_message("update data set %s where name = '%s'", atts, ebn);
1807         old = get_atts(ebn, 0);
1808         send_va_buffer(fd, "old: %s\n", old);
1809         free(old);
1810         ret = real_query(q);
1811         free(q);
1812         if (ret < 0)
1813                 goto out;
1814         new = get_atts(ebn, 0);
1815         ret = send_va_buffer(fd, "new: %s\n", new);
1816         free(new);
1817 out:
1818         free(ebn);
1819         return ret;
1820 }
1821
1822 /*
1823  * set attributes
1824  */
1825 int com_sa(int fd, int argc, char *argv[])
1826 {
1827         int i, ret;
1828         char *atts = NULL, *name;
1829
1830         if (argc < 2)
1831                 return -E_MYSQL_SYNTAX;
1832         for (i = 1; i < argc; i++) {
1833                 int unset = 0;
1834                 char *esc, *tmp, *p =argv[i];
1835                 int len = strlen(p);
1836
1837                 if (!len)
1838                         continue;
1839                 switch (p[len - 1]) {
1840                         case '+':
1841                                 unset = 0;
1842                                 break;
1843                         case '-':
1844                                 unset = 1;
1845                                 break;
1846                         default:
1847                                 goto no_more_atts;
1848                 }
1849                 p[len - 1] = '\0';
1850                 esc = escape_str(p);
1851                 if (!esc)
1852                         return -E_ESCAPE;
1853                 tmp = make_message("%s%s='%s'", atts? "," : "", esc,
1854                         unset? "0" : "1");
1855                 free(esc);
1856                 atts = para_strcat(atts, tmp);
1857                 free(tmp);
1858         }
1859 no_more_atts:
1860         if (!atts)
1861                 return -E_NOATTS;
1862         if (i >= argc) { /* no name given, use current af */
1863                 ret = -E_GET_AUDIO_FILE;
1864                 if (!(name = get_current_audio_file()))
1865                         goto out;
1866                 ret = update_atts(fd, name, atts);
1867                 free(name);
1868         } else {
1869                 ret = 1;
1870                 for (; argv[i] && ret >= 0; i++)
1871                         ret = update_atts(fd, argv[i], atts);
1872         }
1873         refresh_selector_info();
1874 out:
1875         free(atts);
1876         return ret;
1877 }
1878
1879 /*
1880  * copy attributes
1881  */
1882 int com_cam(int fd, int argc, char *argv[])
1883 {
1884         char *name = NULL, *meta = NULL, *atts = NULL;
1885         int i, ret;
1886
1887         if (argc < 3)
1888                 return -E_MYSQL_SYNTAX;
1889         if (!(name = escaped_basename(argv[1])))
1890                 return -E_ESCAPE;
1891         ret = -E_NOATTS;
1892         if (!(atts = get_atts(name, 1)))
1893                 goto out;
1894         ret = -E_META;
1895         if (!(meta = get_meta(name, 0)))
1896                 goto out;
1897         for (i = 2; i < argc; i++) {
1898                 char *ebn, *q;
1899                 ret = -E_ESCAPE;
1900                 if (!(ebn = escaped_basename(argv[i])))
1901                         goto out;
1902                 ret = send_va_buffer(fd, "updating %s\n", ebn);
1903                 if (ret < 0) {
1904                         free(ebn);
1905                         goto out;
1906                 }
1907                 q = make_message("update data set %s where name = '%s'",
1908                         meta, ebn);
1909                 if ((ret = update_atts(fd, ebn, atts)) >= 0)
1910                         ret = real_query(q);
1911                 free(ebn);
1912                 free(q);
1913                 if (ret < 0)
1914                         goto out;
1915         }
1916         ret = 1;
1917 out:
1918         if (name)
1919                 free(name);
1920         if (meta)
1921                 free(meta);
1922         if (atts)
1923                 free(atts);
1924         return ret;
1925 }
1926
1927 /*
1928  * verify / clean
1929  */
1930 static int com_vrfy_clean(int fd, int argc, __a_unused char *argv[])
1931 {
1932         char *query;
1933         int ret, vrfy_mode = strcmp(argv[0], "clean");
1934         void *result = NULL;
1935         unsigned int num_rows;
1936         MYSQL_ROW row;
1937         char *escaped_name;
1938
1939         if (argc != 1)
1940                 return -E_MYSQL_SYNTAX;
1941         ret = -E_NORESULT;
1942         result = get_result("select data.name from data left join dir on "
1943                 "dir.name = data.name where dir.name is NULL");
1944         if (!result)
1945                 goto out;
1946         num_rows = mysql_num_rows(result);
1947         if (!num_rows) {
1948                 ret = send_buffer(fd, "No invalid entries\n");
1949                 goto out;
1950         }
1951         if (vrfy_mode) {
1952                 send_va_buffer(fd, "found %i invalid entr%s\n", num_rows,
1953                         num_rows == 1? "y" : "ies");
1954                 ret = print_results(fd, result, 0, 0, num_rows - 1, 0);
1955                 goto out;
1956         }
1957         while ((row = mysql_fetch_row(result))) {
1958                 ret = -E_NOROW;
1959                 if (!row[0])
1960                         goto out;
1961                 ret = -E_ESCAPE;
1962                 escaped_name = escape_str(row[0]);
1963                 if (!escaped_name)
1964                         goto out;
1965                 send_va_buffer(fd, "deleting %s\n", escaped_name);
1966                 query = make_message("delete from data where name = '%s'",
1967                         escaped_name);
1968                 ret = real_query(query);
1969                 free(query);
1970                 if (ret < 0)
1971                         goto out;
1972         }
1973
1974 out:
1975         if (result)
1976                 mysql_free_result(result);
1977         return ret;
1978 }
1979
1980 /*
1981  * verify
1982  */
1983 int com_vrfy(int fd, int argc, char **argv)
1984 {
1985         return com_vrfy_clean(fd, argc, argv);
1986 }
1987
1988 /*
1989  * clean
1990  */
1991 int com_clean(int fd, int argc, char **argv)
1992 {
1993         return com_vrfy_clean(fd, argc, argv);
1994 }
1995
1996 static FILE *out_file;
1997
1998 static int mysql_write_tmp_file(const char *dir, const char *name)
1999 {
2000         int ret = -E_TMPFILE;
2001         char *msg = make_message("%s\t%s\n", dir, name);
2002         if (fputs(msg, out_file) != EOF)
2003                 ret = 1;
2004         free(msg);
2005         return ret;
2006 }
2007
2008 /*
2009  * update database
2010  */
2011 int com_upd(int fd, int argc, __a_unused char *argv[])
2012 {
2013         char *tempname = NULL, *query = NULL;
2014         int ret, out_fd = -1, num = 0;
2015         void *result = NULL;
2016         unsigned int num_rows;
2017         MYSQL_ROW row;
2018
2019         if (argc != 1)
2020                 return -E_MYSQL_SYNTAX;
2021         out_file = NULL;
2022         tempname = para_strdup("/tmp/mysql.tmp.XXXXXX");
2023         ret = para_mkstemp(tempname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
2024         if (ret < 0)
2025                 goto out;
2026         out_fd = ret;
2027         out_file = fdopen(out_fd, "w");
2028         if (!out_file) {
2029                 close(out_fd);
2030                 goto out;
2031         }
2032         if (find_audio_files(conf.mysql_audio_file_dir_arg, mysql_write_tmp_file) < 0)
2033                 goto out;
2034         num = ftell(out_file);
2035         /*
2036          * we have to make sure the file hit the disk before we call
2037          * real_query
2038          */
2039         fclose(out_file);
2040         out_file = NULL;
2041         PARA_DEBUG_LOG("wrote tempfile %s (%d bytes)\n", tempname, num);
2042         if (!num)
2043                 goto out;
2044         if ((ret = real_query("delete from dir")) < 0)
2045                 goto out;
2046         query = make_message("load data infile '%s' ignore into table dir "
2047                 "fields terminated by '\t' lines terminated by '\n' "
2048                 "(dir, name)", tempname);
2049         ret = real_query(query);
2050         free(query);
2051         if (ret < 0)
2052                 goto out;
2053         result = get_result("select dir.name from dir left join data on "
2054                 "data.name = dir.name where data.name is NULL");
2055         ret = -E_NORESULT;
2056         if (!result)
2057                 goto out;
2058         num_rows = mysql_num_rows(result);
2059         if (!num_rows) {
2060                 ret = send_buffer(fd, "no new entries\n");
2061                 goto out;
2062         }
2063         while ((row = mysql_fetch_row(result))) {
2064                 char *erow;
2065                 ret = -E_NOROW;
2066                 if (!row[0])
2067                         goto out;
2068                 send_va_buffer(fd, "new entry: %s\n", row[0]);
2069                 erow = escape_str(row[0]);
2070                 if (!erow)
2071                         goto out;
2072                 query = make_message("insert into data (name, pic_id) values "
2073                         "('%s','%s')", erow, "1");
2074                 free(erow);
2075                 ret = real_query(query);
2076                 free(query);
2077                 if (ret < 0)
2078                         goto out;
2079         }
2080         ret = 1;
2081 out:
2082         if (out_fd >= 0)
2083                 unlink(tempname);
2084         free(tempname);
2085         if (out_file)
2086                 fclose(out_file);
2087         if (result)
2088                 mysql_free_result(result);
2089         return ret;
2090 }
2091
2092 static char **server_get_audio_file_list(unsigned int num)
2093 {
2094         char **list = para_malloc((num + 1) * sizeof(char *));
2095         char *tmp, *query, *stream = get_current_stream();
2096         void *result = NULL;
2097         unsigned int num_rows;
2098         int i = 0;
2099         MYSQL_ROW row;
2100
2101         tmp = get_query(stream, NULL, 1);
2102         free(stream);
2103         if (!tmp)
2104                 goto err_out;
2105         query = make_message("%s limit %d", tmp, num);
2106         free(tmp);
2107         result = get_result(query);
2108         free(query);
2109         if (!result)
2110                 goto err_out;
2111         num_rows = mysql_num_rows(result);
2112         if (!num_rows)
2113                 goto err_out;
2114         for (i = 0; i < num_rows && i < num; i++) {
2115                 row = mysql_fetch_row(result);
2116                 if (!row || !row[0])
2117                         goto err_out;
2118                 list[i] = para_strdup(row[0]);
2119         }
2120         list[i] = NULL;
2121         goto success;
2122 err_out:
2123         while (i > 0) {
2124                 i--;
2125                 free(list[i]);
2126         }
2127         free(list);
2128         list = NULL;
2129 success:
2130         if (result)
2131                 mysql_free_result(result);
2132         return list;
2133 }
2134
2135 /*
2136  * connect to mysql server, return mysql pointer on success, -E_NOTCONN
2137  * on errors. Called from parent on startup and also from com_cdb().
2138  */
2139 static int init_mysql_server(void)
2140 {
2141         char *u = conf.mysql_user_arg? conf.mysql_user_arg : para_logname();
2142
2143         mysql_ptr = mysql_init(NULL);
2144         if (!mysql_ptr) {
2145                 PARA_CRIT_LOG("%s", "mysql init error\n");
2146                 return -E_NOTCONN;
2147         }
2148         PARA_DEBUG_LOG("connecting: %s@%s:%d\n", u, conf.mysql_host_arg,
2149                 conf.mysql_port_arg);
2150         if (!conf.mysql_user_arg)
2151                 free(u);
2152         /*
2153          * If host is NULL a connection to the local host is assumed,
2154          * If user is NULL, the current user is assumed
2155          */
2156         if (!(mysql_ptr = mysql_real_connect(mysql_ptr,
2157                         conf.mysql_host_arg,
2158                         conf.mysql_user_arg,
2159                         conf.mysql_passwd_arg,
2160                         conf.mysql_database_arg,
2161                         conf.mysql_port_arg, NULL, 0))) {
2162                 PARA_CRIT_LOG("%s", "connect error\n");
2163                 return -E_NOTCONN;
2164         }
2165         PARA_INFO_LOG("%s", "success\n");
2166         return 1;
2167 }
2168
2169 /* mmd lock must be held */
2170 static void write_msg2mmd(int success)
2171 {
2172         sprintf(mmd->selector_info, "dbinfo1:%s\ndbinfo2:mysql-%s\ndbinfo3:\n",
2173                 success < 0? PARA_STRERROR(-success) :
2174                         "successfully connected to mysql server",
2175                 success < 0? "" : mysql_get_server_info(mysql_ptr));
2176 }
2177
2178 /* create database */
2179 int com_cdb(int fd, int argc, char *argv[])
2180 {
2181         char *query;
2182         int ret;
2183
2184         if (mysql_ptr) {
2185                 PARA_INFO_LOG("%s", "closing database\n");
2186                 mysql_close(mysql_ptr);
2187         }
2188         /* dont use any database */
2189         conf.mysql_database_arg = NULL; /* leak? */
2190         ret = -E_MYSQL_INIT;
2191         if (init_mysql_server() < 0 || !mysql_ptr)
2192                 goto out;
2193         if (argc < 2)
2194                 conf.mysql_database_arg = para_strdup("paraslash");
2195         else {
2196                 ret = -E_ESCAPE;
2197                 conf.mysql_database_arg = escape_str(argv[1]);
2198                 if (!conf.mysql_database_arg)
2199                         goto out;
2200         }
2201         query = make_message("create database %s", conf.mysql_database_arg);
2202         ret = real_query(query);
2203         free(query);
2204         if (ret < 0)
2205                 goto out;
2206         /* reconnect with database just created */
2207         mysql_close(mysql_ptr);
2208         ret = -E_MYSQL_INIT;
2209         if (init_mysql_server() < 0 || !mysql_ptr)
2210                 goto out;
2211         mmd_lock();
2212         write_msg2mmd(1);
2213         mmd_unlock();
2214         ret = -E_QFAILED;
2215         if (real_query("create table data (name varchar(255) binary not null "
2216                         "primary key, "
2217                         "lastplayed datetime not null default "
2218                                 "'1970-01-01', "
2219                         "numplayed int not null default 0, "
2220                         "pic_id bigint unsigned not null default 1)") < 0)
2221                 goto out;
2222         if (real_query("create table dir (name varchar(255) binary not null "
2223                         "primary key, dir varchar(255) default null)") < 0)
2224                 goto out;
2225         if (real_query("create table pics ("
2226                         "id bigint(20) unsigned not null primary key "
2227                         "auto_increment, "
2228                         "name varchar(255) binary not null, "
2229                         "pic mediumblob not null)") < 0)
2230                 goto out;
2231         if (real_query("create table streams ("
2232                         "name varchar(255) binary not null primary key, "
2233                         "def blob not null)") < 0)
2234                 goto out;
2235         if (real_query("insert into streams (name, def) values "
2236                         "('current_stream', '(none)')") < 0)
2237                 goto out;
2238         ret = send_va_buffer(fd, "successfully created database %s\n",
2239                 conf.mysql_database_arg);
2240 out:
2241         return ret;
2242 }
2243
2244 static void shutdown_connection(void)
2245 {
2246         if (mysql_ptr) {
2247                 PARA_NOTICE_LOG("%s", "shutting down mysql connection\n");
2248                 mysql_close(mysql_ptr);
2249                 mysql_ptr = NULL;
2250         }
2251 }
2252
2253 /**
2254  * the init function of the mysql-based audio file selector
2255  *
2256  * \param db pointer to the struct to initialize
2257  *
2258  * Check the command line options and initialize all function pointers of \a
2259  * db.  Connect to the mysql server and initialize the info string.
2260  *
2261  * \return This function returns success even if it could not connect
2262  * to the mysql server. This is because the connect is expected to fail
2263  * if there the paraslash database is not yet created. This gives the
2264  * user a chance to send the "cdb" to create the database.
2265  *
2266  * \sa struct audio_file_selector, misc_meta_data::selector_info,
2267  * random_selector.c
2268  */
2269 int mysql_selector_init(struct audio_file_selector *db)
2270 {
2271         int ret;
2272
2273         if (!conf.mysql_passwd_given)
2274                 return -E_NO_MYSQL_PASSWD;
2275         if (!conf.mysql_audio_file_dir_given)
2276                 return -E_NO_AF_DIR;
2277         db->name = "mysql";
2278         db->cmd_list = mysql_selector_cmds;
2279         db->get_audio_file_list = server_get_audio_file_list;
2280         db->update_audio_file = update_audio_file_server_handler;
2281         db->shutdown = shutdown_connection;
2282         ret = init_mysql_server();
2283         if (ret < 0)
2284                 PARA_WARNING_LOG("%s\n", PARA_STRERROR(-ret));
2285         write_msg2mmd(ret);
2286         return 1;       /* return success even if connect failed to give the
2287                          * user the chance to exec com_cdb
2288                          */
2289 }