Debian Codegraph @

src/sonic.c

raw symbols SCIP
1 /*
2 * HTTPDirFS - HTTP Directory Filesystem
3 *
4 * Copyright (C) 2020-2026 Fufu Fang <[email protected]>
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * In addition, as a special exception, the copyright holders give
20 * permission to link the code of portions of this program with the OpenSSL
21 * library.
22 */
23
24 /**
25 * \file sonic.c
26 * \brief Airsonic / Subsonic server API integration implementation
27 */
28
29 #include "sonic.h"
30
31 #include "config.h"
32 #include "link.h"
33 #include "log.h"
34 #include "memcache.h"
35 #include "util.h"
36
37 #include <assert.h>
38 #include <expat.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42
43 typedef struct {
44 char *server;
45 char *username;
46 char *password;
47 char *client;
48 char *api_version;
49 } SonicConfigStruct;
50
51 static SonicConfigStruct SONIC_CONFIG;
52
53 /**
54 * \brief initialise Sonic configuration struct
55 */
56 void sonic_config_init(const char *server, const char *username,
57 const char *password)
58 {
59 SONIC_CONFIG.server = STRNDUP(server, PATH_MAX);
60 /*
61 * Correct for the extra '/'
62 */
63 size_t server_url_len = strnlen(SONIC_CONFIG.server, PATH_MAX);
64 if (server_url_len > 0 && SONIC_CONFIG.server[server_url_len - 1] == '/') {
65 SONIC_CONFIG.server[server_url_len - 1] = '\0';
66 }
67 SONIC_CONFIG.username = STRNDUP(username, NAME_MAX);
68 SONIC_CONFIG.password = STRNDUP(password, NAME_MAX);
69 SONIC_CONFIG.client = DEFAULT_USER_AGENT;
70
71 if (!CONFIG.sonic_insecure) {
72 /*
73 * API 1.13.0 is the minimum version that supports
74 * salt authentication scheme
75 */
76 SONIC_CONFIG.api_version = "1.13.0";
77 } else {
78 /*
79 * API 1.8.0 is the minimum version that supports ID3 mode
80 */
81 SONIC_CONFIG.api_version = "1.8.0";
82 }
83 }
84
85 /**
86 * \brief generate authentication string
87 */
88 static char *sonic_gen_auth_str(void)
89 {
90 if (!CONFIG.sonic_insecure) {
91 char *salt = generate_salt();
92 size_t pwd_len = strnlen(SONIC_CONFIG.password, NAME_MAX);
93 size_t salt_len = strnlen(salt, NAME_MAX);
94 size_t pwd_salt_len = pwd_len + salt_len;
95 char *pwd_salt = CALLOC(pwd_salt_len + 1, sizeof(char));
96 memcpy(pwd_salt, SONIC_CONFIG.password, pwd_len);
97 memcpy(pwd_salt + pwd_len, salt, salt_len);
98 pwd_salt[pwd_salt_len] = '\0';
99 char *token = generate_md5sum(pwd_salt);
100 char *auth_str = CALLOC(PATH_MAX + 1, sizeof(char));
101 snprintf(auth_str, PATH_MAX + 1, ".view?u=%s&t=%s&s=%s&v=%s&c=%s",
102 SONIC_CONFIG.username, token, salt, SONIC_CONFIG.api_version,
103 SONIC_CONFIG.client);
104 FREE(salt);
105 FREE(token);
106 FREE(pwd_salt);
107 return auth_str;
108 } else {
109 char *pwd_hex = str_to_hex(SONIC_CONFIG.password);
110 char *auth_str = CALLOC(PATH_MAX + 1, sizeof(char));
111 snprintf(auth_str, PATH_MAX + 1, ".view?u=%s&p=enc:%s&v=%s&c=%s",
112 SONIC_CONFIG.username, pwd_hex, SONIC_CONFIG.api_version,
113 SONIC_CONFIG.client);
114 FREE(pwd_hex);
115 return auth_str;
116 }
117 }
118
119 /**
120 * \brief generate the first half of the request URL
121 */
122 static char *sonic_gen_url_first_part(char *method)
123 {
124 char *auth_str = sonic_gen_auth_str();
125 char *url = CALLOC(PATH_MAX + 1, sizeof(char));
126 snprintf(url, PATH_MAX + 1, "%s/rest/%s%s", SONIC_CONFIG.server, method,
127 auth_str);
128 FREE(auth_str);
129 return url;
130 }
131
132 /**
133 * \brief generate a getMusicDirectory request URL
134 */
135 static char *sonic_getMusicDirectory_link(const char *id)
136 {
137 char *first_part = sonic_gen_url_first_part("getMusicDirectory");
138 char *url = CALLOC(PATH_MAX + 1, sizeof(char));
139 snprintf(url, PATH_MAX + 1, "%s&id=%s", first_part, id);
140 FREE(first_part);
141 return url;
142 }
143
144 /**
145 * \brief generate a getArtist request URL
146 */
147 static char *sonic_getArtist_link(const char *id)
148 {
149 char *first_part = sonic_gen_url_first_part("getArtist");
150 char *url = CALLOC(PATH_MAX + 1, sizeof(char));
151 snprintf(url, PATH_MAX + 1, "%s&id=%s", first_part, id);
152 FREE(first_part);
153 return url;
154 }
155
156 /**
157 * \brief generate a getAlbum request URL
158 */
159 static char *sonic_getAlbum_link(const char *id)
160 {
161 char *first_part = sonic_gen_url_first_part("getAlbum");
162 char *url = CALLOC(PATH_MAX + 1, sizeof(char));
163 snprintf(url, PATH_MAX + 1, "%s&id=%s", first_part, id);
164 FREE(first_part);
165 return url;
166 }
167
168 /**
169 * \brief generate a download request URL
170 */
171 static char *sonic_stream_link(const char *id)
172 {
173 char *first_part = sonic_gen_url_first_part("stream");
174 char *url = CALLOC(PATH_MAX + 1, sizeof(char));
175 snprintf(url, PATH_MAX + 1, "%s&format=raw&id=%s", first_part, id);
176 FREE(first_part);
177 return url;
178 }
179
180 /**
181 * \brief The parser for Sonic index mode
182 * \details This is the callback function called by the the XML parser.
183 * \param[in] data user supplied data, in this case it is the pointer to the
184 * LinkTable.
185 * \param[in] elem the name of this element, it should be either "child" or
186 * "artist"
187 * \param[in] attr Each attribute seen in a start (or empty) tag occupies
188 * 2 consecutive places in this vector: the attribute name followed by the
189 * attribute value. These pairs are terminated by a null pointer.
190 * \note we are using strcmp rather than strncmp, because we are assuming the
191 * parser terminates the strings properly, which is a fair assumption,
192 * considering how mature expat is.
193 */
194 static void XMLCALL XML_parser_general(void *data, const char *elem,
195 const char **attr)
196 {
197 /*
198 * Error checking
199 */
200 if (!strcmp(elem, "error")) {
201 lprintf(error, "error:\n");
202 for (int i = 0; attr[i]; i += 2) {
203 lprintf(error, "%s: %s\n", attr[i], attr[i + 1]);
204 }
205 }
206
207 LinkTable *linktbl = (LinkTable *)data;
208 Link *link;
209
210 /*
211 * Please refer to the documentation at the function prototype of
212 * sonic_LinkTable_new_id3()
213 */
214 if (!strcmp(elem, "child")
215 || (!strcmp(elem, "artist") && linktbl->links[0]->sonic.depth != 3)) {
216 link = CALLOC(1, sizeof(Link));
217 link->type = LINK_DIR;
218 } else if (!strcmp(elem, "album") && linktbl->links[0]->sonic.depth == 3) {
219 link = CALLOC(1, sizeof(Link));
220 link->type = LINK_DIR;
221 /*
222 * The new table should be a level 4 song table
223 */
224 link->sonic.depth = 4;
225 } else if (!strcmp(elem, "song") && linktbl->links[0]->sonic.depth == 4) {
226 link = CALLOC(1, sizeof(Link));
227 link->type = LINK_FILE;
228 } else {
229 /*
230 * The element does not contain directory structural information
231 */
232 return;
233 }
234
235 int id_set = 0;
236 int linkname_set = 0;
237
238 int track = 0;
239 char *title = "";
240 char *suffix = "";
241 for (int i = 0; attr[i]; i += 2) {
242 if (!strcmp("id", attr[i])) {
243 link->sonic.id = CALLOC(NAME_MAX + 1, sizeof(char));
244 strncpy(link->sonic.id, attr[i + 1], NAME_MAX);
245 id_set = 1;
246 continue;
247 }
248
249 if (!strcmp("path", attr[i])) {
250 memset(link->linkname, 0, NAME_MAX);
251 /*
252 * Skip to the last '/' if it exists
253 */
254 const char *s = strrchr(attr[i + 1], '/');
255 if (s) {
256 strncpy(link->linkname, s + 1, NAME_MAX);
257 } else {
258 strncpy(link->linkname, attr[i + 1], NAME_MAX);
259 }
260 linkname_set = 1;
261 continue;
262 }
263
264 /*
265 * "title" is used for directory name,
266 * "name" is for top level directories
267 * N.B. "path" attribute is given the preference
268 */
269 if (!linkname_set
270 && (!strcmp("title", attr[i]) || !strcmp("name", attr[i]))) {
271 strncpy(link->linkname, attr[i + 1], NAME_MAX);
272 linkname_set = 1;
273 continue;
274 }
275
276 if (!strcmp("isDir", attr[i])) {
277 if (!strcmp("false", attr[i + 1])) {
278 link->type = LINK_FILE;
279 }
280 continue;
281 }
282
283 if (!strcmp("created", attr[i])) {
284 struct tm *tm = CALLOC(1, sizeof(struct tm));
285 strptime(attr[i + 1], "%Y-%m-%dT%H:%M:%S.000Z", tm);
286 link->time = mktime(tm);
287 FREE(tm);
288 continue;
289 }
290
291 if (!strcmp("size", attr[i])) {
292 link->content_length = strtoll(attr[i + 1], NULL, 10);
293 continue;
294 }
295
296 if (!strcmp("track", attr[i])) {
297 track = (int)strtol(attr[i + 1], NULL, 10);
298 continue;
299 }
300
301 if (!strcmp("title", attr[i])) {
302 title = (char *)attr[i + 1];
303 continue;
304 }
305
306 if (!strcmp("suffix", attr[i])) {
307 suffix = (char *)attr[i + 1];
308 continue;
309 }
310 }
311
312 if (!linkname_set && strnlen(title, PATH_MAX) > 0
313 && strnlen(suffix, PATH_MAX) > 0) {
314 snprintf(link->linkname, NAME_MAX + 1, "%02d - %s.%s", track, title,
315 suffix);
316 linkname_set = 1;
317 }
318
319 /*
320 * Clean up if linkname or id is not set
321 */
322 if (!linkname_set || !id_set) {
323 FREE(link);
324 return;
325 }
326
327 if (link->type == LINK_FILE) {
328 char *url = sonic_stream_link(link->sonic.id);
329 strncpy(link->f_url, url, PATH_MAX);
330 FREE(url);
331 }
332
333 LinkTable_add(linktbl, link);
334 }
335
336 static void sanitise_LinkTable(LinkTable *linktbl)
337 {
338 for (int i = 0; i < linktbl->size; i++) {
339 if (!strcmp(linktbl->links[i]->linkname, ".")) {
340 /* Note the super long sanitised name to avoid collision */
341 strcpy(linktbl->links[i]->linkname, "__DOT__");
342 }
343
344 if (!strcmp(linktbl->links[i]->linkname, "/")) {
345 /* Ditto */
346 strcpy(linktbl->links[i]->linkname, "__FORWARD-SLASH__");
347 }
348
349 for (size_t j = 0; linktbl->links[i]->linkname[j] != '\0'; j++) {
350 if (linktbl->links[i]->linkname[j] == '/') {
351 linktbl->links[i]->linkname[j] = '-';
352 }
353 }
354
355 if (linktbl->links[i]->next_table != NULL) {
356 sanitise_LinkTable(linktbl->links[i]->next_table);
357 }
358 }
359 }
360
361 /*
362 * LinkTable of the <index> element currently being parsed by
363 * XML_parser_id3_root() / XML_parser_id3_root_end(). The previous
364 * "last link added to root" heuristic mis-parents artists when an
365 * <index> produces no link or when elements arrive in an unexpected
366 * order. Track the parent explicitly via an end-element handler.
367 */
368 static LinkTable *id3_current_index_table = NULL;
369
370 static void XMLCALL XML_parser_id3_root(void *data, const char *elem,
371 const char **attr);
372
373 static void XMLCALL XML_parser_id3_root_end(void *data, const char *elem)
374 {
375 (void)data;
376 if (!strcmp(elem, "index")) {
377 id3_current_index_table = NULL;
378 }
379 }
380
381 /**
382 * \brief parse a XML string in order to fill in the LinkTable
383 */
384 static LinkTable *sonic_url_to_LinkTable(const char *url,
385 XML_StartElementHandler handler,
386 int depth)
387 {
388 LinkTable *linktbl = LinkTable_alloc(url);
389 linktbl->links[0]->sonic.depth = depth;
390
391 /*
392 * start downloading the base URL
393 */
394 TransferStruct xml = Link_download_full(linktbl->links[0]);
395 if (xml.curr_size == 0) {
396 LinkTable_free(linktbl);
397 return NULL;
398 }
399
400 XML_Parser parser = XML_ParserCreate(NULL);
401 XML_SetUserData(parser, linktbl);
402
403 XML_SetStartElementHandler(parser, handler);
404
405 if (handler == &XML_parser_id3_root) {
406 id3_current_index_table = NULL;
407 XML_SetEndElementHandler(parser, XML_parser_id3_root_end);
408 }
409
410 if (XML_Parse(parser, xml.data, xml.curr_size, 1) == XML_STATUS_ERROR) {
411 lprintf(error, "Parse error at line %lu: %s\n",
412 XML_GetCurrentLineNumber(parser),
413 XML_ErrorString(XML_GetErrorCode(parser)));
414 }
415
416 XML_ParserFree(parser);
417 id3_current_index_table = NULL;
418
419 FREE(xml.data);
420
421 LinkTable_print(linktbl);
422
423 sanitise_LinkTable(linktbl);
424
425 return linktbl;
426 }
427
428 LinkTable *sonic_LinkTable_new_index(const char *id)
429 {
430 char *url;
431 if (strcmp(id, "0") != 0) {
432 url = sonic_getMusicDirectory_link(id);
433 } else {
434 url = sonic_gen_url_first_part("getIndexes");
435 }
436 LinkTable *linktbl = sonic_url_to_LinkTable(url, XML_parser_general, 0);
437 FREE(url);
438 return linktbl;
439 }
440
441 static void XMLCALL XML_parser_id3_root(void *data, const char *elem,
442 const char **attr)
443 {
444 if (!strcmp(elem, "error")) {
445 lprintf(error, "\n");
446 for (int i = 0; attr[i]; i += 2) {
447 lprintf(error, "%s: %s\n", attr[i], attr[i + 1]);
448 }
449 }
450
451 LinkTable *root_linktbl = (LinkTable *)data;
452
453 int id_set = 0;
454 int linkname_set = 0;
455 Link *link;
456 if (!strcmp(elem, "index")) {
457 /*
458 * Add a subdirectory
459 */
460 link = CALLOC(1, sizeof(Link));
461 link->type = LINK_DIR;
462 for (int i = 0; attr[i]; i += 2) {
463 if (!strcmp("name", attr[i])) {
464 strncpy(link->linkname, attr[i + 1], NAME_MAX);
465 linkname_set = 1;
466 /*
467 * Allocate a new LinkTable
468 */
469 link->next_table = LinkTable_alloc("/");
470 }
471 }
472 /*
473 * Make sure we don't add an empty directory
474 */
475 if (linkname_set) {
476 LinkTable_add(root_linktbl, link);
477 id3_current_index_table = link->next_table;
478 } else {
479 FREE(link);
480 }
481 return;
482 } else if (!strcmp(elem, "artist")) {
483 if (!id3_current_index_table) {
484 lprintf(warning, "Ignoring <artist> outside of any <index>\n");
485 return;
486 }
487 link = CALLOC(1, sizeof(Link));
488 link->type = LINK_DIR;
489 /*
490 * The new table should be a level 3 album table
491 */
492 link->sonic.depth = 3;
493 for (int i = 0; attr[i]; i += 2) {
494 if (!strcmp("name", attr[i])) {
495 strncpy(link->linkname, attr[i + 1], NAME_MAX);
496 linkname_set = 1;
497 continue;
498 }
499
500 if (!strcmp("id", attr[i])) {
501 link->sonic.id = CALLOC(NAME_MAX + 1, sizeof(char));
502 strncpy(link->sonic.id, attr[i + 1], NAME_MAX);
503 id_set = 1;
504 continue;
505 }
506 }
507
508 /*
509 * Clean up if linkname is not set
510 */
511 if (!linkname_set || !id_set) {
512 if (link->sonic.id) {
513 FREE(link->sonic.id);
514 }
515
516 FREE(link);
517 return;
518 }
519
520 LinkTable_add(id3_current_index_table, link);
521 }
522 /*
523 * If we reach here, then this element does not contain directory structural
524 * information
525 */
526 }
527
528 LinkTable *sonic_LinkTable_new_id3(int depth, const char *id)
529 {
530 char *url;
531 LinkTable *linktbl = NULL;
532 switch (depth) {
533 /*
534 * Root table
535 */
536 case 0:
537 url = sonic_gen_url_first_part("getArtists");
538 linktbl = sonic_url_to_LinkTable(url, XML_parser_id3_root, 0);
539 FREE(url);
540 break;
541 /*
542 * Album table - get all the albums of an artist
543 */
544 case 3:
545 url = sonic_getArtist_link(id);
546 linktbl = sonic_url_to_LinkTable(url, XML_parser_general, depth);
547 FREE(url);
548 break;
549 /*
550 * Song table - get all the songs of an album
551 */
552 case 4:
553 url = sonic_getAlbum_link(id);
554 linktbl = sonic_url_to_LinkTable(url, XML_parser_general, depth);
555 FREE(url);
556 break;
557 default:
558 /*
559 * We shouldn't reach here.
560 */
561 lprintf(fatal, "case %d.\n", depth);
562 break;
563 }
564
565 return linktbl;
566 }