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