-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
517 lines (439 loc) · 11.9 KB
/
main.cpp
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/* This file is part of pas.
pas is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pas is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with pas. If not, see <http://www.gnu.org/licenses/>.
*/
/* pas is Copyright 2017 by Perry Kivolowitz.
*/
#include <iostream>
#include <string>
#include <ctime>
#include <sstream>
#include <iomanip>
#include <arpa/inet.h>
#include <getopt.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <vector>
#include "commands.pb.h"
using namespace std;
using namespace pas;
#define WHERE __FUNCTION__ << " " << __LINE__ << " "
#define MAX_DACS 1
int listening_socket = -1;
bool keep_going = true;
bool network_diagnostics = false;
string unknown_message;
string invalid_device;
string internal_error;
int port = 5077;
string TimeCode()
{
time_t t = time(nullptr);
tm * tx = localtime(&t);
stringstream ss;
ss << setfill('0') << setw(2) << tx->tm_hour << ":";
ss << setw(2) << tx->tm_min << ":";
ss << setw(2) << tx->tm_sec;
return ss.str();
}
bool CheckDevice(int device)
{
return device >= 0 && device < MAX_DACS;
}
void SIGINTHandler(int)
{
cout << endl << WHERE << "signal caught - setting keep_going to false" << endl;
keep_going = false;
}
void GetOptions(int argc, char* argv[])
{
int opt;
while ((opt = getopt(argc, argv, "dp:")) != -1) {
switch (opt) {
case 'd':
cout << "netword diagnostics turned on" << endl;
network_diagnostics = true;
break;
case 'p':
port = atoi(optarg);
cout << WHERE << "port set to: " << optarg << endl;
break;
}
}
}
bool SendPB(string & s, int server_socket)
{
// NOTE:
// NOTE: length must be an unsigned int because size_t can be 64 bits
// NOTE: or 32 bits. unsigned int is always 32 bits.
// NOTE:
unsigned int length = (unsigned int) s.size();
unsigned int ll = length;
length = htonl(length);
size_t bytes_sent;
if ((bytes_sent = send(server_socket, (const void *) &length, sizeof(length), 0)) != sizeof(length)) {
cout << WHERE << "bad bytes_sent for length: " << strerror(errno) << endl;
return false;
}
if ((bytes_sent = send(server_socket, (const void *) s.data(), ll, 0)) != ll) {
cout << WHERE << "bad bytes_sent for message: " << strerror(errno) << endl;
return false;
}
return true;
}
bool OneInteger_OneIntegerReply(string & in, int socket)
{
bool rv = false;
OneInteger o;
OneInteger outi;
OneString outs;
string output;
if (o.ParseFromString(in)) {
switch (o.type())
{
case ARTIST_COUNT:
case TRACK_COUNT:
outi.set_type(ONE_INT);
outi.set_value(1);
if (outi.SerializeToString(&output)) {
if (SendPB(output, socket)) {
cout << WHERE << "sent 1 as count." << endl;
rv = true;
}
}
else {
cout << WHERE << "failed to serialize response." << endl;
}
break;
case WHO_DEVICE:
case WHAT_DEVICE:
case WHEN_DEVICE:
if (!CheckDevice(o.value())) {
if (SendPB(invalid_device, socket)) {
cout << WHERE << "sent invalid device: " << o.value() << endl;
rv = true;
break;
}
}
outs.set_type(ONE_STRING);
if (o.type() == WHO_DEVICE)
outs.set_value("The Who");
else if (o.type() == WHAT_DEVICE)
outs.set_value("The What");
else {
outs.set_value(TimeCode());
}
if (!outs.SerializeToString(&output)) {
cout << WHERE << "failed to serialize response." << endl;
SendPB(internal_error, socket);
}
else if (SendPB(output, socket)) {
cout << WHERE << "relating to device: " << o.value() << " sent " << outs.value() << endl;
rv = true;
}
break;
default:
cout << WHERE << "should not get here ";
break;
}
rv = true;
}
return rv;
}
bool OneInteger_NoReply(string & in)
{
bool rv = false;
OneInteger o;
if (o.ParseFromString(in)) {
switch (o.type())
{
case CLEAR_DEVICE:
cout << "Clearing device: ";
break;
case NEXT_DEVICE:
cout << "Next track on device: ";
break;
case STOP_DEVICE:
cout << "Stopping device: ";
break;
case RESUME_DEVICE:
cout << "Resuming device: ";
break;
case PAUSE_DEVICE:
cout << "Pausing device: ";
break;
default:
cout << WHERE << " should not get here ";
break;
}
cout << o.value() << endl;
rv = true;
}
return rv;
}
bool TwoInteger_NoReply(string & in)
{
bool rv = false;
TwoIntegers o;
if (o.ParseFromString(in)) {
switch (o.type())
{
case PLAY_TRACK_DEVICE:
if (!CheckDevice(o.value_a())) {
cout << WHERE << "received play on invalid device: " << o.value_a() << " but no reply is being sent." << endl;
}
else {
cout << WHERE << "play track message received. Device: " << o.value_a() << " Track: " << o.value_b() << endl;
}
rv = true;
break;
default:
cout << WHERE << "should not get here." << endl;
break;
}
rv = true;
}
return rv;
}
bool DacInfoCommand(string & in, int socket)
{
bool rv = true;
string s;
SelectResult sr;
sr.set_type(SELECT_RESULT);
Row * r = sr.add_row();
r->set_type(ROW);
google::protobuf::Map<string, string> * result = r->mutable_results();
(*result)[string("index")] = "0";
(*result)[string("name")] = "Make Believe DAC";
(*result)[string("who")] = "The Who";
(*result)[string("what")] = "The What";
(*result)[string("when")] = TimeCode();
if (!sr.SerializeToString(&s)) {
cout << WHERE << "failed to serialize response." << endl;
s = internal_error;
rv = false;
}
else {
cout << WHERE << "sent a DAC_INFO_COMMAND response" << endl;
}
SendPB(s, socket);
return rv;
}
bool SelectCommand(string & in, int socket)
{
bool rv = true;
string s;
SelectResult sr;
sr.set_type(SELECT_RESULT);
Row * r = sr.add_row();
r->set_type(ROW);
google::protobuf::Map<string, string> * result = r->mutable_results();
(*result)[string("id")] = "100";
(*result)[string("fname")] = "fred.flac";
(*result)[string("namespace")] = "default";
(*result)[string("artist")] = "The Who";
(*result)[string("title")] = "The What";
(*result)[string("album")] = "Who's on First";
(*result)[string("genre")] = "Bad Music";
(*result)[string("source")] = "CD";
(*result)[string("duration")] = "00:03:00";
(*result)[string("publisher")] = "Random Hut";
(*result)[string("composer")] = "Mozer le' Poser";
(*result)[string("track")] = "6";
(*result)[string("copyright")] = "Poserworld";
(*result)[string("disc")] = "1";
if (!sr.SerializeToString(&s)) {
cout << WHERE << "failed to serialize response." << endl;
s = internal_error;
rv = false;
}
else {
cout << WHERE << "sent a SELECT_QUERY response" << endl;
}
SendPB(s, socket);
return rv;
}
bool CommandProcessor(int socket, string & in)
{
bool rv = false;
GenericPB g;
if (g.ParseFromString(in)) {
cout << WHERE << "received type: " << g.type() << endl;
switch (g.type())
{
// The OneIntegers that do not send a reply.
case CLEAR_DEVICE:
case NEXT_DEVICE:
case STOP_DEVICE:
case RESUME_DEVICE:
case PAUSE_DEVICE:
rv = OneInteger_NoReply(in);
break;
case TRACK_COUNT:
case ARTIST_COUNT:
case WHO_DEVICE:
case WHEN_DEVICE:
case WHAT_DEVICE:
rv = OneInteger_OneIntegerReply(in, socket);
break;
case PLAY_TRACK_DEVICE:
rv = TwoInteger_NoReply(in);
break;
case DAC_INFO_COMMAND:
rv = DacInfoCommand(in, socket);
break;
case SELECT_QUERY:
rv = SelectCommand(in, socket);
break;
default:
if (SendPB(unknown_message, socket)) {
cout << WHERE << "sent unknown message." << endl;
rv = true;
}
break;
}
}
else {
cout << WHERE << "failed to parse incoming message." << endl;
}
return rv;
}
void HandleConnection(int socket)
{
// NOTE:
// NOTE: length must be unsigned int rather than size_t as size_t
// NOTE: can vary - it can be 32 bits or 64 bits depending upon
// NOTE: the machine. unsigned int is always 32 bits.
// NOTE:
unsigned int length;
unsigned int ll;
size_t bytes_read;
while (keep_going) {
if ((bytes_read = recv(socket, (void*)&length, sizeof(length), MSG_WAITALL)) == sizeof(length)) {
ll = length;
length = ntohl(length);
cout << WHERE << "Length: " << length << " encoded as: " << hex << ll << dec << endl;
string incoming;
incoming.resize(length);
cout << WHERE << "size of incoming: " << incoming.size() << endl;
if ((bytes_read = recv(socket, (void*)&incoming[0], length, MSG_WAITALL)) == length) {
cout << WHERE << "received message of length: " << bytes_read << endl;
if (network_diagnostics && bytes_read < 64) {
for (size_t i = 0; i < 64 && i < length; i++) {
cout << setfill('0') << hex << "0x" << setw(2) << hex << (int)(((int) incoming.at(i)) & 0xFF) << " ";
if (i % 32 == 0 && i > 0)
cout << endl;
}
if (length % 32 != 0)
cout << endl;
cout << dec << setfill(' ');
}
if (!CommandProcessor(socket, incoming)) {
break;
}
}
else {
cout << WHERE << "failed to read message correctly: " << bytes_read << " " << strerror(errno) << endl;
if (network_diagnostics && bytes_read < 64) {
for (size_t i = 0; i < 64 && i < bytes_read; i++) {
cout << setfill('0') << hex << "0x" << setw(2) << hex << (int)(((int) incoming.at(i)) & 0xFF) << " ";
if (i % 32 == 0 && i > 0)
cout << endl;
}
if (bytes_read % 32 != 0)
cout << endl;
cout << dec << setfill(' ');
}
break;
}
}
else {
cout << WHERE << "failed to read length correctly: " << strerror(errno) << endl;
break;
}
}
}
void Serve()
{
int incoming_socket;
if ((listening_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
cout << WHERE << strerror(errno) << endl;
return;
}
int optval = 1;
if (setsockopt(listening_socket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) < 0) {
cout << WHERE << strerror(errno) << endl;
return;
}
sockaddr_in listening_sockaddr;
memset(&listening_sockaddr, 0, sizeof(sockaddr_in));
listening_sockaddr.sin_family = AF_INET;
listening_sockaddr.sin_port = htons(port);
listening_sockaddr.sin_addr.s_addr = INADDR_ANY;
if (bind(listening_socket, (sockaddr*)&listening_sockaddr, sizeof(sockaddr_in)) < 0) {
cout << WHERE << " " << strerror(errno) << endl;
return;
}
// Configure for handling at most one (1) client.
if (listen(listening_socket, 1) != 0) {
cout << WHERE << " " << strerror(errno) << endl;
return;
}
sockaddr_in client_info;
memset(&client_info, 0, sizeof(sockaddr_in));
int c = sizeof(sockaddr_in);
int connection_counter = 0;
cout << WHERE << "monitoring network." << endl;
while ((incoming_socket = accept(listening_socket, (sockaddr*)&client_info, (socklen_t*)&c)) > 0) {
cout << WHERE << "Connection: " << connection_counter << " established." << endl;
HandleConnection(incoming_socket);
cout << WHERE << "Connection: " << connection_counter << " taken down." << endl;
connection_counter++;
if (!keep_going)
break;
}
}
bool InitializeErrorMessages()
{
bool rv = true;
OneInteger o;
o.set_type(ERROR_MESSAGE);
o.set_value(UNKNOWN_MESSAGE);
if (!o.SerializeToString(&unknown_message))
rv = false;
o.set_value(INVALID_DEVICE);
if (!o.SerializeToString(&invalid_device))
rv = false;
o.set_value(INTERNAL_ERROR);
if (!o.SerializeToString(&internal_error))
rv = false;
return rv;
}
int main(int argc, char* argv[])
{
signal(SIGINT, SIGINTHandler);
siginterrupt(SIGINT, 1);
if (!InitializeErrorMessages()) {
cout << WHERE << "failed to initialize stock error messages." << endl;
return 1;
}
GetOptions(argc, argv);
Serve();
if (listening_socket >= 0)
close(listening_socket);
return 0;
}