2 * Copyright (C) 1999-2007 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file mysql_selector.c para_server's mysql-based audio file selector */
9 /** \cond some internal constants */
10 #define MEDIUM_BLOB_SIZE 16777220 /* (2**24 + 4) */
11 #define BLOB_SIZE 65539 /* (2**16 + 3) */
15 #include "server.cmdline.h"
19 #include "afs_common.h"
20 #include <mysql/mysql.h>
21 #include <mysql/mysql_version.h>
26 #include "user_list.h"
27 #include "mysql_selector_command_list.h"
30 /** pointer to the shared memory area */
31 extern struct misc_meta_data *mmd;
33 static void *mysql_ptr = NULL;
34 static int mysql_lock;
37 * contains name/replacement pairs used by s_a_r_list()
42 /** the name of the macro */
44 /** the replacement text */
45 const char *replacement;
48 static const struct para_macro mysql_macro_list[] = {
50 .replacement = "(data.%s != '1')"
53 .replacement = "(data.%s = '1')"
56 .replacement = "%sdata.Pic_Id"
59 .replacement = "(data.name like '%s')"
62 .replacement = "%sFLOOR((UNIX_TIMESTAMP(now())"
63 "-UNIX_TIMESTAMP(data.Lastplayed))/60)"
66 .replacement = "%sdata.Numplayed"
73 * Simple search and replace routine.
75 * \param src Source String.
76 * \param macro_name The name of the macro.
77 * \param replacement The replacement format string.
79 * In \p src, replace each occurence of \p macro_name(arg) by the string
80 * determined by the \p replacement format string. \p replacement may (but
81 * needs not) contain a single string conversion specifier (%s) which gets
84 * \return A string in which all matches in \p src are replaced, or \p NULL if
85 * an error was encountered. Caller must free the result.
89 __must_check __malloc static char *s_a_r(const char *src, const char* macro_name,
90 const char *replacement)
97 const char *bufptr = src;
99 if (!macro_name || !replacement || !src)
100 return para_strdup(src);
101 if (regcomp(&preg, macro_name, 0) != 0)
103 while (regexec(&preg, bufptr, nmatch, pmatch, eflags)
105 char *tmp, *arg, *o_bracket, *c_bracket;
107 o_bracket = strchr(bufptr + pmatch[0].rm_so, '(');
108 c_bracket = o_bracket? strchr(o_bracket, ')') : NULL;
111 tmp = para_strdup(bufptr);
112 tmp[pmatch[0].rm_so] = '\0';
113 dest = para_strcat(dest, tmp);
116 arg = para_strdup(o_bracket + 1);
117 arg[c_bracket - o_bracket - 1] = '\0';
118 tmp = make_message(replacement, arg);
120 dest = para_strcat(dest, tmp);
125 dest = para_strcat(dest, bufptr);
126 // PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
133 * replace a string according to a list of macros
135 * \param macro_list the array containing a macro/replacement pairs.
136 * \param src the source string
138 * This function just calls s_a_r() for each element of \p macro_list.
140 * \return \p NULL if one of the underlying calls to \p s_a_r returned \p NULL.
141 * Otherwise the completely expanded version of \p src is returned.
143 __must_check __malloc static char *s_a_r_list(const struct para_macro *macro_list,
146 const struct para_macro *mp = macro_list;
147 char *ret = NULL, *tmp = para_strdup(src);
150 ret = s_a_r(tmp, mp->name, mp->replacement);
152 if (!ret) /* syntax error */
157 //PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
161 static int lockless_real_query(const char *query)
165 PARA_DEBUG_LOG("%s\n", query);
166 if (mysql_real_query(mysql_ptr, query, strlen(query))) {
167 PARA_ERROR_LOG("real_query error (%s)\n",
168 mysql_error(mysql_ptr));
174 static int real_query(const char *query)
178 mutex_lock(mysql_lock);
179 ret = lockless_real_query(query);
180 mutex_unlock(mysql_lock);
185 * Use open connection given by mysql_ptr to query server. Returns a
186 * result pointer on succes and NULL on errors
188 static struct MYSQL_RES *get_result(const char *query)
192 mutex_lock(mysql_lock);
193 if (lockless_real_query(query) < 0)
195 result = mysql_store_result(mysql_ptr);
197 PARA_ERROR_LOG("%s", "store_result error\n");
199 mutex_unlock(mysql_lock);
203 * write input from fd to dynamically allocated char array,
204 * but maximal max_size byte. Return size.
206 static int fd2buf(int fd, char **buf_ptr, size_t max_size)
208 const size_t chunk_size = 1024;
210 char *buf = para_malloc(size * sizeof(char)), *p = buf;
213 while ((ret = recv_bin_buffer(fd, p, chunk_size)) > 0) {
215 if ((p - buf) + chunk_size >= size) {
219 if (size > max_size) {
223 tmp = para_realloc(buf, size);
238 static char *escape_blob(const char* old, size_t size)
244 new = para_malloc(2 * size * sizeof(char) + 1);
245 mysql_real_escape_string(mysql_ptr, new, old, size);
249 static char *escape_str(const char* old)
251 return escape_blob(old, strlen(old));
254 static char *escaped_basename(const char *name)
256 char *esc, *bn = para_basename(name);
260 esc = escape_str(bn);
268 int com_na(__a_unused int fd, int argc, char *argv[])
274 return -E_MYSQL_SYNTAX;
275 tmp = escape_str(argv[1]);
278 q = make_message("alter table data add %s char(1) "
279 "not null default 0", tmp);
289 int com_da(__a_unused int fd, int argc, char *argv[])
295 return -E_MYSQL_SYNTAX;
296 tmp = escape_str(argv[1]);
299 q = make_message("alter table data drop %s", tmp);
307 static int com_stradd_picadd(int fd, int argc, char *argv[])
309 char *blob = NULL, *esc_blob = NULL, *q = NULL, *tmp = NULL;
310 const char *fmt, *del_fmt;
311 int ret, stradd = strcmp(argv[0], "picadd");
315 return -E_MYSQL_SYNTAX;
316 if (strlen(argv[1]) >= MAXLINE - 1)
317 return -E_NAMETOOLONG;
322 fmt = "insert into streams (name, def) values ('%s','%s')";
323 del_fmt="delete from streams where name='%s'";
325 size = MEDIUM_BLOB_SIZE;
326 fmt = "insert into pics (name, pic) values ('%s','%s')";
327 del_fmt="delete from pics where pic='%s'";
329 tmp = escape_str(argv[1]);
332 q = make_message(del_fmt, tmp);
338 if ((ret = send_buffer(fd, AWAITING_DATA_MSG) < 0))
340 if ((ret = fd2buf(fd, &blob, size)) < 0)
346 esc_blob = escape_blob(blob, size);
349 tmp = escape_str(argv[1]);
352 q = make_message(fmt, tmp, esc_blob);
363 int com_stradd(int fd, int argc, char *argv[])
365 return com_stradd_picadd(fd, argc, argv);
369 int com_picadd(int fd, int argc, char *argv[])
371 return com_stradd_picadd(fd, argc, argv);
375 * print results to fd
377 static int print_results(int fd, void *result,
378 my_ulonglong top, my_ulonglong left,
379 my_ulonglong bottom, my_ulonglong right)
385 for (i = top; i <= bottom; i++) {
386 row = mysql_fetch_row(result);
389 for (j = left; j <= right; j++) {
390 ret = send_va_buffer(fd, j == left? "%s" : "\t%s",
391 row[j]? row[j] : "NULL");
395 ret = send_buffer(fd, "\n");
405 int com_verb(int fd, int argc, char *argv[])
409 my_ulonglong num_rows, num_fields, top = 0, left = 0;
413 return -E_MYSQL_SYNTAX;
414 tmp = escape_str(argv[1]);
417 result = get_result(tmp);
420 /* return success, because it's ok to have no results */
422 num_fields = mysql_field_count(mysql_ptr);
423 num_rows = mysql_num_rows(result);
425 if (num_fields && num_rows)
426 ret = print_results(fd, result, top, left, num_rows - 1,
428 mysql_free_result(result);
432 /* returns NULL on errors or if there are no atts defined yet */
433 static void *get_all_attributes(void)
435 void *result = get_result("desc data");
436 unsigned int num_rows;
440 num_rows = mysql_num_rows(result);
442 mysql_free_result(result);
445 mysql_data_seek(result, (my_ulonglong)4); /* skip Lastplayed, Numplayed... */
450 * list all attributes
452 int com_laa(int fd, int argc, __a_unused char *argv[])
456 my_ulonglong top = 0, left = 0, bottom, right = 0;
459 return -E_MYSQL_SYNTAX;
460 result = get_all_attributes();
463 bottom = mysql_num_rows(result);
465 return -E_MYSQL_SYNTAX;
467 ret = print_results(fd, result, top, left, bottom, right);
468 mysql_free_result(result);
475 int com_hist(int fd, int argc, char *argv[])
480 my_ulonglong num_rows, top = 0, left = 0, right = 1;
483 return -E_MYSQL_SYNTAX;
485 char *tmp = escape_str(argv[1]);
488 atts = make_message("where %s = '1'", tmp);
491 atts = para_strdup(NULL);
493 q = make_message("select name, to_days(now()) - to_days(lastplayed) from "
494 "data %s order by lastplayed", atts);
496 result = get_result(q);
500 num_rows = mysql_num_rows(result);
503 ret = print_results(fd, result, top, left, num_rows - 1, right);
504 mysql_free_result(result);
509 * get last num audio files
511 int com_last(int fd, int argc, char *argv[])
516 my_ulonglong top = 0, left = 0, right = 0;
523 return -E_MYSQL_SYNTAX;
524 q = make_message("select name from data order by lastplayed desc "
526 result = get_result(q);
530 ret = print_results(fd, result, top, left, mysql_num_rows(result) - 1,
532 mysql_free_result(result);
536 int com_mbox(int fd, int argc, char *argv[])
541 my_ulonglong num_rows, num_fields, top = 0, left = 0;
542 char *query = para_strdup("select concat('From foo@localhost ', "
543 "date_format(Lastplayed, '%a %b %e %T %Y'), "
544 "'\nReceived: from\nTo: bar\n");
547 result = get_all_attributes();
551 while ((row = mysql_fetch_row(result))) {
556 tmp = make_message("%sX-Attribute-%s: ', %s, '\n", query,
561 query = para_strcat(query,
569 char *esc = escape_str(argv[1]), *tmp;
573 tmp = make_message("%s where name LIKE '%s'", query, esc);
578 mysql_free_result(result);
580 result = get_result(query);
583 ret = -E_EMPTY_RESULT;
584 num_fields = mysql_field_count(mysql_ptr);
585 num_rows = mysql_num_rows(result);
586 if (!num_fields || !num_rows)
588 ret = print_results(fd, result, top, left, num_rows - 1,
593 mysql_free_result(result);
598 * get attributes by name. If verbose is not 0, this function returns a string
599 * of the form 'att1="0",att2="1"'... which is used in com_cam() for
600 * constructing a mysql update query. Otherwise the space-separated list of all
601 * attributes which are set in the audio file given by name is returned. Never
602 * returns NULL in *NON VERBOSE* mode.
604 static char *get_atts(char *name, int verbose)
606 char *atts = NULL, *buf, *ebn;
607 void *result = NULL, *result2 = NULL;
610 my_ulonglong num_fields, offset = 4; /* skip Lastplayed, Numplayed... */
613 result2 = get_all_attributes();
616 ebn = escaped_basename(name);
619 buf = make_message("select * from data where name='%s'", ebn);
621 result = get_result(buf);
625 num_fields = mysql_num_fields(result);
628 mysql_data_seek(result2, offset);
629 row = mysql_fetch_row(result);
632 for (i = 4; i < num_fields; i++) {
633 int is_set = row[i] && !strcmp(row[i], "1");
634 row2 = mysql_fetch_row(result2);
635 if (!row2 || !row2[0])
637 if (atts && (verbose || is_set))
638 atts = para_strcat(atts, verbose? "," : " ");
639 if (is_set || verbose)
640 atts = para_strcat(atts, row2[0]);
642 atts = para_strcat(atts, is_set? "=\"1\"" : "=\"0\"");
646 mysql_free_result(result2);
648 mysql_free_result(result);
649 if (!atts && !verbose)
650 atts = para_strdup("(none)");
654 /* never returns NULL in verbose mode */
655 static char *get_meta(char *name, int verbose)
659 char *ebn, *q, *ret = NULL;
660 const char *verbose_fmt =
661 "select concat('lastplayed: ', "
662 "(to_days(now()) - to_days(lastplayed)),"
663 "' day(s). numplayed: ', numplayed, "
664 "', pic: ', pic_id) "
665 "from data where name = '%s'";
666 /* is that really needed? */
667 const char *fmt = "select concat('lastplayed=\\'', lastplayed, "
668 "'\\', numplayed=\\'', numplayed, "
669 "'\\', pic_id=\\'', pic_id, '\\'') "
670 "from data where name = '%s'";
672 if (!(ebn = escaped_basename(name)))
674 q = make_message(verbose? verbose_fmt : fmt, ebn);
676 result = get_result(q);
680 row = mysql_fetch_row(result);
683 ret = para_strdup(row[0]);
686 mysql_free_result(result);
688 ret = para_strdup("(not yet played)");
692 static char *get_dir(char *name)
694 char *ret = NULL, *q, *ebn;
698 if (!(ebn = escaped_basename(name)))
700 q = make_message("select dir from dir where name = '%s'", ebn);
702 result = get_result(q);
706 row = mysql_fetch_row(result);
708 ret = para_strdup(row[0]);
709 mysql_free_result(result);
713 /* never returns NULL */
714 static char *get_current_stream(void)
718 void *result = get_result("select def from streams where "
719 "name = 'current_stream'");
723 row = mysql_fetch_row(result);
726 ret = para_strdup(row[0]);
727 mysql_free_result(result);
731 mysql_free_result(result);
732 return para_strdup("(none)");
736 * Read stream definition of stream streamname and construct mysql
737 * query. Return NULL on errors. If streamname is NULL, use current
738 * stream. If that is also NULL, use query that selects everything.
739 * If filename is NULL, query will list everything, otherwise only
740 * the score of given file.
742 static char *get_query(char *streamname, char *filename, int with_path)
744 char *accept_opts = NULL, *deny_opts = NULL, *score = NULL;
745 char *where_clause, *order, *query;
746 char command[255] = ""; /* buffer for sscanf */
750 char *select_clause = NULL;
752 tmp = get_current_stream();
754 tmp = escape_str(streamname);
758 if (!strcmp(tmp, "(none)")) {
761 char *ret, *ebn = escaped_basename(filename);
764 ret = make_message("select to_days(now()) - "
765 "to_days(lastplayed) from data "
766 "where name = '%s'", ebn);
772 "select concat(dir.dir, '/', dir.name) "
773 "from data, dir where dir.name = data.name "
774 "order by data.lastplayed"
777 "select name from data where name is not NULL "
778 "order by lastplayed"
782 query = make_message("select def from streams where name = '%s'",
784 result = get_result(query);
789 row = mysql_fetch_row(result);
795 char *arg, *line = end;
797 if (!(end = strchr(line, '\n')))
801 if (sscanf(line, "%200s%n", command, &n) < 1)
804 if (!strcmp(command, "accept:")) {
805 char *tmp2 = s_a_r_list(mysql_macro_list, arg);
807 accept_opts = para_strcat(
808 accept_opts, " or ");
809 accept_opts = para_strcat(accept_opts, tmp2);
813 if (!strcmp(command, "deny:")) {
814 char *tmp2 = s_a_r_list(mysql_macro_list, arg);
816 deny_opts = para_strcat(deny_opts, " or ");
817 deny_opts = para_strcat(deny_opts, tmp2);
821 if (!score && !strcmp(command, "score:"))
822 score = s_a_r_list(mysql_macro_list, arg);
825 score = s_a_r_list(mysql_macro_list, conf.mysql_default_score_arg);
830 char *ebn = escaped_basename(filename);
833 select_clause = make_message("select %s from data ", score);
835 where_clause = make_message( "where name = '%s' ", ebn);
837 order = para_strdup("");
840 select_clause = para_strdup(with_path?
841 "select concat(dir.dir, '/', dir.name) from data, dir "
842 "where dir.name = data.name "
844 "select name from data where name is not NULL");
845 order = make_message("order by -(%s)", score);
847 if (accept_opts && deny_opts) {
848 where_clause = make_message("and ((%s) and not (%s)) ",
849 accept_opts, deny_opts);
852 if (accept_opts && !deny_opts) {
853 where_clause = make_message("and (%s) ", accept_opts);
856 if (!accept_opts && deny_opts) {
857 where_clause = make_message("and not (%s) ", deny_opts);
860 where_clause = para_strdup("");
862 query = make_message("%s %s %s", select_clause, where_clause, order);
872 mysql_free_result(result);
879 * This is called from server and from some commands. Name must not be NULL
880 * Never returns NULL.
882 static char *get_selector_info(char *name)
884 char *meta, *atts, *info, *dir, *query, *stream;
886 MYSQL_ROW row = NULL;
889 return para_strdup("(none)");
890 stream = get_current_stream();
891 meta = get_meta(name, 1);
892 atts = get_atts(name, 0);
895 query = get_query(stream, name, 0); /* FIXME: pass stream == NULL instead? */
898 result = get_result(query);
901 row = mysql_fetch_row(result);
903 info = make_message("dbinfo1:dir: %s\n"
904 "dbinfo2:stream: %s, %s, score: %s\n"
906 dir? dir : "(not contained in table)",
908 (result && row && row[0])? row[0] : "(no score)",
915 mysql_free_result(result);
919 /* might return NULL */
920 static char *get_current_audio_file(void)
924 name = para_basename(mmd->filename);
929 /* If called as child, mmd_lock must be held */
930 static void update_mmd(char *info)
932 PARA_DEBUG_LOG("%s", "updating shared memory area\n");
933 strncpy(mmd->selector_info, info, MMD_INFO_SIZE - 1);
934 mmd->selector_info[MMD_INFO_SIZE - 1] = '\0';
937 static void refresh_selector_info(void)
939 char *name = get_current_audio_file();
944 info = get_selector_info(name);
952 /* list attributes / print database info */
953 static int com_la_info(int fd, int argc, char *argv[])
955 char *name = NULL, *meta = NULL, *atts = NULL, *dir = NULL;
956 int ret, la = strcmp(argv[0], "info");
959 ret = -E_GET_AUDIO_FILE;
960 if (!(name = get_current_audio_file()))
962 ret = send_va_buffer(fd, "%s\n", name);
967 if (!(name = escaped_basename(argv[1])))
970 meta = get_meta(name, 1);
971 atts = get_atts(name, 0);
974 ret = send_va_buffer(fd, "%s\n", atts);
976 ret = send_va_buffer(fd, "dir: %s\n" "%s\n" "attributes: %s\n",
977 dir? dir : "(not contained in table)", meta, atts);
986 /* list attributes */
987 int com_la(int fd, int argc, char *argv[])
989 return com_la_info(fd, argc, argv);
992 /* print database info */
993 int com_info(int fd, int argc, char *argv[])
995 return com_la_info(fd, argc, argv);
998 static int change_stream(const char *stream)
1002 query = make_message("update streams set def='%s' "
1003 "where name = 'current_stream'", stream);
1004 ret = real_query(query);
1009 static int get_pic_id_by_name(char *name)
1012 void *result = NULL;
1016 if (!(ebn = escaped_basename(name)))
1018 q = make_message("select pic_id from data where name = '%s'", ebn);
1020 result = get_result(q);
1024 row = mysql_fetch_row(result);
1028 mysql_free_result(result);
1032 static int remove_entry(const char *name)
1034 char *q, *ebn = escaped_basename(name);
1035 int ret = -E_ESCAPE;
1039 q = make_message("delete from data where name = '%s'", ebn);
1040 real_query(q); /* ignore errors */
1042 q = make_message("delete from dir where name = '%s'", ebn);
1043 real_query(q); /* ignore errors */
1051 static int add_entry(const char *name)
1053 char *q, *dn, *ebn = NULL, *edn = NULL;
1056 if (!name || !*name)
1057 return -E_MYSQL_SYNTAX;
1058 ebn = escaped_basename(name);
1061 ret = -E_MYSQL_SYNTAX;
1062 dn = para_dirname(name);
1066 edn = escape_str(dn);
1070 q = make_message("insert into data (name, pic_id) values "
1071 "('%s', '%s')", ebn, "1");
1072 ret = real_query(q);
1073 // ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1077 q = make_message("insert into dir (name, dir) values "
1078 "('%s', '%s')", ebn, edn);
1079 // ret = 1; PARA_DEBUG_LOG("q: %s\n", q);
1080 ret = real_query(q);
1091 * remove/add entries
1093 static int com_rm_ne(__a_unused int fd, int argc, char *argv[])
1095 int ne = !strcmp(argv[0], "ne");
1098 return -E_MYSQL_SYNTAX;
1099 for (i = 1; i < argc; i++) {
1100 ret = remove_entry(argv[i]);
1105 ret = add_entry(argv[i]);
1115 int com_rm(int fd, int argc, char *argv[])
1117 return com_rm_ne(fd, argc, argv);
1123 int com_ne(int fd, int argc, char *argv[])
1125 return com_ne(fd, argc, argv);
1131 int com_mv(__a_unused int fd, int argc, char *argv[])
1133 char *q, *dn, *ebn1 = NULL, *ebn2 = NULL, *edn = NULL;
1137 return -E_MYSQL_SYNTAX;
1139 ebn1 = escaped_basename(argv[1]);
1140 ebn2 = escaped_basename(argv[2]);
1141 if (!ebn1 || !ebn2 || !*ebn1 || !*ebn2)
1143 ret = -E_MYSQL_SYNTAX;
1144 if (!strcmp(ebn1, ebn2))
1146 remove_entry(argv[2]); /* no need to escape, ignore error */
1147 q = make_message("update data set name = '%s' where name = '%s'",
1149 ret = real_query(q);
1153 ret = -E_AUDIO_FILE;
1154 if (!mysql_affected_rows(mysql_ptr))
1156 q = make_message("update dir set name = '%s' where name = '%s'",
1158 ret = real_query(q);
1164 dn = para_dirname(argv[2]);
1168 edn = escape_str(dn);
1175 q = make_message("update dir set dir = '%s' where name = '%s'",
1177 ret = real_query(q);
1189 static int com_set(__a_unused int fd, int argc, char *argv[])
1194 const char *field = strcmp(argv[0], "picass")? "numplayed" : "pic_id";
1197 return -E_MYSQL_SYNTAX;
1199 for (i = 2; i < argc; i++) {
1200 ebn = escaped_basename(argv[i]);
1203 q = make_message("update data set %s = %lu "
1204 "where name = '%s'", field, id, ebn);
1206 ret = real_query(q);
1215 * snp: set numplayed
1217 int com_picass(int fd, int argc, char *argv[])
1219 return com_set(fd, argc, argv);
1223 * snp: set numplayed
1225 int com_snp(int fd, int argc, char *argv[])
1227 int ret = com_set(fd, argc, argv);
1229 refresh_selector_info();
1234 * picch: change entry's name in pics table
1236 int com_picch(__a_unused int fd, int argc, char *argv[])
1243 return -E_MYSQL_SYNTAX;
1246 tmp = escape_str(argv[2]);
1249 q = make_message("update pics set name = '%s' where id = %lu", tmp, id);
1251 ret = real_query(q);
1257 * piclist: print list of pics in db
1259 int com_piclist(__a_unused int fd, int argc, __a_unused char *argv[])
1261 void *result = NULL;
1263 unsigned long *length;
1267 return -E_MYSQL_SYNTAX;
1268 result = get_result("select id,name,pic from pics order by id");
1271 while ((row = mysql_fetch_row(result))) {
1272 length = mysql_fetch_lengths(result);
1273 if (!row || !row[0] || !row[1] || !row[2])
1275 ret = send_va_buffer(fd, "%s\t%lu\t%s\n", row[0], length[2], row[1]);
1281 mysql_free_result(result);
1286 * picdel: delete picture from database
1288 int com_picdel(int fd, int argc, char *argv[])
1296 return -E_MYSQL_SYNTAX;
1297 for (i = 1; i < argc; i++) {
1299 q = make_message("delete from pics where id = %lu", id);
1300 ret = real_query(q);
1304 aff = mysql_affected_rows(mysql_ptr);
1306 ret = send_va_buffer(fd, "No such id: %lu\n", id);
1311 q = make_message("update data set pic_id = 1 where pic_id = %lu", id);
1312 ret = real_query(q);
1318 * pic: get picture by name or by number
1320 int com_pic(int fd, int argc, char *argv[])
1322 void *result = NULL;
1324 unsigned long *length, id;
1326 char *q, *name = NULL;
1329 ret = -E_GET_AUDIO_FILE;
1330 name = get_current_audio_file();
1333 name = escaped_basename(argv[1]);
1338 id = atoi(name + 1);
1340 id = get_pic_id_by_name(name);
1344 q = make_message("select pic from pics where id = '%lu'", id);
1345 result = get_result(q);
1349 row = mysql_fetch_row(result);
1351 if (!row || !row[0])
1353 length = mysql_fetch_lengths(result);
1354 ret = send_bin_buffer(fd, row[0], *length);
1356 mysql_free_result(result);
1361 int com_strdel(__a_unused int fd, int argc, char *argv[])
1367 return -E_MYSQL_SYNTAX;
1368 tmp = escape_str(argv[1]);
1371 q = make_message("delete from streams where name='%s'", tmp);
1373 ret = real_query(q);
1381 int com_ls(int fd, int argc, char *argv[])
1386 my_ulonglong num_rows, top = 0, left = 0, right = 0;
1389 return -E_MYSQL_SYNTAX;
1391 char *tmp = escape_str(argv[1]);
1394 q = make_message("select name from data where name like '%s'",
1398 q = para_strdup("select name from data");
1399 result = get_result(q);
1403 num_rows = mysql_num_rows(result);
1406 ret = print_results(fd, result, top, left, num_rows - 1, right);
1407 mysql_free_result(result);
1414 int com_summary(__a_unused int fd, int argc, __a_unused char *argv[])
1419 void *result2 = NULL;
1420 const char *fmt = "select count(name) from data where %s='1'";
1421 int ret = -E_NORESULT;
1424 return -E_MYSQL_SYNTAX;
1425 result = get_all_attributes();
1428 while ((row = mysql_fetch_row(result))) {
1435 buf = make_message(fmt, row[0]);
1436 result2 = get_result(buf);
1441 row2 = mysql_fetch_row(result2);
1442 if (!row2 || !row2[0])
1444 ret = send_va_buffer(fd, "%s\t%s\n", row[0], row2[0]);
1451 mysql_free_result(result2);
1453 mysql_free_result(result);
1457 static int get_numplayed(char *name)
1461 const char *fmt = "select numplayed from data where name = '%s'";
1462 char *buf = make_message(fmt, name);
1463 int ret = -E_NORESULT;
1465 result = get_result(buf);
1470 row = mysql_fetch_row(result);
1471 if (!row || !row[0])
1476 mysql_free_result(result);
1480 static int update_audio_file(char *name)
1483 const char *fmt1 = "update data set lastplayed = now() where name = '%s'";
1484 const char *fmt2 = "update data set numplayed = %i where name = '%s'";
1486 char *ebn = escaped_basename(name);
1491 q = make_message(fmt1, ebn);
1492 ret = real_query(q);
1496 ret = get_numplayed(ebn);
1499 q = make_message(fmt2, ret + 1, ebn);
1500 ret = real_query(q);
1507 static void update_audio_file_server_handler(char *name)
1510 info = get_selector_info(name);
1513 update_audio_file(name);
1516 int com_us(__a_unused int fd, int argc, char *argv[])
1522 return -E_MYSQL_SYNTAX;
1523 tmp = escape_str(argv[1]);
1526 ret = update_audio_file(argv[1]);
1529 refresh_selector_info();
1533 /* select previous / next stream */
1534 static int com_ps_ns(__a_unused int fd, int argc, char *argv[])
1536 char *query, *stream = get_current_stream();
1537 void *result = get_result("select name from streams");
1540 my_ulonglong num_rows, match, i;
1542 ret = -E_MYSQL_SYNTAX;
1548 num_rows = mysql_num_rows(result);
1549 ret = -E_EMPTY_RESULT;
1553 for (i = 0; i < num_rows; i++) {
1554 row = mysql_fetch_row(result);
1555 if (!row || !row[0])
1557 if (!strcmp(row[0], "current_stream"))
1559 if (!strcmp(row[0], stream))
1566 if (!strcmp(argv[0], "ps"))
1567 i = match > 0? match - 1 : num_rows - 1;
1569 i = match < num_rows - 1? match + 1 : 0;
1571 mysql_data_seek(result, i);
1572 row = mysql_fetch_row(result);
1573 if (!row || !row[0])
1575 if (!strcmp(row[0], "current_stream")) {
1576 if (!strcmp(argv[0], "ps")) {
1577 i = match < 2? match + num_rows - 2 : match - 2;
1580 i = i > num_rows - 1? i - num_rows : i;
1582 mysql_data_seek(result, i);
1583 row = mysql_fetch_row(result);
1584 if (!row || !row[0])
1587 query = make_message("update streams set def='%s' where name = "
1588 "'current_stream'", row[0]);
1589 ret = real_query(query);
1591 refresh_selector_info();
1595 mysql_free_result(result);
1599 /* select previous stream */
1600 int com_ps(int fd, int argc, char *argv[])
1602 return com_ps_ns(fd, argc, argv);
1605 /* select next stream */
1606 int com_ns(int fd, int argc, char *argv[])
1608 return com_ps_ns(fd, argc, argv);
1612 int com_streams(int fd, int argc, __a_unused char *argv[])
1614 unsigned int num_rows;
1615 int i, ret = -E_NORESULT;
1619 if (argc > 1 && strcmp(argv[1], "current_stream"))
1620 return -E_MYSQL_SYNTAX;
1622 char *cs = get_current_stream();
1623 ret = send_va_buffer(fd, "%s\n", cs);
1627 result = get_result("select name from streams");
1630 num_rows = mysql_num_rows(result);
1635 for (i = 0; i < num_rows; i++) {
1636 row = mysql_fetch_row(result);
1637 if (!row || !row[0])
1639 if (strcmp(row[0], "current_stream"))
1640 send_va_buffer(fd, "%s\n", row[0]);
1645 mysql_free_result(result);
1649 /* query stream definition */
1650 int com_strq(int fd, int argc, char *argv[])
1658 ret = -E_GET_STREAM;
1659 name = get_current_stream();
1662 name = escaped_basename(argv[1]);
1667 query = make_message("select def from streams where name='%s'", name);
1669 result = get_result(query);
1674 row = mysql_fetch_row(result);
1675 if (!row || !row[0])
1677 /* no '\n' needed */
1678 ret = send_buffer(fd, row[0]);
1681 mysql_free_result(result);
1685 /* change stream / change stream and play */
1686 static int com_cs_csp(int fd, int argc, char *argv[])
1688 int ret, stream_change;
1689 char *query, *stream = NULL;
1690 char *old_stream = get_current_stream();
1691 int csp = !strcmp(argv[0], "csp");
1693 ret = -E_MYSQL_SYNTAX;
1699 ret = send_va_buffer(fd, "%s\n", old_stream);
1703 /* test if stream is valid, no need to escape argv[1] */
1704 query = get_query(argv[1], NULL, 0);
1709 stream = escape_str(argv[1]);
1712 stream_change = strcmp(stream, old_stream);
1713 if (stream_change) {
1714 ret = change_stream(stream);
1717 refresh_selector_info();
1721 mmd->new_vss_status_flags |= VSS_PLAYING;
1723 mmd->new_vss_status_flags |= VSS_NEXT;
1734 int com_cs(int fd, int argc, char *argv[])
1736 return com_cs_csp(fd, argc, argv);
1739 /* change stream and play */
1740 int com_csp(int fd, int argc, char *argv[])
1742 return com_cs_csp(fd, argc, argv);
1745 /* score list / skip */
1746 static int com_sl_skip(int fd, int argc, char *argv[])
1748 void *result = NULL;
1750 int ret, i, skip = !strcmp(argv[0], "skip");
1751 char *query, *stream, *tmp;
1752 unsigned int num_rows, num;
1755 return -E_MYSQL_SYNTAX;
1756 num = atoi(argv[1]);
1758 return -E_MYSQL_SYNTAX;
1760 stream = get_current_stream();
1762 return -E_GET_STREAM;
1764 stream = escape_str(argv[2]);
1768 tmp = get_query(stream, NULL, 0);
1771 return -E_GET_QUERY;
1772 query = make_message("%s limit %d", tmp, num);
1775 result = get_result(query);
1779 ret = -E_EMPTY_RESULT;
1780 num_rows = mysql_num_rows(result);
1783 for (i = 0; i < num_rows && i < num; i++) {
1784 row = mysql_fetch_row(result);
1786 send_va_buffer(fd, "Skipping %s\n", row[0]);
1787 update_audio_file(row[0]);
1789 send_va_buffer(fd, "%s\n", row[0]? row[0]: "BUG");
1794 mysql_free_result(result);
1799 int com_sl(int fd, int argc, char *argv[])
1801 return com_sl_skip(fd, argc, argv);
1805 int com_skip(int fd, int argc, char *argv[])
1807 return com_sl_skip(fd, argc, argv);
1811 * update attributes of name
1813 static int update_atts(int fd, char *name, char *atts)
1816 char *ebn, *q, *old, *new = NULL;
1820 ebn = escaped_basename(name);
1823 q = make_message("update data set %s where name = '%s'", atts, ebn);
1824 old = get_atts(ebn, 0);
1825 send_va_buffer(fd, "old: %s\n", old);
1827 ret = real_query(q);
1831 new = get_atts(ebn, 0);
1832 ret = send_va_buffer(fd, "new: %s\n", new);
1842 int com_sa(int fd, int argc, char *argv[])
1845 char *atts = NULL, *name;
1848 return -E_MYSQL_SYNTAX;
1849 for (i = 1; i < argc; i++) {
1851 char *esc, *tmp, *p =argv[i];
1852 int len = strlen(p);
1856 switch (p[len - 1]) {
1867 esc = escape_str(p);
1870 tmp = make_message("%s%s='%s'", atts? "," : "", esc,
1873 atts = para_strcat(atts, tmp);
1879 if (i >= argc) { /* no name given, use current af */
1880 ret = -E_GET_AUDIO_FILE;
1881 if (!(name = get_current_audio_file()))
1883 ret = update_atts(fd, name, atts);
1887 for (; argv[i] && ret >= 0; i++)
1888 ret = update_atts(fd, argv[i], atts);
1890 refresh_selector_info();
1899 int com_cam(int fd, int argc, char *argv[])
1901 char *name = NULL, *meta = NULL, *atts = NULL;
1905 return -E_MYSQL_SYNTAX;
1906 if (!(name = escaped_basename(argv[1])))
1909 if (!(atts = get_atts(name, 1)))
1912 if (!(meta = get_meta(name, 0)))
1914 for (i = 2; i < argc; i++) {
1917 if (!(ebn = escaped_basename(argv[i])))
1919 ret = send_va_buffer(fd, "updating %s\n", ebn);
1924 q = make_message("update data set %s where name = '%s'",
1926 if ((ret = update_atts(fd, ebn, atts)) >= 0)
1927 ret = real_query(q);
1947 static int com_vrfy_clean(int fd, int argc, __a_unused char *argv[])
1950 int ret, vrfy_mode = strcmp(argv[0], "clean");
1951 void *result = NULL;
1954 my_ulonglong num_rows, top = 0, left = 0, right = 0;
1957 return -E_MYSQL_SYNTAX;
1959 result = get_result("select data.name from data left join dir on "
1960 "dir.name = data.name where dir.name is NULL");
1963 num_rows = mysql_num_rows(result);
1965 ret = send_buffer(fd, "No invalid entries\n");
1969 send_va_buffer(fd, "found %lli invalid entr%s\n", num_rows,
1970 num_rows == 1? "y" : "ies");
1971 ret = print_results(fd, result, top, left, num_rows - 1, right);
1974 while ((row = mysql_fetch_row(result))) {
1979 escaped_name = escape_str(row[0]);
1982 send_va_buffer(fd, "deleting %s\n", escaped_name);
1983 query = make_message("delete from data where name = '%s'",
1985 ret = real_query(query);
1993 mysql_free_result(result);
2000 int com_vrfy(int fd, int argc, char **argv)
2002 return com_vrfy_clean(fd, argc, argv);
2008 int com_clean(int fd, int argc, char **argv)
2010 return com_vrfy_clean(fd, argc, argv);
2013 static FILE *out_file;
2015 static int mysql_write_tmp_file(const char *dir, const char *name)
2017 int ret = -E_TMPFILE;
2018 char *msg = make_message("%s\t%s\n", dir, name);
2019 if (fputs(msg, out_file) != EOF)
2028 int com_upd(int fd, int argc, __a_unused char *argv[])
2030 char *tempname = NULL, *query = NULL;
2031 int ret, out_fd = -1, num = 0;
2032 void *result = NULL;
2033 unsigned int num_rows;
2037 return -E_MYSQL_SYNTAX;
2039 tempname = para_strdup("/tmp/mysql.tmp.XXXXXX");
2040 ret = para_mkstemp(tempname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
2044 out_file = fdopen(out_fd, "w");
2049 if (find_audio_files(conf.mysql_audio_file_dir_arg, mysql_write_tmp_file) < 0)
2051 num = ftell(out_file);
2053 * we have to make sure the file hit the disk before we call
2058 PARA_DEBUG_LOG("wrote tempfile %s (%d bytes)\n", tempname, num);
2061 if ((ret = real_query("delete from dir")) < 0)
2063 query = make_message("load data infile '%s' ignore into table dir "
2064 "fields terminated by '\t' lines terminated by '\n' "
2065 "(dir, name)", tempname);
2066 ret = real_query(query);
2070 result = get_result("select dir.name from dir left join data on "
2071 "data.name = dir.name where data.name is NULL");
2075 num_rows = mysql_num_rows(result);
2077 ret = send_buffer(fd, "no new entries\n");
2080 while ((row = mysql_fetch_row(result))) {
2085 send_va_buffer(fd, "new entry: %s\n", row[0]);
2086 erow = escape_str(row[0]);
2089 query = make_message("insert into data (name, pic_id) values "
2090 "('%s','%s')", erow, "1");
2092 ret = real_query(query);
2105 mysql_free_result(result);
2109 static char **server_get_audio_file_list(unsigned int num)
2111 char **list = para_malloc((num + 1) * sizeof(char *));
2112 char *tmp, *query, *stream = get_current_stream();
2113 void *result = NULL;
2114 unsigned int num_rows;
2118 tmp = get_query(stream, NULL, 1);
2122 query = make_message("%s limit %d", tmp, num);
2124 result = get_result(query);
2128 num_rows = mysql_num_rows(result);
2131 for (i = 0; i < num_rows && i < num; i++) {
2132 row = mysql_fetch_row(result);
2133 if (!row || !row[0])
2135 list[i] = para_strdup(row[0]);
2148 mysql_free_result(result);
2153 * connect to mysql server, return mysql pointer on success, -E_NOTCONN
2154 * on errors. Called from parent on startup and also from com_cdb().
2156 static int init_mysql_server(void)
2158 char *u = conf.mysql_user_arg? conf.mysql_user_arg : para_logname();
2161 mysql_ptr = mysql_init(NULL);
2163 PARA_CRIT_LOG("%s", "mysql init error\n");
2166 if (conf.mysql_port_arg < 0)
2167 return -E_MYSQL_SYNTAX;
2168 port = conf.mysql_port_arg;
2169 PARA_DEBUG_LOG("connecting: %s@%s:%d\n", u, conf.mysql_host_arg, port);
2170 if (!conf.mysql_user_arg)
2173 * If host is NULL a connection to the local host is assumed,
2174 * If user is NULL, the current user is assumed
2176 if (!(mysql_ptr = mysql_real_connect(mysql_ptr,
2177 conf.mysql_host_arg,
2178 conf.mysql_user_arg,
2179 conf.mysql_passwd_arg,
2180 conf.mysql_database_arg,
2182 PARA_CRIT_LOG("%s", "connect error\n");
2185 PARA_INFO_LOG("%s", "success\n");
2189 /* mmd lock must be held */
2190 static void write_msg2mmd(int success)
2192 sprintf(mmd->selector_info, "dbinfo1:%s\ndbinfo2:mysql-%s\ndbinfo3:\n",
2193 success < 0? PARA_STRERROR(-success) :
2194 "successfully connected to mysql server",
2195 success < 0? "" : mysql_get_server_info(mysql_ptr));
2198 /* create database */
2199 int com_cdb(int fd, int argc, char *argv[])
2205 PARA_INFO_LOG("%s", "closing database\n");
2206 mysql_close(mysql_ptr);
2208 /* dont use any database */
2209 conf.mysql_database_arg = NULL; /* leak? */
2210 ret = -E_MYSQL_INIT;
2211 if (init_mysql_server() < 0 || !mysql_ptr)
2214 conf.mysql_database_arg = para_strdup("paraslash");
2217 conf.mysql_database_arg = escape_str(argv[1]);
2218 if (!conf.mysql_database_arg)
2221 query = make_message("create database %s", conf.mysql_database_arg);
2222 ret = real_query(query);
2226 /* reconnect with database just created */
2227 mysql_close(mysql_ptr);
2228 ret = -E_MYSQL_INIT;
2229 if (init_mysql_server() < 0 || !mysql_ptr)
2235 if (real_query("create table data (name varchar(255) binary not null "
2237 "lastplayed datetime not null default "
2239 "numplayed int not null default 0, "
2240 "pic_id bigint unsigned not null default 1)") < 0)
2242 if (real_query("create table dir (name varchar(255) binary not null "
2243 "primary key, dir varchar(255) default null)") < 0)
2245 if (real_query("create table pics ("
2246 "id bigint(20) unsigned not null primary key "
2248 "name varchar(255) binary not null, "
2249 "pic mediumblob not null)") < 0)
2251 if (real_query("create table streams ("
2252 "name varchar(255) binary not null primary key, "
2253 "def blob not null)") < 0)
2255 if (real_query("insert into streams (name, def) values "
2256 "('current_stream', '(none)')") < 0)
2258 ret = send_va_buffer(fd, "successfully created database %s\n",
2259 conf.mysql_database_arg);
2264 static void shutdown_connection(void)
2269 PARA_NOTICE_LOG("%s", "shutting down mysql connection\n");
2270 mysql_close(mysql_ptr);
2274 ret = mutex_destroy(mysql_lock);
2276 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
2282 * the init function of the mysql-based audio file selector
2284 * \param db pointer to the struct to initialize
2286 * Check the command line options and initialize all function pointers of \a
2287 * db. Connect to the mysql server and initialize the info string.
2289 * \return This function returns success even if it could not connect
2290 * to the mysql server. This is because the connect is expected to fail
2291 * if there the paraslash database is not yet created. This gives the
2292 * user a chance to send the "cdb" to create the database.
2294 * \sa struct audio_file_selector, misc_meta_data::selector_info,
2297 int mysql_selector_init(struct audio_file_selector *db)
2301 if (!conf.mysql_passwd_given)
2302 return -E_NO_MYSQL_PASSWD;
2303 if (!conf.mysql_audio_file_dir_given)
2304 return -E_NO_AF_DIR;
2306 db->cmd_list = mysql_selector_cmds;
2307 db->get_audio_file_list = server_get_audio_file_list;
2308 db->update_audio_file = update_audio_file_server_handler;
2309 db->shutdown = shutdown_connection;
2314 ret = init_mysql_server();
2316 PARA_WARNING_LOG("%s\n", PARA_STRERROR(-ret));
2318 return 1; /* return success even if connect failed to give the
2319 * user the chance to exec com_cdb