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