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;
50 static void command_handler_sighandler(int s)
54 PARA_EMERG_LOG("terminating on signal %d\n", SIGTERM);
55 subcmd_should_die = true;
59 * Compute human readable vss status text.
61 * We can't call vss_playing() and friends here because those functions read
62 * the flags from the primary mmd structure, so calling them from command
63 * handler context would require to take the mmd lock. At the time the function
64 * is called we already took a copy of the mmd structure and want to use the
65 * flags value of the copy for computing the vss status text.
67 static char *vss_status_tohuman(unsigned int flags)
69 if (flags & VSS_PLAYING)
70 return para_strdup("playing");
72 return para_strdup("stopped");
73 return para_strdup("paused");
79 static char *vss_get_status_flags(unsigned int flags)
81 char *msg = alloc(5 * sizeof(char));
83 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
84 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
85 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
86 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
91 static unsigned get_status(struct misc_meta_data *nmmd, bool parser_friendly,
94 char *status, *flags; /* vss status info */
95 /* nobody updates our version of "now" */
96 long offset = (nmmd->offset + 500) / 1000;
97 struct timeval current_time;
98 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
100 /* report real status */
101 status = vss_status_tohuman(nmmd->vss_status_flags);
102 flags = vss_get_status_flags(nmmd->vss_status_flags);
103 clock_get_realtime(¤t_time);
105 * The calls to WRITE_STATUS_ITEM() below never fail because
106 * b->max_size is zero (unlimited), see \ref para_printf(). However,
107 * clang is not smart enough to prove this and complains nevertheless.
108 * Casting the return value to void silences clang.
110 (void)WRITE_STATUS_ITEM(&b, SI_status, "%s\n", status);
111 (void)WRITE_STATUS_ITEM(&b, SI_status_flags, "%s\n", flags);
112 (void)WRITE_STATUS_ITEM(&b, SI_offset, "%li\n", offset);
113 (void)WRITE_STATUS_ITEM(&b, SI_afs_mode, "%s\n", mmd->afs_mode_string);
114 (void)WRITE_STATUS_ITEM(&b, SI_stream_start, "%lu.%lu\n",
115 (long unsigned)nmmd->stream_start.tv_sec,
116 (long unsigned)nmmd->stream_start.tv_usec);
117 (void)WRITE_STATUS_ITEM(&b, SI_current_time, "%lu.%lu\n",
118 (long unsigned)current_time.tv_sec,
119 (long unsigned)current_time.tv_usec);
127 * Send a sideband packet through a blocking file descriptor.
129 * \param scc fd and crypto keys.
130 * \param buf The buffer to send.
131 * \param numbytes The size of \a buf.
132 * \param band The sideband designator of this packet.
133 * \param dont_free If true, never deallocate \a buf.
135 * The nonblock flag must be disabled for the file descriptor given by \a scc.
137 * Stream cipher encryption is automatically activated if necessary via the
138 * sideband transformation, depending on the value of \a band.
142 * \sa \ref send_sb_va().
144 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
145 int band, bool dont_free)
148 struct sb_context *sbc;
150 sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
151 struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
153 sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
155 ret = sb_get_send_buffers(sbc, iov);
156 ret = xwritev(scc->fd, iov, ret);
159 } while (sb_sent(sbc, ret) == false);
167 * Create a variable sized buffer and send it as a sideband packet.
169 * \param scc Passed to \ref send_sb.
170 * \param band See \ref send_sb.
171 * \param fmt The format string.
173 * \return The return value of the underlying call to \ref send_sb.
175 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
176 const char *fmt, ...)
183 ret = xvasprintf(&msg, fmt, ap);
185 return send_sb(scc, msg, ret, band, false);
189 * Send an error message to a client.
191 * \param cc Client info.
192 * \param err The (positive) error code.
194 * \return The return value of the underlying call to send_sb_va().
196 int send_strerror(struct command_context *cc, int err)
198 return send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err));
202 * Send an error context to a client,
204 * \param cc Client info.
205 * \param errctx The error context string.
207 * \return The return value of the underlying call to send_sb_va().
209 * This function frees the error context string after it was sent.
211 int send_errctx(struct command_context *cc, char *errctx)
217 ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", errctx);
222 static int check_sender_args(struct command_context *cc,
223 struct lls_parse_result *lpr, struct sender_command_data *scd)
226 const char * const subcmds[] = {SENDER_SUBCOMMANDS};
229 unsigned num_inputs = lls_num_inputs(lpr);
231 scd->sender_num = -1;
232 ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
234 send_errctx(cc, errctx);
237 arg = lls_input(0, lpr);
239 if (strcmp(senders[i]->name, arg) == 0)
242 return -E_COMMAND_SYNTAX;
244 arg = lls_input(1, lpr);
245 for (i = 0; i < NUM_SENDER_CMDS; i++)
246 if (!strcmp(subcmds[i], arg))
248 if (i == NUM_SENDER_CMDS)
249 return -E_COMMAND_SYNTAX;
251 if (!senders[scd->sender_num]->client_cmds[scd->cmd_num])
252 return -E_SENDER_CMD;
253 switch (scd->cmd_num) {
257 return -E_COMMAND_SYNTAX;
261 if (num_inputs != 3 || parse_cidr(lls_input(2, lpr), scd->host,
262 sizeof(scd->host), &scd->netmask) == NULL)
263 return -E_COMMAND_SYNTAX;
268 return -E_COMMAND_SYNTAX;
269 return parse_fec_url(lls_input(2, lpr), scd);
271 return -E_COMMAND_SYNTAX;
277 * Receive a sideband packet from a blocking file descriptor.
279 * \param scc fd and crypto keys.
280 * \param expected_band The expected band designator.
281 * \param max_size Passed to \ref sb_new_recv().
282 * \param result Body of the sideband packet is returned here.
284 * If \a expected_band is not \p SBD_ANY, the band designator of the received
285 * sideband packet is compared to \a expected_band and a mismatch is considered
290 int recv_sb(struct stream_cipher_context *scc,
291 enum sb_designator expected_band,
292 size_t max_size, struct iovec *result)
295 struct sb_context *sbc;
297 struct sb_buffer sbb;
298 sb_transformation trafo;
300 trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
302 sbc = sb_new_recv(max_size, trafo, scc->recv);
304 sb_get_recv_buffer(sbc, &iov);
305 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
310 ret = sb_received(sbc, ret, &sbb);
317 if (expected_band != SBD_ANY && sbb.band != expected_band)
326 static int com_sender(struct command_context *cc, struct lls_parse_result *lpr)
330 struct sender_command_data scd;
332 if (lls_num_inputs(lpr) == 0) {
335 ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
340 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
342 ret = check_sender_args(cc, lpr, &scd);
344 if (scd.sender_num < 0)
346 if (strcmp(lls_input(1, lpr), "status") == 0)
347 msg = senders[scd.sender_num]->status();
349 msg = senders[scd.sender_num]->help();
350 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
353 switch (scd.cmd_num) {
356 assert(senders[scd.sender_num]->resolve_target);
357 ret = senders[scd.sender_num]->resolve_target(lls_input(2, lpr),
363 for (i = 0; i < 10; i++) {
364 mutex_lock(mmd_mutex);
365 if (mmd->sender_cmd_data.cmd_num >= 0) {
366 /* another sender command is active, retry in 100ms */
367 struct timespec ts = {.tv_nsec = 100 * 1000 * 1000};
368 mutex_unlock(mmd_mutex);
369 nanosleep(&ts, NULL);
372 mmd->sender_cmd_data = scd;
373 mutex_unlock(mmd_mutex);
376 return (i < 10)? 1 : -E_LOCK;
378 EXPORT_SERVER_CMD_HANDLER(sender);
380 static int com_si(struct command_context *cc,
381 __a_unused struct lls_parse_result *lpr)
386 ut = daemon_get_uptime_str(now);
387 mutex_lock(mmd_mutex);
388 ret = xasprintf(&msg,
389 "up: %s\nplayed: %u\n"
392 "connections (active/accepted/total): %u/%u/%u\n"
393 "supported audio formats: %s\n",
397 mmd->active_connections,
400 AUDIO_FORMAT_HANDLERS
402 mutex_unlock(mmd_mutex);
404 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
406 EXPORT_SERVER_CMD_HANDLER(si);
408 static int com_version(struct command_context *cc, struct lls_parse_result *lpr)
413 if (SERVER_CMD_OPT_GIVEN(VERSION, VERBOSE, lpr))
414 len = xasprintf(&msg, "%s", version_text("server"));
416 len = xasprintf(&msg, "%s\n", version_single_line("server"));
417 return send_sb(&cc->scc, msg, len, SBD_OUTPUT, false);
419 EXPORT_SERVER_CMD_HANDLER(version);
421 /** These status items are cleared if no audio file is currently open. */
422 #define EMPTY_STATUS_ITEMS \
427 ITEM(attributes_bitmap) \
428 ITEM(attributes_txt) \
439 ITEM(seconds_total) \
452 ITEM(amplification) \
456 * Create a set of audio-file related status items with empty values. These are
457 * written to stat clients when no audio file is open.
459 static unsigned empty_status_items(bool parser_friendly, char **result)
465 len = xasprintf(&esi,
466 #define ITEM(x) "0004 %02x:\n"
469 #define ITEM(x) , (unsigned) SI_ ## x
474 len = xasprintf(&esi,
475 #define ITEM(x) "%s:\n"
478 #define ITEM(x) ,status_item_list[SI_ ## x]
485 #undef EMPTY_STATUS_ITEMS
487 static int com_stat(struct command_context *cc, struct lls_parse_result *lpr)
490 struct misc_meta_data tmp, *nmmd = &tmp;
492 bool parser_friendly = SERVER_CMD_OPT_GIVEN(STAT, PARSER_FRIENDLY,
494 uint32_t num = SERVER_CMD_UINT32_VAL(STAT, NUM, lpr);
495 const struct timespec ts = {.tv_sec = 50, .tv_nsec = 0};
497 para_sigaction(SIGINT, SIG_IGN);
498 para_sigaction(SIGUSR1, command_handler_sighandler);
499 para_sigaction(SIGTERM, command_handler_sighandler);
501 * Simply checking subcmd_should_die is racy because a signal may
502 * arrive after the check but before the subsequent call to sleep(3).
503 * If this happens, sleep(3) would not be interrupted by the signal.
504 * To avoid this we block SIGTERM here and allow it to arrive only
507 para_block_signal(SIGTERM);
511 * Copy the mmd structure to minimize the time we hold the mmd
514 mutex_lock(mmd_mutex);
516 mutex_unlock(mmd_mutex);
517 ret = get_status(nmmd, parser_friendly, &s);
518 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
521 if (nmmd->vss_status_flags & VSS_NEXT) {
523 ret = empty_status_items(parser_friendly, &esi);
524 ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
528 send_afs_status(cc, parser_friendly);
530 if (num > 0 && !--num)
532 sigemptyset(&set); /* empty set means: unblock all signals */
534 * pselect(2) allows to atomically unblock signals, then go to
535 * sleep. Calling sigprocmask(2) followed by sleep(3) would
536 * open a race window similar to the one described above.
538 pselect(1, NULL, NULL, NULL, &ts, &set);
539 if (subcmd_should_die)
541 ret = -E_SERVER_CRASH;
548 EXPORT_SERVER_CMD_HANDLER(stat);
550 static const char *aux_info_cb(unsigned cmd_num, bool verbose)
552 static char result[80];
553 unsigned perms = server_command_perms[cmd_num];
556 /* permissions: VSS_READ | VSS_WRITE */
557 sprintf(result, "permissions: %s",
558 server_command_perms_txt[cmd_num]);
560 result[0] = perms & AFS_READ? 'a' : '-';
561 result[1] = perms & AFS_WRITE? 'A' : '-';
562 result[2] = perms & VSS_READ? 'v' : '-';
563 result[3] = perms & VSS_WRITE? 'V' : '-';
569 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
574 bool long_help = SERVER_CMD_OPT_GIVEN(HELP, LONG, lpr);
576 lsu_com_help(long_help, lpr, server_cmd_suite, aux_info_cb, &buf, &n);
577 ret = send_sb(&cc->scc, buf, n, SBD_OUTPUT, false);
580 EXPORT_SERVER_CMD_HANDLER(help);
582 static int com_hup(__a_unused struct command_context *cc,
583 __a_unused struct lls_parse_result *lpr)
585 kill(getppid(), SIGHUP);
588 EXPORT_SERVER_CMD_HANDLER(hup);
590 static int com_ll(struct command_context *cc, struct lls_parse_result *lpr)
594 const char *sev[] = {SEVERITIES}, *arg;
595 int ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
598 send_errctx(cc, errctx);
601 if (lls_num_inputs(lpr) == 0) { /* reporting is an unprivileged op. */
602 const char *severity;
603 mutex_lock(mmd_mutex);
604 severity = sev[mmd->loglevel];
605 mutex_unlock(mmd_mutex);
606 return send_sb_va(&cc->scc, SBD_OUTPUT, "%s\n", severity);
609 * Changing the loglevel changes the state of both the afs and the vss,
610 * so we require both AFS_WRITE and VSS_WRITE.
612 perms = AFS_WRITE | VSS_WRITE;
613 if ((cc->u->perms & perms) != perms)
614 return -ERRNO_TO_PARA_ERROR(EPERM);
615 arg = lls_input(0, lpr);
616 for (ll = 0; ll < NUM_LOGLEVELS; ll++)
617 if (!strcmp(arg, sev[ll]))
619 if (ll >= NUM_LOGLEVELS)
620 return -ERRNO_TO_PARA_ERROR(EINVAL);
621 PARA_INFO_LOG("new log level: %s\n", sev[ll]);
622 /* Ask the server and afs processes to adjust their log level. */
623 mutex_lock(mmd_mutex);
625 mutex_unlock(mmd_mutex);
628 EXPORT_SERVER_CMD_HANDLER(ll);
630 static int com_term(__a_unused struct command_context *cc,
631 __a_unused struct lls_parse_result *lpr)
634 * The server catches SIGTERM and propagates this signal to all its
635 * children. We are about to exit anyway, but we'd leak tons of memory
636 * if being terminated by the signal. So we ignore the signal here and
637 * terminate via the normal exit path, deallocating all memory.
639 para_sigaction(SIGTERM, SIG_IGN);
640 kill(getppid(), SIGTERM);
643 EXPORT_SERVER_CMD_HANDLER(term);
645 static int com_play(__a_unused struct command_context *cc,
646 __a_unused struct lls_parse_result *lpr)
648 mutex_lock(mmd_mutex);
649 mmd->new_vss_status_flags |= VSS_PLAYING;
650 mmd->new_vss_status_flags &= ~VSS_NOMORE;
651 mutex_unlock(mmd_mutex);
654 EXPORT_SERVER_CMD_HANDLER(play);
656 static int com_stop(__a_unused struct command_context *cc,
657 __a_unused struct lls_parse_result *lpr)
659 mutex_lock(mmd_mutex);
660 mmd->new_vss_status_flags &= ~VSS_PLAYING;
661 mmd->new_vss_status_flags &= ~VSS_REPOS;
662 mmd->new_vss_status_flags |= VSS_NEXT;
663 mutex_unlock(mmd_mutex);
666 EXPORT_SERVER_CMD_HANDLER(stop);
668 static int com_pause(__a_unused struct command_context *cc,
669 __a_unused struct lls_parse_result *lpr)
671 mutex_lock(mmd_mutex);
672 if (!vss_paused() && !vss_stopped()) {
674 mmd->new_vss_status_flags &= ~VSS_PLAYING;
675 mmd->new_vss_status_flags &= ~VSS_NEXT;
677 mutex_unlock(mmd_mutex);
680 EXPORT_SERVER_CMD_HANDLER(pause);
682 static int com_next(__a_unused struct command_context *cc,
683 __a_unused struct lls_parse_result *lpr)
685 mutex_lock(mmd_mutex);
687 mmd->new_vss_status_flags |= VSS_NEXT;
688 mutex_unlock(mmd_mutex);
691 EXPORT_SERVER_CMD_HANDLER(next);
693 static int com_nomore(__a_unused struct command_context *cc,
694 __a_unused struct lls_parse_result *lpr)
696 mutex_lock(mmd_mutex);
697 if (vss_playing() || vss_paused())
698 mmd->new_vss_status_flags |= VSS_NOMORE;
699 mutex_unlock(mmd_mutex);
702 EXPORT_SERVER_CMD_HANDLER(nomore);
704 static int com_ff(struct command_context *cc, struct lls_parse_result *lpr)
710 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
712 send_errctx(cc, errctx);
715 ret = para_atoi32(lls_input(0, lpr), &i);
717 if (ret != -E_ATOI_JUNK_AT_END)
720 * Compatibility code to keep the historic syntax (ff 30-)
721 * working. This can be removed after 0.7.0.
723 ret = sscanf(lls_input(0, lpr), "%i%c", &i, &c);
725 return -E_COMMAND_SYNTAX;
726 if (ret > 1 && c == '-') {
727 PARA_WARNING_LOG("use of obsolete syntax\n");
731 mutex_lock(mmd_mutex);
732 ret = -E_NO_AUDIO_FILE;
733 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
736 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
738 * We need this cast because without it the expression on the right
739 * hand side is of unsigned type.
741 promille += 1000 * i / (int)mmd->afd.afhi.seconds_total;
744 if (promille > 1000) {
745 mmd->new_vss_status_flags |= VSS_NEXT;
748 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
749 mmd->new_vss_status_flags |= VSS_REPOS;
750 mmd->new_vss_status_flags &= ~VSS_NEXT;
753 mutex_unlock(mmd_mutex);
756 EXPORT_SERVER_CMD_HANDLER(ff);
758 static int com_jmp(struct command_context *cc, struct lls_parse_result *lpr)
763 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
765 send_errctx(cc, errctx);
768 if (sscanf(lls_input(0, lpr), "%d", &i) <= 0)
769 return -ERRNO_TO_PARA_ERROR(EINVAL);
770 if (i < 0 || i > 100)
771 return -ERRNO_TO_PARA_ERROR(EINVAL);
772 mutex_lock(mmd_mutex);
773 ret = -E_NO_AUDIO_FILE;
774 if (!mmd->afd.afhi.chunks_total)
776 PARA_INFO_LOG("jumping to %d%%\n", i);
777 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
778 mmd->new_vss_status_flags |= VSS_REPOS;
779 mmd->new_vss_status_flags &= ~VSS_NEXT;
783 mutex_unlock(mmd_mutex);
786 EXPORT_SERVER_CMD_HANDLER(jmp);
788 static void reset_signals(void)
790 para_sigaction(SIGCHLD, SIG_IGN);
791 para_sigaction(SIGINT, SIG_DFL);
792 para_sigaction(SIGTERM, SIG_DFL);
793 para_sigaction(SIGHUP, SIG_DFL);
796 struct connection_features {
797 bool sha256_requested; /* can be removed after 0.7.0 */
800 static int parse_auth_request(char *buf, int len, const struct user **u,
801 struct connection_features *cf)
804 char *p, *username, **features = NULL;
805 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
808 memset(cf, 0, sizeof(*cf));
809 if (len < auth_rq_len + 2)
810 return -E_AUTH_REQUEST;
811 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
812 return -E_AUTH_REQUEST;
813 username = buf + auth_rq_len;
814 p = strchr(username, ' ');
818 return -E_AUTH_REQUEST;
821 create_argv(p, ",", &features);
823 * Still accept sideband and AES feature requests (as a no-op)
824 * because some 0.6.x clients request them. The two checks
825 * below may be removed after 0.7.1.
827 for (i = 0; features[i]; i++) {
828 if (strcmp(features[i], "sideband") == 0)
830 if (strcmp(features[i], "aes_ctr128") == 0)
833 * ->sha256_requested can go away after 0.7.0 but the
834 * check has to stay until 0.9.0.
836 if (strcmp(features[i], "sha256") == 0)
837 cf->sha256_requested = true;
839 ret = -E_BAD_FEATURE;
844 PARA_DEBUG_LOG("received auth request for user %s\n", username);
845 *u = user_list_lookup(username);
852 #define HANDSHAKE_BUFSIZE 4096
854 static int run_command(struct command_context *cc, struct iovec *iov)
857 char *p, *end, **argv;
858 const struct lls_command *lcmd = NULL;
860 struct lls_parse_result *lpr;
863 if (iov->iov_base == NULL || iov->iov_len == 0)
864 return -ERRNO_TO_PARA_ERROR(EINVAL);
866 p[iov->iov_len - 1] = '\0'; /* just to be sure */
868 ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
870 send_errctx(cc, errctx);
873 perms = server_command_perms[ret];
874 if ((perms & cc->u->perms) != perms)
875 return -ERRNO_TO_PARA_ERROR(EPERM);
876 lcmd = lls_cmd(ret, server_cmd_suite);
877 end = iov->iov_base + iov->iov_len;
878 for (i = 0; p < end; i++)
881 argv = arr_alloc(argc + 1, sizeof(char *));
882 for (i = 0, p = iov->iov_base; p < end; i++) {
883 argv[i] = para_strdup(p);
887 PARA_NOTICE_LOG("calling com_%s() for user %s\n",
888 lls_command_name(lcmd), cc->u->name);
889 ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
891 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
892 ret = ud->handler(cc, lpr);
893 lls_free_parse_result(lpr, lcmd);
895 send_errctx(cc, errctx);
897 mutex_lock(mmd_mutex);
899 if (ret >= 0 && (perms & AFS_WRITE))
901 mutex_unlock(mmd_mutex);
906 * Perform user authentication and execute a command.
908 * \param fd The file descriptor to send output to.
910 * Whenever para_server accepts an incoming tcp connection on the port it
911 * listens on, it forks and the resulting child calls this function.
913 * An RSA-based challenge/response is used to authenticate the peer. If the
914 * authentication succeeds, a random session key is generated and sent back to
915 * the peer, encrypted with its RSA public key. From this point on, all
916 * transfers are encrypted with this session key using a stream cipher.
918 * Next it is checked if the peer supplied a valid server command or a command
919 * for the audio file selector. If yes, and if the user has sufficient
920 * permissions to execute this command, the function calls the corresponding
921 * command handler which performs argument checking and further processing.
923 * To cope with DOS attacks, a timer is set up right after the fork. If the
924 * connection was still not authenticated when the timeout expires, the child
925 * process is terminated.
929 * \sa alarm(2), \ref openssl.c, \ref crypt.h.
931 int handle_connect(int fd)
934 unsigned char rand_buf[APC_CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
935 unsigned char challenge_hash[HASH2_SIZE];
936 char *command = NULL, *buf = alloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
938 struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
940 struct connection_features cf;
944 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
945 ret = mark_fd_blocking(fd);
948 /* send Welcome message */
949 ret = write_va_buffer(fd, "This is para_server, version "
950 PACKAGE_VERSION ".\n"
951 "Features: sha256\n" /* no longer announce this after 0.8.0 */
955 /* recv auth request line */
956 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
959 ret = parse_auth_request(buf, ret, &cc->u, &cf);
963 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
964 ret = apc_pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
965 (unsigned char *)buf);
971 * We don't want to reveal our user names, so we send a
972 * challenge to the client even if the user does not exist, and
973 * fail the authentication later.
976 get_random_bytes_or_die((unsigned char *)buf, numbytes);
978 PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
979 APC_CHALLENGE_SIZE, numbytes);
980 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
984 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
985 HANDSHAKE_BUFSIZE, &iov);
989 numbytes = iov.iov_len;
990 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
995 * The correct response is the hash of the first APC_CHALLENGE_SIZE bytes
996 * of the random data.
999 if (cf.sha256_requested) {
1000 if (numbytes != HASH2_SIZE)
1002 hash2_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
1003 if (memcmp(challenge_hash, buf, HASH2_SIZE))
1005 } else { /* old client. This can be removed after 0.7.0 */
1006 if (numbytes != HASH_SIZE)
1008 hash_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
1009 if (memcmp(challenge_hash, buf, HASH_SIZE))
1012 /* auth successful */
1014 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1015 /* init stream cipher keys with the second part of the random buffer */
1016 cc->scc.recv = sc_new(rand_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
1017 cc->scc.send = sc_new(rand_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
1019 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1022 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1025 ret = run_command(cc, &iov);
1032 if (send_strerror(cc, -ret) >= 0)
1033 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1035 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1039 mutex_lock(mmd_mutex);
1040 mmd->active_connections--;
1041 mutex_unlock(mmd_mutex);
1043 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1045 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1047 sc_free(cc->scc.recv);
1048 sc_free(cc->scc.send);