1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file command.c Client authentication and server commands. */
5 #include <netinet/in.h>
6 #include <sys/socket.h>
30 #include "server_cmd.lsg.h"
31 #include "user_list.h"
35 #define SERVER_CMD_AUX_INFO(_arg) _arg,
36 static const unsigned server_command_perms[] = {LSG_SERVER_CMD_AUX_INFOS};
37 #undef SERVER_CMD_AUX_INFO
38 #define SERVER_CMD_AUX_INFO(_arg) #_arg,
39 static const char * const server_command_perms_txt[] = {LSG_SERVER_CMD_AUX_INFOS};
40 #undef SERVER_CMD_AUX_INFO
42 /** Commands including options must be shorter than this. */
43 #define MAX_COMMAND_LEN 32768
46 extern struct misc_meta_data *mmd;
47 int send_afs_status(struct command_context *cc, int parser_friendly);
48 static bool subcmd_should_die;
51 * Don't call PARA_XXX_LOG() here as we might already hold the log mutex. See
52 * generic_signal_handler() for details.
54 static void command_handler_sighandler(int s)
57 subcmd_should_die = true;
61 * Compute human readable vss status text.
63 * We can't call vss_playing() and friends here because those functions read
64 * the flags from the primary mmd structure, so calling them from command
65 * handler context would require to take the mmd lock. At the time the function
66 * is called we already took a copy of the mmd structure and want to use the
67 * flags value of the copy for computing the vss status text.
69 static char *vss_status_tohuman(unsigned int flags)
71 if (flags & VSS_PLAYING)
72 return para_strdup("playing");
74 return para_strdup("stopped");
75 return para_strdup("paused");
81 static char *vss_get_status_flags(unsigned int flags)
83 char *msg = alloc(5 * sizeof(char));
85 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
86 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
87 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
88 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
93 static unsigned get_status(struct misc_meta_data *nmmd, bool parser_friendly,
96 char *status, *flags; /* vss status info */
97 /* nobody updates our version of "now" */
98 long offset = (nmmd->offset + 500) / 1000;
99 struct timeval current_time;
100 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
102 /* report real status */
103 status = vss_status_tohuman(nmmd->vss_status_flags);
104 flags = vss_get_status_flags(nmmd->vss_status_flags);
105 clock_get_realtime(¤t_time);
107 * The calls to WRITE_STATUS_ITEM() below never fail because
108 * b->max_size is zero (unlimited), see \ref para_printf(). However,
109 * clang is not smart enough to prove this and complains nevertheless.
110 * Casting the return value to void silences clang.
112 (void)WRITE_STATUS_ITEM(&b, SI_status, "%s\n", status);
113 (void)WRITE_STATUS_ITEM(&b, SI_status_flags, "%s\n", flags);
114 (void)WRITE_STATUS_ITEM(&b, SI_offset, "%li\n", offset);
115 (void)WRITE_STATUS_ITEM(&b, SI_afs_mode, "%s\n", mmd->afs_mode_string);
116 (void)WRITE_STATUS_ITEM(&b, SI_stream_start, "%lu.%lu\n",
117 (long unsigned)nmmd->stream_start.tv_sec,
118 (long unsigned)nmmd->stream_start.tv_usec);
119 (void)WRITE_STATUS_ITEM(&b, SI_current_time, "%lu.%lu\n",
120 (long unsigned)current_time.tv_sec,
121 (long unsigned)current_time.tv_usec);
129 * Send a sideband packet through a blocking file descriptor.
131 * \param scc fd and crypto keys.
132 * \param buf The buffer to send.
133 * \param numbytes The size of \a buf.
134 * \param band The sideband designator of this packet.
135 * \param dont_free If true, never deallocate \a buf.
137 * The nonblock flag must be disabled for the file descriptor given by \a scc.
139 * Stream cipher encryption is automatically activated if necessary via the
140 * sideband transformation, depending on the value of \a band.
144 * \sa \ref send_sb_va().
146 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
147 int band, bool dont_free)
150 struct sb_context *sbc;
152 sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
153 struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
155 sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
157 ret = sb_get_send_buffers(sbc, iov);
158 ret = xwritev(scc->fd, iov, ret);
161 } while (sb_sent(sbc, ret) == false);
169 * Create a variable sized buffer and send it as a sideband packet.
171 * \param scc Passed to \ref send_sb.
172 * \param band See \ref send_sb.
173 * \param fmt The format string.
175 * \return The return value of the underlying call to \ref send_sb.
177 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
178 const char *fmt, ...)
185 ret = xvasprintf(&msg, fmt, ap);
187 return send_sb(scc, msg, ret, band, false);
191 * Send an error message to a client.
193 * \param cc Client info.
194 * \param err The (positive) error code.
196 * \return The return value of the underlying call to send_sb_va().
198 int send_strerror(struct command_context *cc, int err)
200 return send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err));
204 * Send an error context to a client,
206 * \param cc Client info.
207 * \param errctx The error context string.
209 * \return The return value of the underlying call to send_sb_va().
211 * This function frees the error context string after it was sent.
213 int send_errctx(struct command_context *cc, char *errctx)
219 ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", errctx);
224 static int check_sender_args(struct command_context *cc,
225 struct lls_parse_result *lpr, struct sender_command_data *scd)
228 const char * const subcmds[] = {SENDER_SUBCOMMANDS};
231 unsigned num_inputs = lls_num_inputs(lpr);
233 scd->sender_num = -1;
234 ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
236 send_errctx(cc, errctx);
239 arg = lls_input(0, lpr);
241 if (strcmp(senders[i]->name, arg) == 0)
244 return -E_COMMAND_SYNTAX;
246 arg = lls_input(1, lpr);
247 for (i = 0; i < NUM_SENDER_CMDS; i++)
248 if (!strcmp(subcmds[i], arg))
250 if (i == NUM_SENDER_CMDS)
251 return -E_COMMAND_SYNTAX;
253 if (!senders[scd->sender_num]->client_cmds[scd->cmd_num])
254 return -E_SENDER_CMD;
255 switch (scd->cmd_num) {
259 return -E_COMMAND_SYNTAX;
263 if (num_inputs != 3 || parse_cidr(lls_input(2, lpr), scd->host,
264 sizeof(scd->host), &scd->netmask) == NULL)
265 return -E_COMMAND_SYNTAX;
270 return -E_COMMAND_SYNTAX;
271 return parse_fec_url(lls_input(2, lpr), scd);
273 return -E_COMMAND_SYNTAX;
279 * Receive a sideband packet from a blocking file descriptor.
281 * \param scc fd and crypto keys.
282 * \param expected_band The expected band designator.
283 * \param max_size Passed to \ref sb_new_recv().
284 * \param result Body of the sideband packet is returned here.
286 * If \a expected_band is not \p SBD_ANY, the band designator of the received
287 * sideband packet is compared to \a expected_band and a mismatch is considered
292 int recv_sb(struct stream_cipher_context *scc,
293 enum sb_designator expected_band,
294 size_t max_size, struct iovec *result)
297 struct sb_context *sbc;
299 struct sb_buffer sbb;
300 sb_transformation trafo;
302 trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
304 sbc = sb_new_recv(max_size, trafo, scc->recv);
306 sb_get_recv_buffer(sbc, &iov);
307 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
312 ret = sb_received(sbc, ret, &sbb);
319 if (expected_band != SBD_ANY && sbb.band != expected_band)
328 static int com_sender(struct command_context *cc, struct lls_parse_result *lpr)
332 struct sender_command_data scd;
334 if (lls_num_inputs(lpr) == 0) {
337 ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
342 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
344 ret = check_sender_args(cc, lpr, &scd);
346 if (scd.sender_num < 0)
348 if (strcmp(lls_input(1, lpr), "status") == 0)
349 msg = senders[scd.sender_num]->status();
351 msg = senders[scd.sender_num]->help();
352 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
355 switch (scd.cmd_num) {
358 assert(senders[scd.sender_num]->resolve_target);
359 ret = senders[scd.sender_num]->resolve_target(lls_input(2, lpr),
365 for (i = 0; i < 10; i++) {
366 mutex_lock(mmd_mutex);
367 if (mmd->sender_cmd_data.cmd_num >= 0) {
368 /* another sender command is active, retry in 100ms */
369 struct timespec ts = {.tv_nsec = 100 * 1000 * 1000};
370 mutex_unlock(mmd_mutex);
371 nanosleep(&ts, NULL);
374 mmd->sender_cmd_data = scd;
375 mutex_unlock(mmd_mutex);
378 return (i < 10)? 1 : -E_LOCK;
380 EXPORT_SERVER_CMD_HANDLER(sender);
382 static int com_si(struct command_context *cc,
383 __a_unused struct lls_parse_result *lpr)
388 ut = daemon_get_uptime_str(now);
389 mutex_lock(mmd_mutex);
390 ret = xasprintf(&msg,
391 "up: %s\nplayed: %u\n"
394 "connections (active/accepted/total): %u/%u/%u\n"
395 "supported audio formats: %s\n",
399 mmd->active_connections,
402 AUDIO_FORMAT_HANDLERS
404 mutex_unlock(mmd_mutex);
406 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
408 EXPORT_SERVER_CMD_HANDLER(si);
410 static int com_version(struct command_context *cc, struct lls_parse_result *lpr)
415 if (SERVER_CMD_OPT_GIVEN(VERSION, VERBOSE, lpr))
416 len = xasprintf(&msg, "%s", version_text("server"));
418 len = xasprintf(&msg, "%s\n", version_single_line("server"));
419 return send_sb(&cc->scc, msg, len, SBD_OUTPUT, false);
421 EXPORT_SERVER_CMD_HANDLER(version);
423 /** These status items are cleared if no audio file is currently open. */
424 #define EMPTY_STATUS_ITEMS \
429 ITEM(attributes_bitmap) \
430 ITEM(attributes_txt) \
441 ITEM(seconds_total) \
454 ITEM(amplification) \
458 * Create a set of audio-file related status items with empty values. These are
459 * written to stat clients when no audio file is open.
461 static unsigned empty_status_items(bool parser_friendly, char **result)
467 len = xasprintf(&esi,
468 #define ITEM(x) "0004 %02x:\n"
471 #define ITEM(x) , (unsigned) SI_ ## x
476 len = xasprintf(&esi,
477 #define ITEM(x) "%s:\n"
480 #define ITEM(x) ,status_item_list[SI_ ## x]
487 #undef EMPTY_STATUS_ITEMS
489 static int com_stat(struct command_context *cc, struct lls_parse_result *lpr)
492 struct misc_meta_data tmp, *nmmd = &tmp;
494 bool parser_friendly = SERVER_CMD_OPT_GIVEN(STAT, PARSER_FRIENDLY,
496 uint32_t num = SERVER_CMD_UINT32_VAL(STAT, NUM, lpr);
497 const struct timespec ts = {.tv_sec = 50, .tv_nsec = 0};
499 para_sigaction(SIGINT, SIG_IGN);
500 para_sigaction(SIGUSR1, command_handler_sighandler);
501 para_sigaction(SIGTERM, command_handler_sighandler);
503 * Simply checking subcmd_should_die is racy because a signal may
504 * arrive after the check but before the subsequent call to sleep(3).
505 * If this happens, sleep(3) would not be interrupted by the signal.
506 * To avoid this we block SIGTERM here and allow it to arrive only
509 para_block_signal(SIGTERM);
510 para_block_signal(SIGUSR1);
514 * Copy the mmd structure to minimize the time we hold the mmd
517 mutex_lock(mmd_mutex);
519 mutex_unlock(mmd_mutex);
520 ret = get_status(nmmd, parser_friendly, &s);
521 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
524 if (nmmd->vss_status_flags & VSS_NEXT) {
526 ret = empty_status_items(parser_friendly, &esi);
527 ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
531 send_afs_status(cc, parser_friendly);
533 if (num > 0 && !--num)
535 sigemptyset(&set); /* empty set means: unblock all signals */
537 * pselect(2) allows to atomically unblock signals, then go to
538 * sleep. Calling sigprocmask(2) followed by sleep(3) would
539 * open a race window similar to the one described above.
541 pselect(1, NULL, NULL, NULL, &ts, &set);
542 if (subcmd_should_die) {
543 PARA_EMERG_LOG("terminating on SIGTERM\n");
546 ret = -E_SERVER_CRASH;
553 EXPORT_SERVER_CMD_HANDLER(stat);
555 static const char *aux_info_cb(unsigned cmd_num, bool verbose)
557 static char result[80];
558 unsigned perms = server_command_perms[cmd_num];
561 /* permissions: VSS_READ | VSS_WRITE */
562 sprintf(result, "permissions: %s",
563 server_command_perms_txt[cmd_num]);
565 result[0] = perms & AFS_READ? 'a' : '-';
566 result[1] = perms & AFS_WRITE? 'A' : '-';
567 result[2] = perms & VSS_READ? 'v' : '-';
568 result[3] = perms & VSS_WRITE? 'V' : '-';
574 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
579 bool long_help = SERVER_CMD_OPT_GIVEN(HELP, LONG, lpr);
581 lsu_com_help(long_help, lpr, server_cmd_suite, aux_info_cb, &buf, &n);
582 ret = send_sb(&cc->scc, buf, n, SBD_OUTPUT, false);
585 EXPORT_SERVER_CMD_HANDLER(help);
587 static int com_hup(__a_unused struct command_context *cc,
588 __a_unused struct lls_parse_result *lpr)
590 kill(getppid(), SIGHUP);
593 EXPORT_SERVER_CMD_HANDLER(hup);
595 static int com_ll(struct command_context *cc, struct lls_parse_result *lpr)
599 const char *sev[] = {SEVERITIES}, *arg;
600 int ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
603 send_errctx(cc, errctx);
606 if (lls_num_inputs(lpr) == 0) { /* reporting is an unprivileged op. */
607 const char *severity;
608 mutex_lock(mmd_mutex);
609 severity = sev[mmd->loglevel];
610 mutex_unlock(mmd_mutex);
611 return send_sb_va(&cc->scc, SBD_OUTPUT, "%s\n", severity);
614 * Changing the loglevel changes the state of both the afs and the vss,
615 * so we require both AFS_WRITE and VSS_WRITE.
617 perms = AFS_WRITE | VSS_WRITE;
618 if ((cc->u->perms & perms) != perms)
619 return -ERRNO_TO_PARA_ERROR(EPERM);
620 arg = lls_input(0, lpr);
621 for (ll = 0; ll < NUM_LOGLEVELS; ll++)
622 if (!strcmp(arg, sev[ll]))
624 if (ll >= NUM_LOGLEVELS)
625 return -ERRNO_TO_PARA_ERROR(EINVAL);
626 PARA_INFO_LOG("new log level: %s\n", sev[ll]);
627 /* Ask the server and afs processes to adjust their log level. */
628 mutex_lock(mmd_mutex);
630 mutex_unlock(mmd_mutex);
633 EXPORT_SERVER_CMD_HANDLER(ll);
635 static int com_term(__a_unused struct command_context *cc,
636 __a_unused struct lls_parse_result *lpr)
639 * The server catches SIGTERM and propagates this signal to all its
640 * children. We are about to exit anyway, but we'd leak tons of memory
641 * if being terminated by the signal. So we ignore the signal here and
642 * terminate via the normal exit path, deallocating all memory.
644 para_sigaction(SIGTERM, SIG_IGN);
645 kill(getppid(), SIGTERM);
648 EXPORT_SERVER_CMD_HANDLER(term);
650 static int com_play(__a_unused struct command_context *cc,
651 __a_unused struct lls_parse_result *lpr)
653 mutex_lock(mmd_mutex);
654 mmd->new_vss_status_flags |= VSS_PLAYING;
655 mmd->new_vss_status_flags &= ~VSS_NOMORE;
656 mutex_unlock(mmd_mutex);
659 EXPORT_SERVER_CMD_HANDLER(play);
661 static int com_stop(__a_unused struct command_context *cc,
662 __a_unused struct lls_parse_result *lpr)
664 mutex_lock(mmd_mutex);
665 mmd->new_vss_status_flags &= ~VSS_PLAYING;
666 mmd->new_vss_status_flags &= ~VSS_REPOS;
667 mmd->new_vss_status_flags |= VSS_NEXT;
668 mutex_unlock(mmd_mutex);
671 EXPORT_SERVER_CMD_HANDLER(stop);
673 static int com_pause(__a_unused struct command_context *cc,
674 __a_unused struct lls_parse_result *lpr)
676 mutex_lock(mmd_mutex);
677 if (!vss_paused() && !vss_stopped()) {
679 mmd->new_vss_status_flags &= ~VSS_PLAYING;
680 mmd->new_vss_status_flags &= ~VSS_NEXT;
682 mutex_unlock(mmd_mutex);
685 EXPORT_SERVER_CMD_HANDLER(pause);
687 static int com_next(__a_unused struct command_context *cc,
688 __a_unused struct lls_parse_result *lpr)
690 mutex_lock(mmd_mutex);
692 mmd->new_vss_status_flags |= VSS_NEXT;
693 mutex_unlock(mmd_mutex);
696 EXPORT_SERVER_CMD_HANDLER(next);
698 static int com_nomore(__a_unused struct command_context *cc,
699 __a_unused struct lls_parse_result *lpr)
701 mutex_lock(mmd_mutex);
702 if (vss_playing() || vss_paused())
703 mmd->new_vss_status_flags |= VSS_NOMORE;
704 mutex_unlock(mmd_mutex);
707 EXPORT_SERVER_CMD_HANDLER(nomore);
709 static int com_ff(struct command_context *cc, struct lls_parse_result *lpr)
715 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
717 send_errctx(cc, errctx);
720 ret = para_atoi32(lls_input(0, lpr), &i);
723 mutex_lock(mmd_mutex);
724 ret = -E_NO_AUDIO_FILE;
725 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
728 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
730 * We need this cast because without it the expression on the right
731 * hand side is of unsigned type.
733 promille += 1000 * i / (int)mmd->afd.afhi.seconds_total;
736 if (promille > 1000) {
737 mmd->new_vss_status_flags |= VSS_NEXT;
740 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
741 mmd->new_vss_status_flags |= VSS_REPOS;
742 mmd->new_vss_status_flags &= ~VSS_NEXT;
745 mutex_unlock(mmd_mutex);
748 EXPORT_SERVER_CMD_HANDLER(ff);
750 static int com_jmp(struct command_context *cc, struct lls_parse_result *lpr)
755 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
757 send_errctx(cc, errctx);
760 if (sscanf(lls_input(0, lpr), "%d", &i) <= 0)
761 return -ERRNO_TO_PARA_ERROR(EINVAL);
762 if (i < 0 || i > 100)
763 return -ERRNO_TO_PARA_ERROR(EINVAL);
764 mutex_lock(mmd_mutex);
765 ret = -E_NO_AUDIO_FILE;
766 if (!mmd->afd.afhi.chunks_total)
768 PARA_INFO_LOG("jumping to %d%%\n", i);
769 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
770 mmd->new_vss_status_flags |= VSS_REPOS;
771 mmd->new_vss_status_flags &= ~VSS_NEXT;
775 mutex_unlock(mmd_mutex);
778 EXPORT_SERVER_CMD_HANDLER(jmp);
780 static void reset_signals(void)
782 para_sigaction(SIGCHLD, SIG_IGN);
783 para_sigaction(SIGINT, SIG_DFL);
784 para_sigaction(SIGTERM, SIG_DFL);
785 para_sigaction(SIGHUP, SIG_DFL);
788 struct connection_features {
789 bool sha256_requested; /* can be removed after 0.7.0 */
792 static int parse_auth_request(char *buf, int len, const struct user **u,
793 struct connection_features *cf)
796 char *p, *username, **features = NULL;
797 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
800 memset(cf, 0, sizeof(*cf));
801 if (len < auth_rq_len + 2)
802 return -E_AUTH_REQUEST;
803 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
804 return -E_AUTH_REQUEST;
805 username = buf + auth_rq_len;
806 p = strchr(username, ' ');
810 return -E_AUTH_REQUEST;
813 create_argv(p, ",", &features);
815 * Still accept sideband and AES feature requests (as a no-op)
816 * because some 0.6.x clients request them. The two checks
817 * below may be removed after 0.7.1.
819 for (i = 0; features[i]; i++) {
820 if (strcmp(features[i], "sideband") == 0)
822 if (strcmp(features[i], "aes_ctr128") == 0)
825 * ->sha256_requested can go away after 0.7.0 but the
826 * check has to stay until 0.9.0.
828 if (strcmp(features[i], "sha256") == 0)
829 cf->sha256_requested = true;
831 ret = -E_BAD_FEATURE;
836 PARA_DEBUG_LOG("received auth request for user %s\n", username);
837 *u = user_list_lookup(username);
844 #define HANDSHAKE_BUFSIZE 4096
846 static int run_command(struct command_context *cc, struct iovec *iov)
849 char *p, *end, **argv;
850 const struct lls_command *lcmd = NULL;
852 struct lls_parse_result *lpr;
855 if (iov->iov_base == NULL || iov->iov_len == 0)
856 return -ERRNO_TO_PARA_ERROR(EINVAL);
858 p[iov->iov_len - 1] = '\0'; /* just to be sure */
860 ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
862 send_errctx(cc, errctx);
865 perms = server_command_perms[ret];
866 if ((perms & cc->u->perms) != perms)
867 return -ERRNO_TO_PARA_ERROR(EPERM);
868 lcmd = lls_cmd(ret, server_cmd_suite);
869 end = iov->iov_base + iov->iov_len;
870 for (i = 0; p < end; i++)
873 argv = arr_alloc(argc + 1, sizeof(char *));
874 for (i = 0, p = iov->iov_base; p < end; i++) {
875 argv[i] = para_strdup(p);
879 PARA_NOTICE_LOG("calling com_%s() for user %s\n",
880 lls_command_name(lcmd), cc->u->name);
881 ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
883 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
884 ret = ud->handler(cc, lpr);
885 lls_free_parse_result(lpr, lcmd);
887 send_errctx(cc, errctx);
889 mutex_lock(mmd_mutex);
891 if (ret >= 0 && (perms & AFS_WRITE))
893 mutex_unlock(mmd_mutex);
898 * Perform user authentication and execute a command.
900 * \param fd The file descriptor to send output to.
902 * Whenever para_server accepts an incoming tcp connection on the port it
903 * listens on, it forks and the resulting child calls this function.
905 * An RSA-based challenge/response is used to authenticate the peer. If the
906 * authentication succeeds, a random session key is generated and sent back to
907 * the peer, encrypted with its RSA public key. From this point on, all
908 * transfers are encrypted with this session key using a stream cipher.
910 * Next it is checked if the peer supplied a valid server command or a command
911 * for the audio file selector. If yes, and if the user has sufficient
912 * permissions to execute this command, the function calls the corresponding
913 * command handler which performs argument checking and further processing.
915 * To cope with DOS attacks, a timer is set up right after the fork. If the
916 * connection was still not authenticated when the timeout expires, the child
917 * process is terminated.
921 * \sa alarm(2), \ref openssl.c, \ref crypt.h.
923 int handle_connect(int fd)
926 unsigned char rand_buf[APC_CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
927 unsigned char challenge_hash[HASH2_SIZE];
928 char *command = NULL, *buf = alloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
930 struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
932 struct connection_features cf;
936 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
937 ret = mark_fd_blocking(fd);
940 /* send Welcome message */
941 ret = write_va_buffer(fd, "This is para_server, version "
942 PACKAGE_VERSION ".\n"
943 "Features: sha256\n" /* no longer announce this after 0.8.0 */
947 /* recv auth request line */
948 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
951 ret = parse_auth_request(buf, ret, &cc->u, &cf);
955 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
956 ret = apc_pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
957 (unsigned char *)buf);
963 * We don't want to reveal our user names, so we send a
964 * challenge to the client even if the user does not exist, and
965 * fail the authentication later.
968 get_random_bytes_or_die((unsigned char *)buf, numbytes);
970 PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
971 APC_CHALLENGE_SIZE, numbytes);
972 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
976 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
977 HANDSHAKE_BUFSIZE, &iov);
981 numbytes = iov.iov_len;
982 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
987 * The correct response is the hash of the first APC_CHALLENGE_SIZE bytes
988 * of the random data.
991 if (cf.sha256_requested) {
992 if (numbytes != HASH2_SIZE)
994 hash2_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
995 if (memcmp(challenge_hash, buf, HASH2_SIZE))
997 } else { /* old client. This can be removed after 0.7.0 */
998 if (numbytes != HASH_SIZE)
1000 hash_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
1001 if (memcmp(challenge_hash, buf, HASH_SIZE))
1004 /* auth successful */
1006 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1007 /* init stream cipher keys with the second part of the random buffer */
1008 cc->scc.recv = sc_new(rand_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
1009 cc->scc.send = sc_new(rand_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
1011 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1014 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1017 ret = run_command(cc, &iov);
1024 if (send_strerror(cc, -ret) >= 0)
1025 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1027 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1031 mutex_lock(mmd_mutex);
1032 mmd->active_connections--;
1033 mutex_unlock(mmd_mutex);
1035 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1037 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1039 sc_free(cc->scc.recv);
1040 sc_free(cc->scc.send);