-
Notifications
You must be signed in to change notification settings - Fork 2
/
spshell_posix.c
503 lines (417 loc) · 11.5 KB
/
spshell_posix.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/** This file is part of SpotifyWebApi - <[email protected]> ===
*
* Copyright 2011,Hugo Lindström <[email protected]>
*
*
* Inspiration and reused functions has come from Spotifys spshell example
* and that code is:
* Copyright (c) 2006-2010 Spotify Ltd
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <signal.h>
#include "spshell.h"
#include <locale.h>
// Replace
extern char* replace(const char *const original, const char *const pattern, const char *const replacement);
/* Provide clock_gettime() emulation using gettimeofday on OSX */
#ifdef __APPLE__
#define CLOCK_REALTIME 0
int clock_gettime(int clkid, struct timespec *ts)
{
struct timeval tv;
int ret = gettimeofday(&tv, 0);
(void)clkid;
TIMEVAL_TO_TIMESPEC(&tv, ts);
return ret;
}
#else
#include <wait.h>
#endif
#include "cmd.h"
#ifdef USE_MYSQL
#include "mysql.h"
#endif
#include <ctype.h>
/// Set when libspotify want to process events
static int notify_events;
/// Synchronization mutex to protect various shared data
static pthread_mutex_t notify_mutex;
/// Synchronization condition variable for the main thread
static pthread_cond_t notify_cond;
/// Synchronization condition variable to disable prompt temporarily
static pthread_cond_t prompt_cond;
/// Command line to execute
static char *request;
static int wait_for_cmd;
extern int is_logged_out;
/// MYSQL related
#ifdef USE_MYSQL
extern MYSQL *mysql_connect();
extern int _mysql_close(MYSQL *);
#endif
/**
* Sighandler
*/
void sigcleaner(int s)
{
while(wait(NULL) > 0);
}
void sigchld_handler(int s)
{
sp_session_logout(g_session);
sp_session_release(g_session);
#ifdef USE_MYSQL
_mysql_close(g_conn);
#endif
printf("Exiting...\n,");
exit(s);
}
/* Converts a hex character to its integer value */
char from_hex(char ch) {
return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}
/* Returns a url-decoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
char *url_decode(char *str)
{
char *pstr = str, *buf = malloc(strlen(str) + 1), *pbuf = buf;
while (*pstr) {
if (*pstr == '%')
{
if (pstr[1] && pstr[2])
{
*pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
pstr += 2;
}
}
else if (*pstr == '+')
{
*pbuf++ = ' ';
}
else
{
*pbuf++ = *pstr;
}
pstr++;
}
*pbuf = '\0';
return buf;
}
/**
* socketreciver waits for a new request and
* executes it.
*/
static void *socketreciver(void *sock)
{
pthread_mutex_lock(¬ify_mutex);
int *sockfd = (int*)&sock;
while(1)
{
while(wait_for_cmd == 0)
pthread_cond_wait(&prompt_cond, ¬ify_mutex);
pthread_mutex_unlock(¬ify_mutex);
struct sockaddr_in client;
char buf[BUF_SIZE] = "";
char method[BUF_SIZE] = "";
char url[BUF_SIZE] = "";
char protocol[BUF_SIZE] = "";
socklen_t len;
memset(&client, 0, sizeof(client));
len = sizeof client;
if ((newfd = accept(*sockfd, (struct sockaddr *)&client, &len)) < 0)
{
perror("accept");
exit(EXIT_FAILURE);
}
if (recv(newfd, buf, sizeof(buf), 0) < 0)
{
perror("recv");
exit(EXIT_FAILURE);
}
if( buf != NULL )
{
if ( sscanf ( buf, "%s %s %s", method, url, protocol ) != 1 )
{
if( ( strcmp( method, "GET" ) == 0 ) && ( strcmp( url, "/favicon.ico" ) != 0 ) )
{
//printf("%s %s %s\n",protocol, method, url);
#ifdef USE_MYSQL
_mysql_updateStats(g_conn, "globalHit");
#endif
pthread_mutex_lock(¬ify_mutex);
wait_for_cmd = 0;
request = replace(url_decode( url ), "/", " ");
//printf("request: %s\n",request);
pthread_cond_signal(¬ify_cond);
}
}
}
}
return NULL;
}
/**
*
*/
long startListner()
{
int port;
if(!DPORT)
port = PORT;
else
port = DPORT;
long socketfd;
/// clean all the dead processes
struct sigaction sa;
sa.sa_handler = sigcleaner;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if(sigaction(SIGCHLD, &sa, NULL) == -1){
perror("Server-sigaction() error");
exit(1);
}
printf("Listening on port %d\n", port);
if ((socketfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
exit(EXIT_FAILURE);
}
/// Set the socket and reuse
int opt = 1;
if (setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
{
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
/// Setting server ip
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
/// Bind the port
if (bind(socketfd, (struct sockaddr *) &server, sizeof(server)) < 0)
{
perror("bind");
exit(EXIT_FAILURE);
}
/// And also listen
if (listen(socketfd, SOMAXCONN) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
return socketfd;
}
/**
*
*/
void start_recv(void)
{
static pthread_t id;
long socketfd;
if (id)
return;
/// Start the listner
socketfd = startListner();
wait_for_cmd = 1;
pthread_create(&id, NULL, socketreciver, (void*)socketfd);
}
/**
*
*/
int main(int argc, char **argv)
{
/// @todo, Implement Verbose and Debug options
/// Currently supports setting custom port, -p PORT
opterr = 0;
int c;
while ((c = getopt (argc, argv, "p:")) != -1)
{
switch (c)
{
case 'p':
DPORT = atoi(optarg);
break;
case '?':
if (optopt == 'p')
fprintf (stderr, "Option -%c requires a port as argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
return 1;
default:
abort ();
}
}
/// clean all the dead processes
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = sigchld_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
if(sigaction(SIGINT, &sigIntHandler, NULL) == -1)
{
perror("Server-sigaction() error");
exit(1);
}
int r;
int next_timeout = 0;
pthread_mutex_init(¬ify_mutex, NULL);
pthread_cond_init(¬ify_cond, NULL);
pthread_cond_init(&prompt_cond, NULL);
if ((r = spshell_init(USERNAME, PASSWORD)) != 0)
exit(r);
pthread_mutex_lock(¬ify_mutex);
/// Mysql connection initatition
#ifdef USE_MYSQL
g_conn = _mysql_connect();
if(!g_conn)
{
printf("Failed to set mysql connection!\n");
exit(1);
}
#endif
while(!is_logged_out)
{
/// Release prompt
if (next_timeout == 0)
{
while(!notify_events && !request)
pthread_cond_wait(¬ify_cond, ¬ify_mutex);
}
else
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += next_timeout / 1000;
ts.tv_nsec += (next_timeout % 1000) * 1000000;
while(!notify_events && !request)
{
if(pthread_cond_timedwait(¬ify_cond, ¬ify_mutex, &ts))
break;
}
}
/// Process input from request
if(request)
{
char *l= request;
request = NULL;
pthread_mutex_unlock(¬ify_mutex);
cmd_exec_unparsed(l);
pthread_mutex_lock(¬ify_mutex);
free(l);
}
/// Process libspotify events
notify_events = 0;
pthread_mutex_unlock(¬ify_mutex);
do
{
sp_session_process_events(g_session, &next_timeout);
} while (next_timeout == 0);
pthread_mutex_lock(¬ify_mutex);
}
printf("Logged out\n");
sp_session_release(g_session);
#ifdef USE_MYSQL
if(g_conn)
_mysql_close(g_conn);
#endif
printf("Exiting...\n");
return 0;
}
/**
* setHeader(int code)
* set the header to respective err code
*/
char *setHeader(int code)
{
char *header;
switch(code)
{
case 200: header = STATUS_OK;
break;
case 400: header = STATUS_ERR;
break;
case 404: header = STATUS_CONTERR;
break;
case 503: header = STATUS_CONNERR;
break;
default: header = STATUS_NIMPL;
}
return header;
}
/**
* cmd_sendresponse(json_t *resp, int code);
* we need to send the response back to the httpd
*
*/
void cmd_sendresponse(json_t *json, int code)
{
char *response = json_dumps(json, JSON_COMPACT);
json_decref(json);
/// this is the child process
if(!fork())
{
int rc;
// Send HTTP Status header
char *header = setHeader(code);
send(newfd, header, strlen(header), 0);
// Send JSON Header
char *jsonheader = JSON;
send(newfd,jsonheader, strlen(jsonheader), 0);
// Send the Response
do
{
if(response != NULL)
{
rc = send(newfd, response, strlen(response),0);
if (rc == -1)
{
printf("Fail to send to server %s\n", strerror(errno));
break;
}
}
} while (rc <= 0);
close(newfd);
exit(0);
}
else
{
close(newfd);
}
}
/**
* Cmd done
* notifys that the commands is finnished, back to wait_for_cmd
*/
void cmd_done(void)
{
pthread_mutex_lock(¬ify_mutex);
wait_for_cmd = 1;
pthread_cond_signal(&prompt_cond);
pthread_mutex_unlock(¬ify_mutex);
}
/**
*
*/
void notify_main_thread(sp_session *session)
{
pthread_mutex_lock(¬ify_mutex);
notify_events = 1;
pthread_cond_signal(¬ify_cond);
pthread_mutex_unlock(¬ify_mutex);
}