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 /** \cond server_cmd_aux_info */
36 #define SERVER_CMD_AUX_INFO(_arg) _arg,
37 static const unsigned server_command_perms[] = {LSG_SERVER_CMD_AUX_INFOS};
38 #undef SERVER_CMD_AUX_INFO
39 #define SERVER_CMD_AUX_INFO(_arg) #_arg,
40 static const char * const server_command_perms_txt[] = {LSG_SERVER_CMD_AUX_INFOS};
41 #undef SERVER_CMD_AUX_INFO
42 /** \endcond server_cmd_aux_info */
44 /** Commands including options must be shorter than this. */
45 #define MAX_COMMAND_LEN 32768
48 extern struct misc_meta_data *mmd;
49 int send_afs_status(struct command_context *cc, int parser_friendly);
50 static bool subcmd_should_die;
53 * Don't call PARA_XXX_LOG() here as we might already hold the log mutex. See
54 * generic_signal_handler() for details.
56 static void command_handler_sighandler(int s)
59 subcmd_should_die = true;
63 * Compute human readable vss status text.
65 * We can't call vss_playing() and friends here because those functions read
66 * the flags from the primary mmd structure, so calling them from command
67 * handler context would require to take the mmd lock. At the time the function
68 * is called we already took a copy of the mmd structure and want to use the
69 * flags value of the copy for computing the vss status text.
71 static char *vss_status_tohuman(unsigned int flags)
73 if (flags & VSS_PLAYING)
74 return para_strdup("playing");
76 return para_strdup("stopped");
77 return para_strdup("paused");
83 static char *vss_get_status_flags(unsigned int flags)
85 char *msg = alloc(5 * sizeof(char));
87 msg[0] = (flags & VSS_PLAYING)? 'P' : '_';
88 msg[1] = (flags & VSS_NOMORE)? 'O' : '_';
89 msg[2] = (flags & VSS_NEXT)? 'N' : '_';
90 msg[3] = (flags & VSS_REPOS)? 'R' : '_';
95 static unsigned get_status(struct misc_meta_data *nmmd, bool parser_friendly,
98 char *status, *flags; /* vss status info */
99 /* nobody updates our version of "now" */
100 long offset = (nmmd->offset + 500) / 1000;
101 struct timeval current_time;
102 struct para_buffer b = {.flags = parser_friendly? PBF_SIZE_PREFIX : 0};
104 /* report real status */
105 status = vss_status_tohuman(nmmd->vss_status_flags);
106 flags = vss_get_status_flags(nmmd->vss_status_flags);
107 clock_get_realtime(¤t_time);
109 * The calls to WRITE_STATUS_ITEM() below never fail because
110 * b->max_size is zero (unlimited), see \ref para_printf(). However,
111 * clang is not smart enough to prove this and complains nevertheless.
112 * Casting the return value to void silences clang.
114 (void)WRITE_STATUS_ITEM(&b, SI_status, "%s\n", status);
115 (void)WRITE_STATUS_ITEM(&b, SI_status_flags, "%s\n", flags);
116 (void)WRITE_STATUS_ITEM(&b, SI_offset, "%li\n", offset);
117 (void)WRITE_STATUS_ITEM(&b, SI_afs_mode, "%s\n", mmd->afs_mode_string);
118 (void)WRITE_STATUS_ITEM(&b, SI_stream_start, "%lu.%lu\n",
119 (long unsigned)nmmd->stream_start.tv_sec,
120 (long unsigned)nmmd->stream_start.tv_usec);
121 (void)WRITE_STATUS_ITEM(&b, SI_current_time, "%lu.%lu\n",
122 (long unsigned)current_time.tv_sec,
123 (long unsigned)current_time.tv_usec);
131 * Send a sideband packet through a blocking file descriptor.
133 * \param scc fd and crypto keys.
134 * \param buf The buffer to send.
135 * \param numbytes The size of \a buf.
136 * \param band The sideband designator of this packet.
137 * \param dont_free If true, never deallocate \a buf.
139 * The nonblock flag must be disabled for the file descriptor given by \a scc.
141 * Stream cipher encryption is automatically activated if necessary via the
142 * sideband transformation, depending on the value of \a band.
146 * \sa \ref send_sb_va().
148 int send_sb(struct stream_cipher_context *scc, void *buf, size_t numbytes,
149 int band, bool dont_free)
152 struct sb_context *sbc;
154 sb_transformation trafo = band < SBD_PROCEED? NULL : sc_trafo;
155 struct sb_buffer sbb = SBB_INIT(band, buf, numbytes);
157 sbc = sb_new_send(&sbb, dont_free, trafo, scc->send);
159 ret = sb_get_send_buffers(sbc, iov);
160 ret = xwritev(scc->fd, iov, ret);
163 } while (sb_sent(sbc, ret) == false);
171 * Create a variable sized buffer and send it as a sideband packet.
173 * \param scc Passed to \ref send_sb.
174 * \param band See \ref send_sb.
175 * \param fmt The format string.
177 * \return The return value of the underlying call to \ref send_sb.
179 __printf_3_4 int send_sb_va(struct stream_cipher_context *scc, int band,
180 const char *fmt, ...)
187 ret = xvasprintf(&msg, fmt, ap);
189 return send_sb(scc, msg, ret, band, false);
193 * Send an error message to a client.
195 * \param cc Client info.
196 * \param err The (positive) error code.
198 * \return The return value of the underlying call to send_sb_va().
200 int send_strerror(struct command_context *cc, int err)
202 return send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", para_strerror(err));
206 * Send an error context to a client,
208 * \param cc Client info.
209 * \param errctx The error context string.
211 * \return The return value of the underlying call to send_sb_va().
213 * This function frees the error context string after it was sent.
215 int send_errctx(struct command_context *cc, char *errctx)
221 ret = send_sb_va(&cc->scc, SBD_ERROR_LOG, "%s\n", errctx);
226 static int check_sender_args(struct command_context *cc,
227 struct lls_parse_result *lpr, struct sender_command_data *scd)
230 const char * const subcmds[] = {SENDER_SUBCOMMANDS};
233 unsigned num_inputs = lls_num_inputs(lpr);
235 scd->sender_num = -1;
236 ret = lls(lls_check_arg_count(lpr, 2, INT_MAX, &errctx));
238 send_errctx(cc, errctx);
241 arg = lls_input(0, lpr);
243 if (strcmp(senders[i]->name, arg) == 0)
246 return -E_COMMAND_SYNTAX;
248 arg = lls_input(1, lpr);
249 for (i = 0; i < NUM_SENDER_CMDS; i++)
250 if (!strcmp(subcmds[i], arg))
252 if (i == NUM_SENDER_CMDS)
253 return -E_COMMAND_SYNTAX;
255 if (!senders[scd->sender_num]->client_cmds[scd->cmd_num])
256 return -E_SENDER_CMD;
257 switch (scd->cmd_num) {
261 return -E_COMMAND_SYNTAX;
265 if (num_inputs != 3 || parse_cidr(lls_input(2, lpr), scd->host,
266 sizeof(scd->host), &scd->netmask) == NULL)
267 return -E_COMMAND_SYNTAX;
272 return -E_COMMAND_SYNTAX;
273 return parse_fec_url(lls_input(2, lpr), scd);
275 return -E_COMMAND_SYNTAX;
281 * Receive a sideband packet from a blocking file descriptor.
283 * \param scc fd and crypto keys.
284 * \param expected_band The expected band designator.
285 * \param max_size Passed to \ref sb_new_recv().
286 * \param result Body of the sideband packet is returned here.
288 * If \a expected_band is not \p SBD_ANY, the band designator of the received
289 * sideband packet is compared to \a expected_band and a mismatch is considered
294 int recv_sb(struct stream_cipher_context *scc,
295 enum sb_designator expected_band,
296 size_t max_size, struct iovec *result)
299 struct sb_context *sbc;
301 struct sb_buffer sbb;
302 sb_transformation trafo;
304 trafo = expected_band != SBD_ANY && expected_band < SBD_PROCEED?
306 sbc = sb_new_recv(max_size, trafo, scc->recv);
308 sb_get_recv_buffer(sbc, &iov);
309 ret = recv_bin_buffer(scc->fd, iov.iov_base, iov.iov_len);
314 ret = sb_received(sbc, ret, &sbb);
321 if (expected_band != SBD_ANY && sbb.band != expected_band)
330 static int com_sender(struct command_context *cc, struct lls_parse_result *lpr)
334 struct sender_command_data scd;
336 if (lls_num_inputs(lpr) == 0) {
339 ret = xasprintf(&tmp, "%s%s\n", msg? msg : "",
344 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
346 ret = check_sender_args(cc, lpr, &scd);
348 if (scd.sender_num < 0)
350 if (strcmp(lls_input(1, lpr), "status") == 0)
351 msg = senders[scd.sender_num]->status();
353 msg = senders[scd.sender_num]->help();
354 return send_sb(&cc->scc, msg, strlen(msg), SBD_OUTPUT, false);
357 switch (scd.cmd_num) {
360 assert(senders[scd.sender_num]->resolve_target);
361 ret = senders[scd.sender_num]->resolve_target(lls_input(2, lpr),
367 for (i = 0; i < 10; i++) {
368 mutex_lock(mmd_mutex);
369 if (mmd->sender_cmd_data.cmd_num >= 0) {
370 /* another sender command is active, retry in 100ms */
371 struct timespec ts = {.tv_nsec = 100 * 1000 * 1000};
372 mutex_unlock(mmd_mutex);
373 nanosleep(&ts, NULL);
376 mmd->sender_cmd_data = scd;
377 mutex_unlock(mmd_mutex);
380 return (i < 10)? 1 : -E_LOCK;
382 EXPORT_SERVER_CMD_HANDLER(sender);
384 static int com_si(struct command_context *cc,
385 __a_unused struct lls_parse_result *lpr)
390 ut = daemon_get_uptime_str(now);
391 mutex_lock(mmd_mutex);
392 ret = xasprintf(&msg,
393 "up: %s\nplayed: %u\n"
396 "connections (active/accepted/total): %u/%u/%u\n"
397 "supported audio formats: %s\n",
401 mmd->active_connections,
404 AUDIO_FORMAT_HANDLERS
406 mutex_unlock(mmd_mutex);
408 return send_sb(&cc->scc, msg, ret, SBD_OUTPUT, false);
410 EXPORT_SERVER_CMD_HANDLER(si);
412 static int com_version(struct command_context *cc, struct lls_parse_result *lpr)
417 if (SERVER_CMD_OPT_GIVEN(VERSION, VERBOSE, lpr))
418 len = xasprintf(&msg, "%s", version_text("server"));
420 len = xasprintf(&msg, "%s\n", version_single_line("server"));
421 return send_sb(&cc->scc, msg, len, SBD_OUTPUT, false);
423 EXPORT_SERVER_CMD_HANDLER(version);
425 /** \cond empty_status_items */
426 /* These status items are cleared if no audio file is currently open. */
427 #define EMPTY_STATUS_ITEMS \
432 ITEM(attributes_bitmap) \
433 ITEM(attributes_txt) \
444 ITEM(seconds_total) \
457 ITEM(amplification) \
460 /** \endcond empty_status_items */
463 * Create a set of audio-file related status items with empty values. These are
464 * written to stat clients when no audio file is open.
466 static unsigned empty_status_items(bool parser_friendly, char **result)
472 len = xasprintf(&esi,
473 #define ITEM(x) "0004 %02x:\n"
476 #define ITEM(x) , (unsigned) SI_ ## x
481 len = xasprintf(&esi,
482 #define ITEM(x) "%s:\n"
485 #define ITEM(x) ,status_item_list[SI_ ## x]
492 #undef EMPTY_STATUS_ITEMS
494 static int com_stat(struct command_context *cc, struct lls_parse_result *lpr)
497 struct misc_meta_data tmp, *nmmd = &tmp;
499 bool parser_friendly = SERVER_CMD_OPT_GIVEN(STAT, PARSER_FRIENDLY,
501 uint32_t num = SERVER_CMD_UINT32_VAL(STAT, NUM, lpr);
502 const struct timespec ts = {.tv_sec = 50, .tv_nsec = 0};
504 para_sigaction(SIGINT, SIG_IGN);
505 para_sigaction(SIGUSR1, command_handler_sighandler);
506 para_sigaction(SIGTERM, command_handler_sighandler);
508 * Simply checking subcmd_should_die is racy because a signal may
509 * arrive after the check but before the subsequent call to sleep(3).
510 * If this happens, sleep(3) would not be interrupted by the signal.
511 * To avoid this we block SIGTERM here and allow it to arrive only
514 para_block_signal(SIGTERM);
515 para_block_signal(SIGUSR1);
519 * Copy the mmd structure to minimize the time we hold the mmd
522 mutex_lock(mmd_mutex);
524 mutex_unlock(mmd_mutex);
525 ret = get_status(nmmd, parser_friendly, &s);
526 ret = send_sb(&cc->scc, s, ret, SBD_OUTPUT, false);
529 if (nmmd->vss_status_flags & VSS_NEXT) {
531 ret = empty_status_items(parser_friendly, &esi);
532 ret = send_sb(&cc->scc, esi, ret, SBD_OUTPUT, false);
536 send_afs_status(cc, parser_friendly);
538 if (num > 0 && !--num)
540 sigemptyset(&set); /* empty set means: unblock all signals */
542 * pselect(2) allows to atomically unblock signals, then go to
543 * sleep. Calling sigprocmask(2) followed by sleep(3) would
544 * open a race window similar to the one described above.
546 pselect(1, NULL, NULL, NULL, &ts, &set);
547 if (subcmd_should_die) {
548 PARA_EMERG_LOG("terminating on SIGTERM\n");
551 ret = -E_SERVER_CRASH;
558 EXPORT_SERVER_CMD_HANDLER(stat);
560 static const char *aux_info_cb(unsigned cmd_num, bool verbose)
562 static char result[80];
563 unsigned perms = server_command_perms[cmd_num];
566 /* permissions: VSS_READ | VSS_WRITE */
567 sprintf(result, "permissions: %s",
568 server_command_perms_txt[cmd_num]);
570 result[0] = perms & AFS_READ? 'a' : '-';
571 result[1] = perms & AFS_WRITE? 'A' : '-';
572 result[2] = perms & VSS_READ? 'v' : '-';
573 result[3] = perms & VSS_WRITE? 'V' : '-';
579 static int com_help(struct command_context *cc, struct lls_parse_result *lpr)
584 bool long_help = SERVER_CMD_OPT_GIVEN(HELP, LONG, lpr);
586 lsu_com_help(long_help, lpr, server_cmd_suite, aux_info_cb, &buf, &n);
587 ret = send_sb(&cc->scc, buf, n, SBD_OUTPUT, false);
590 EXPORT_SERVER_CMD_HANDLER(help);
592 static int com_hup(__a_unused struct command_context *cc,
593 __a_unused struct lls_parse_result *lpr)
595 kill(getppid(), SIGHUP);
598 EXPORT_SERVER_CMD_HANDLER(hup);
600 static int com_ll(struct command_context *cc, struct lls_parse_result *lpr)
604 const char *sev[] = {SEVERITIES}, *arg;
605 int ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
608 send_errctx(cc, errctx);
611 if (lls_num_inputs(lpr) == 0) { /* reporting is an unprivileged op. */
612 const char *severity;
613 mutex_lock(mmd_mutex);
614 severity = sev[mmd->loglevel];
615 mutex_unlock(mmd_mutex);
616 return send_sb_va(&cc->scc, SBD_OUTPUT, "%s\n", severity);
619 * Changing the loglevel changes the state of both the afs and the vss,
620 * so we require both AFS_WRITE and VSS_WRITE.
622 perms = AFS_WRITE | VSS_WRITE;
623 if ((cc->u->perms & perms) != perms)
624 return -ERRNO_TO_PARA_ERROR(EPERM);
625 arg = lls_input(0, lpr);
626 for (ll = 0; ll < NUM_LOGLEVELS; ll++)
627 if (!strcmp(arg, sev[ll]))
629 if (ll >= NUM_LOGLEVELS)
630 return -ERRNO_TO_PARA_ERROR(EINVAL);
631 PARA_INFO_LOG("new log level: %s\n", sev[ll]);
632 /* Ask the server and afs processes to adjust their log level. */
633 mutex_lock(mmd_mutex);
635 mutex_unlock(mmd_mutex);
638 EXPORT_SERVER_CMD_HANDLER(ll);
640 static int com_term(__a_unused struct command_context *cc,
641 __a_unused struct lls_parse_result *lpr)
644 * The server catches SIGTERM and propagates this signal to all its
645 * children. We are about to exit anyway, but we'd leak tons of memory
646 * if being terminated by the signal. So we ignore the signal here and
647 * terminate via the normal exit path, deallocating all memory.
649 para_sigaction(SIGTERM, SIG_IGN);
650 kill(getppid(), SIGTERM);
653 EXPORT_SERVER_CMD_HANDLER(term);
655 static int com_play(__a_unused struct command_context *cc,
656 __a_unused struct lls_parse_result *lpr)
658 mutex_lock(mmd_mutex);
659 mmd->new_vss_status_flags |= VSS_PLAYING;
660 mmd->new_vss_status_flags &= ~VSS_NOMORE;
661 mutex_unlock(mmd_mutex);
664 EXPORT_SERVER_CMD_HANDLER(play);
666 static int com_stop(__a_unused struct command_context *cc,
667 __a_unused struct lls_parse_result *lpr)
669 mutex_lock(mmd_mutex);
670 mmd->new_vss_status_flags &= ~VSS_PLAYING;
671 mmd->new_vss_status_flags &= ~VSS_REPOS;
672 mmd->new_vss_status_flags |= VSS_NEXT;
673 mutex_unlock(mmd_mutex);
676 EXPORT_SERVER_CMD_HANDLER(stop);
678 static int com_pause(__a_unused struct command_context *cc,
679 __a_unused struct lls_parse_result *lpr)
681 mutex_lock(mmd_mutex);
682 if (!vss_paused() && !vss_stopped()) {
684 mmd->new_vss_status_flags &= ~VSS_PLAYING;
685 mmd->new_vss_status_flags &= ~VSS_NEXT;
687 mutex_unlock(mmd_mutex);
690 EXPORT_SERVER_CMD_HANDLER(pause);
692 static int com_next(__a_unused struct command_context *cc,
693 __a_unused struct lls_parse_result *lpr)
695 mutex_lock(mmd_mutex);
697 mmd->new_vss_status_flags |= VSS_NEXT;
698 mutex_unlock(mmd_mutex);
701 EXPORT_SERVER_CMD_HANDLER(next);
703 static int com_nomore(__a_unused struct command_context *cc,
704 __a_unused struct lls_parse_result *lpr)
706 mutex_lock(mmd_mutex);
707 if (vss_playing() || vss_paused())
708 mmd->new_vss_status_flags |= VSS_NOMORE;
709 mutex_unlock(mmd_mutex);
712 EXPORT_SERVER_CMD_HANDLER(nomore);
714 static int com_ff(struct command_context *cc, struct lls_parse_result *lpr)
720 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
722 send_errctx(cc, errctx);
725 ret = para_atoi32(lls_input(0, lpr), &i);
728 mutex_lock(mmd_mutex);
729 ret = -E_NO_AUDIO_FILE;
730 if (!mmd->afd.afhi.chunks_total || !mmd->afd.afhi.seconds_total)
733 promille = (1000 * mmd->current_chunk) / mmd->afd.afhi.chunks_total;
735 * We need this cast because without it the expression on the right
736 * hand side is of unsigned type.
738 promille += 1000 * i / (int)mmd->afd.afhi.seconds_total;
741 if (promille > 1000) {
742 mmd->new_vss_status_flags |= VSS_NEXT;
745 mmd->repos_request = (mmd->afd.afhi.chunks_total * promille) / 1000;
746 mmd->new_vss_status_flags |= VSS_REPOS;
747 mmd->new_vss_status_flags &= ~VSS_NEXT;
750 mutex_unlock(mmd_mutex);
753 EXPORT_SERVER_CMD_HANDLER(ff);
755 static int com_jmp(struct command_context *cc, struct lls_parse_result *lpr)
760 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
762 send_errctx(cc, errctx);
765 if (sscanf(lls_input(0, lpr), "%d", &i) <= 0)
766 return -ERRNO_TO_PARA_ERROR(EINVAL);
767 if (i < 0 || i > 100)
768 return -ERRNO_TO_PARA_ERROR(EINVAL);
769 mutex_lock(mmd_mutex);
770 ret = -E_NO_AUDIO_FILE;
771 if (!mmd->afd.afhi.chunks_total)
773 PARA_INFO_LOG("jumping to %d%%\n", i);
774 mmd->repos_request = (mmd->afd.afhi.chunks_total * i + 50) / 100;
775 mmd->new_vss_status_flags |= VSS_REPOS;
776 mmd->new_vss_status_flags &= ~VSS_NEXT;
780 mutex_unlock(mmd_mutex);
783 EXPORT_SERVER_CMD_HANDLER(jmp);
785 static void reset_signals(void)
787 para_sigaction(SIGCHLD, SIG_IGN);
788 para_sigaction(SIGINT, SIG_DFL);
789 para_sigaction(SIGTERM, SIG_DFL);
790 para_sigaction(SIGHUP, SIG_DFL);
793 struct connection_features {
794 bool sha256_requested; /* can be removed after 0.7.0 */
797 static int parse_auth_request(char *buf, int len, const struct user **u,
798 struct connection_features *cf)
801 char *p, *username, **features = NULL;
802 size_t auth_rq_len = strlen(AUTH_REQUEST_MSG);
805 memset(cf, 0, sizeof(*cf));
806 if (len < auth_rq_len + 2)
807 return -E_AUTH_REQUEST;
808 if (strncmp(buf, AUTH_REQUEST_MSG, auth_rq_len) != 0)
809 return -E_AUTH_REQUEST;
810 username = buf + auth_rq_len;
811 p = strchr(username, ' ');
815 return -E_AUTH_REQUEST;
818 create_argv(p, ",", &features);
819 for (i = 0; features[i]; i++) {
821 * ->sha256_requested can go away after 0.7.0 so that
822 * sha256 is used unconditionally, but we need to
823 * accept the feature request until 0.9.0.
825 if (strcmp(features[i], "sha256") == 0)
826 cf->sha256_requested = true;
828 ret = -E_BAD_FEATURE;
833 PARA_DEBUG_LOG("received auth request for user %s\n", username);
834 *u = user_list_lookup(username);
841 #define HANDSHAKE_BUFSIZE 4096
843 static int run_command(struct command_context *cc, struct iovec *iov)
846 char *p, *end, **argv;
847 const struct lls_command *lcmd = NULL;
849 struct lls_parse_result *lpr;
852 if (iov->iov_base == NULL || iov->iov_len == 0)
853 return -ERRNO_TO_PARA_ERROR(EINVAL);
855 p[iov->iov_len - 1] = '\0'; /* just to be sure */
857 ret = lls(lls_lookup_subcmd(p, server_cmd_suite, &errctx));
859 send_errctx(cc, errctx);
862 perms = server_command_perms[ret];
863 if ((perms & cc->u->perms) != perms)
864 return -ERRNO_TO_PARA_ERROR(EPERM);
865 lcmd = lls_cmd(ret, server_cmd_suite);
866 end = iov->iov_base + iov->iov_len;
867 for (i = 0; p < end; i++)
870 argv = arr_alloc(argc + 1, sizeof(char *));
871 for (i = 0, p = iov->iov_base; p < end; i++) {
872 argv[i] = para_strdup(p);
876 PARA_NOTICE_LOG("calling com_%s() for user %s\n",
877 lls_command_name(lcmd), cc->u->name);
878 ret = lls(lls_parse(argc, argv, lcmd, &lpr, &errctx));
880 const struct server_cmd_user_data *ud = lls_user_data(lcmd);
881 ret = ud->handler(cc, lpr);
882 lls_free_parse_result(lpr, lcmd);
884 send_errctx(cc, errctx);
886 mutex_lock(mmd_mutex);
888 if (ret >= 0 && (perms & AFS_WRITE))
890 mutex_unlock(mmd_mutex);
895 * Perform user authentication and execute a command.
897 * \param fd The file descriptor to send output to.
899 * Whenever para_server accepts an incoming tcp connection on the port it
900 * listens on, it forks and the resulting child calls this function.
902 * An RSA-based challenge/response is used to authenticate the peer. If the
903 * authentication succeeds, a random session key is generated and sent back to
904 * the peer, encrypted with its RSA public key. From this point on, all
905 * transfers are encrypted with this session key using a stream cipher.
907 * Next it is checked if the peer supplied a valid server command or a command
908 * for the audio file selector. If yes, and if the user has sufficient
909 * permissions to execute this command, the function calls the corresponding
910 * command handler which performs argument checking and further processing.
912 * To cope with DOS attacks, a timer is set up right after the fork. If the
913 * connection was still not authenticated when the timeout expires, the child
914 * process is terminated.
918 * \sa alarm(2), \ref openssl.c, \ref crypt.h.
920 int handle_connect(int fd)
923 unsigned char rand_buf[APC_CHALLENGE_SIZE + 2 * SESSION_KEY_LEN];
924 unsigned char challenge_hash[HASH2_SIZE];
925 char *command = NULL, *buf = alloc(HANDSHAKE_BUFSIZE) /* must be on the heap */;
927 struct command_context cc_struct = {.u = NULL}, *cc = &cc_struct;
929 struct connection_features cf;
933 /* we need a blocking fd here as recv() might return EAGAIN otherwise. */
934 ret = mark_fd_blocking(fd);
937 /* send Welcome message */
938 ret = write_va_buffer(fd, "This is para_server, version "
939 PACKAGE_VERSION ".\n"
940 "Features: sha256\n" /* no longer announce this after 0.8.0 */
944 /* recv auth request line */
945 ret = recv_buffer(fd, buf, HANDSHAKE_BUFSIZE);
948 ret = parse_auth_request(buf, ret, &cc->u, &cf);
952 get_random_bytes_or_die(rand_buf, sizeof(rand_buf));
953 ret = apc_pub_encrypt(cc->u->pubkey, rand_buf, sizeof(rand_buf),
954 (unsigned char *)buf);
960 * We don't want to reveal our user names, so we send a
961 * challenge to the client even if the user does not exist, and
962 * fail the authentication later.
965 get_random_bytes_or_die((unsigned char *)buf, numbytes);
967 PARA_DEBUG_LOG("sending %d byte challenge + session key (%zu bytes)\n",
968 APC_CHALLENGE_SIZE, numbytes);
969 ret = send_sb(&cc->scc, buf, numbytes, SBD_CHALLENGE, false);
973 ret = recv_sb(&cc->scc, SBD_CHALLENGE_RESPONSE,
974 HANDSHAKE_BUFSIZE, &iov);
978 numbytes = iov.iov_len;
979 PARA_DEBUG_LOG("received %zu bytes challenge response\n", numbytes);
984 * The correct response is the hash of the first APC_CHALLENGE_SIZE bytes
985 * of the random data.
988 if (cf.sha256_requested) {
989 if (numbytes != HASH2_SIZE)
991 hash2_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
992 if (memcmp(challenge_hash, buf, HASH2_SIZE))
994 } else { /* old client. This can be removed after 0.7.0 */
995 if (numbytes != HASH_SIZE)
997 hash_function((char *)rand_buf, APC_CHALLENGE_SIZE, challenge_hash);
998 if (memcmp(challenge_hash, buf, HASH_SIZE))
1001 /* auth successful */
1003 PARA_INFO_LOG("good auth for %s\n", cc->u->name);
1004 /* init stream cipher keys with the second part of the random buffer */
1005 cc->scc.recv = sc_new(rand_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
1006 cc->scc.send = sc_new(rand_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
1008 ret = send_sb(&cc->scc, NULL, 0, SBD_PROCEED, false);
1011 ret = recv_sb(&cc->scc, SBD_COMMAND, MAX_COMMAND_LEN, &iov);
1014 ret = run_command(cc, &iov);
1021 if (send_strerror(cc, -ret) >= 0)
1022 send_sb(&cc->scc, NULL, 0, SBD_EXIT__FAILURE, true);
1024 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1028 mutex_lock(mmd_mutex);
1029 mmd->active_connections--;
1030 mutex_unlock(mmd_mutex);
1032 ret = send_sb(&cc->scc, NULL, 0, SBD_EXIT__SUCCESS, true);
1034 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1036 sc_free(cc->scc.recv);
1037 sc_free(cc->scc.send);