getty.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Based on agetty - another getty program for Linux. By W. Z. Venema 1989
  4. * Ported to Linux by Peter Orbaek <poe@daimi.aau.dk>
  5. * This program is freely distributable.
  6. *
  7. * option added by Eric Rasmussen <ear@usfirst.org> - 12/28/95
  8. *
  9. * 1999-02-22 Arkadiusz Mickiewicz <misiek@misiek.eu.org>
  10. * - Added Native Language Support
  11. *
  12. * 1999-05-05 Thorsten Kranzkowski <dl8bcu@gmx.net>
  13. * - Enabled hardware flow control before displaying /etc/issue
  14. *
  15. * 2011-01 Venys Vlasenko
  16. * - Removed parity detection code. It can't work reliably:
  17. * if all chars received have bit 7 cleared and odd (or even) parity,
  18. * it is impossible to determine whether other side is 8-bit,no-parity
  19. * or 7-bit,odd(even)-parity. It also interferes with non-ASCII usernames.
  20. * - From now on, we assume that parity is correctly set.
  21. *
  22. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  23. */
  24. //config:config GETTY
  25. //config: bool "getty"
  26. //config: default y
  27. //config: select FEATURE_SYSLOG
  28. //config: help
  29. //config: getty lets you log in on a tty. It is normally invoked by init.
  30. //config:
  31. //config: Note that you can save a few bytes by disabling it and
  32. //config: using login applet directly.
  33. //config: If you need to reset tty attributes before calling login,
  34. //config: this script approximates getty:
  35. //config:
  36. //config: exec </dev/$1 >/dev/$1 2>&1 || exit 1
  37. //config: reset
  38. //config: stty sane; stty ispeed 38400; stty ospeed 38400
  39. //config: printf "%s login: " "`hostname`"
  40. //config: read -r login
  41. //config: exec /bin/login "$login"
  42. //applet:IF_GETTY(APPLET(getty, BB_DIR_SBIN, BB_SUID_DROP))
  43. //kbuild:lib-$(CONFIG_GETTY) += getty.o
  44. #include "libbb.h"
  45. #include <syslog.h>
  46. #ifndef IUCLC
  47. # define IUCLC 0
  48. #endif
  49. #ifndef LOGIN_PROCESS
  50. # undef ENABLE_FEATURE_UTMP
  51. # undef ENABLE_FEATURE_WTMP
  52. # define ENABLE_FEATURE_UTMP 0
  53. # define ENABLE_FEATURE_WTMP 0
  54. #endif
  55. /* The following is used for understandable diagnostics */
  56. #ifdef DEBUGGING
  57. static FILE *dbf;
  58. # define DEBUGTERM "/dev/ttyp0"
  59. # define debug(...) do { fprintf(dbf, __VA_ARGS__); fflush(dbf); } while (0)
  60. #else
  61. # define debug(...) ((void)0)
  62. #endif
  63. /*
  64. * Things you may want to modify.
  65. *
  66. * You may disagree with the default line-editing etc. characters defined
  67. * below. Note, however, that DEL cannot be used for interrupt generation
  68. * and for line editing at the same time.
  69. */
  70. #undef _PATH_LOGIN
  71. #define _PATH_LOGIN "/bin/login"
  72. /* Displayed before the login prompt.
  73. * If ISSUE is not defined, getty will never display the contents of the
  74. * /etc/issue file. You will not want to spit out large "issue" files at the
  75. * wrong baud rate.
  76. */
  77. #define ISSUE "/etc/issue"
  78. /* Macro to build Ctrl-LETTER. Assumes ASCII dialect */
  79. #define CTL(x) ((x) ^ 0100)
  80. /*
  81. * When multiple baud rates are specified on the command line,
  82. * the first one we will try is the first one specified.
  83. */
  84. #define MAX_SPEED 10 /* max. nr. of baud rates */
  85. struct globals {
  86. unsigned timeout;
  87. const char *login; /* login program */
  88. const char *fakehost;
  89. const char *tty_name;
  90. char *initstring; /* modem init string */
  91. const char *issue; /* alternative issue file */
  92. int numspeed; /* number of baud rates to try */
  93. int speeds[MAX_SPEED]; /* baud rates to be tried */
  94. unsigned char eol; /* end-of-line char seen (CR or NL) */
  95. struct termios tty_attrs;
  96. char line_buf[128];
  97. };
  98. #define G (*ptr_to_globals)
  99. #define INIT_G() do { \
  100. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  101. } while (0)
  102. //usage:#define getty_trivial_usage
  103. //usage: "[OPTIONS] BAUD_RATE[,BAUD_RATE]... TTY [TERMTYPE]"
  104. //usage:#define getty_full_usage "\n\n"
  105. //usage: "Open TTY, prompt for login name, then invoke /bin/login\n"
  106. //usage: "\n -h Enable hardware RTS/CTS flow control"
  107. //usage: "\n -L Set CLOCAL (ignore Carrier Detect state)"
  108. //usage: "\n -m Get baud rate from modem's CONNECT status message"
  109. //usage: "\n -n Don't prompt for login name"
  110. //usage: "\n -w Wait for CR or LF before sending /etc/issue"
  111. //usage: "\n -i Don't display /etc/issue"
  112. //usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
  113. //usage: "\n -l LOGIN Invoke LOGIN instead of /bin/login"
  114. //usage: "\n -t SEC Terminate after SEC if no login name is read"
  115. //usage: "\n -I INITSTR Send INITSTR before anything else"
  116. //usage: "\n -H HOST Log HOST into the utmp file as the hostname"
  117. //usage: "\n"
  118. //usage: "\nBAUD_RATE of 0 leaves it unchanged"
  119. static const char opt_string[] ALIGN1 = "I:LH:f:hil:mt:wn";
  120. #define F_INITSTRING (1 << 0) /* -I */
  121. #define F_LOCAL (1 << 1) /* -L */
  122. #define F_FAKEHOST (1 << 2) /* -H */
  123. #define F_CUSTISSUE (1 << 3) /* -f */
  124. #define F_RTSCTS (1 << 4) /* -h */
  125. #define F_NOISSUE (1 << 5) /* -i */
  126. #define F_LOGIN (1 << 6) /* -l */
  127. #define F_PARSE (1 << 7) /* -m */
  128. #define F_TIMEOUT (1 << 8) /* -t */
  129. #define F_WAITCRLF (1 << 9) /* -w */
  130. #define F_NOPROMPT (1 << 10) /* -n */
  131. /* convert speed string to speed code; return <= 0 on failure */
  132. static int bcode(const char *s)
  133. {
  134. int value = bb_strtou(s, NULL, 10); /* yes, int is intended! */
  135. if (value < 0) /* bad terminating char, overflow, etc */
  136. return value;
  137. return tty_value_to_baud(value);
  138. }
  139. /* parse alternate baud rates */
  140. static void parse_speeds(char *arg)
  141. {
  142. char *cp;
  143. /* NB: at least one iteration is always done */
  144. debug("entered parse_speeds\n");
  145. while ((cp = strsep(&arg, ",")) != NULL) {
  146. G.speeds[G.numspeed] = bcode(cp);
  147. if (G.speeds[G.numspeed] < 0)
  148. bb_error_msg_and_die("bad speed: %s", cp);
  149. /* note: arg "0" turns into speed B0 */
  150. G.numspeed++;
  151. if (G.numspeed > MAX_SPEED)
  152. bb_error_msg_and_die("too many alternate speeds");
  153. }
  154. debug("exiting parse_speeds\n");
  155. }
  156. /* parse command-line arguments */
  157. static void parse_args(char **argv)
  158. {
  159. char *ts;
  160. int flags;
  161. opt_complementary = "-2:t+"; /* at least 2 args; -t N */
  162. flags = getopt32(argv, opt_string,
  163. &G.initstring, &G.fakehost, &G.issue,
  164. &G.login, &G.timeout
  165. );
  166. if (flags & F_INITSTRING) {
  167. G.initstring = xstrdup(G.initstring);
  168. /* decode \ddd octal codes into chars */
  169. strcpy_and_process_escape_sequences(G.initstring, G.initstring);
  170. }
  171. argv += optind;
  172. debug("after getopt\n");
  173. /* We loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
  174. G.tty_name = argv[0];
  175. ts = argv[1]; /* baud rate(s) */
  176. if (isdigit(argv[0][0])) {
  177. /* A number first, assume it's a speed (BSD style) */
  178. G.tty_name = ts; /* tty name is in argv[1] */
  179. ts = argv[0]; /* baud rate(s) */
  180. }
  181. parse_speeds(ts);
  182. if (argv[2])
  183. xsetenv("TERM", argv[2]);
  184. debug("exiting parse_args\n");
  185. }
  186. /* set up tty as standard input, output, error */
  187. static void open_tty(void)
  188. {
  189. /* Set up new standard input, unless we are given an already opened port */
  190. if (NOT_LONE_DASH(G.tty_name)) {
  191. if (G.tty_name[0] != '/')
  192. G.tty_name = xasprintf("/dev/%s", G.tty_name); /* will leak it */
  193. /* Open the tty as standard input */
  194. debug("open(2)\n");
  195. close(0);
  196. xopen(G.tty_name, O_RDWR | O_NONBLOCK); /* uses fd 0 */
  197. /* Set proper protections and ownership */
  198. fchown(0, 0, 0); /* 0:0 */
  199. fchmod(0, 0620); /* crw--w---- */
  200. } else {
  201. char *n;
  202. /*
  203. * Standard input should already be connected to an open port.
  204. * Make sure it is open for read/write.
  205. */
  206. if ((fcntl(0, F_GETFL) & (O_RDWR|O_RDONLY|O_WRONLY)) != O_RDWR)
  207. bb_error_msg_and_die("stdin is not open for read/write");
  208. /* Try to get real tty name instead of "-" */
  209. n = xmalloc_ttyname(0);
  210. if (n)
  211. G.tty_name = n;
  212. }
  213. applet_name = xasprintf("getty: %s", skip_dev_pfx(G.tty_name));
  214. }
  215. static void set_tty_attrs(void)
  216. {
  217. if (tcsetattr_stdin_TCSANOW(&G.tty_attrs) < 0)
  218. bb_perror_msg_and_die("tcsetattr");
  219. }
  220. /* We manipulate tty_attrs this way:
  221. * - first, we read existing tty_attrs
  222. * - init_tty_attrs modifies some parts and sets it
  223. * - auto_baud and/or BREAK processing can set different speed and set tty attrs
  224. * - finalize_tty_attrs again modifies some parts and sets tty attrs before
  225. * execing login
  226. */
  227. static void init_tty_attrs(int speed)
  228. {
  229. /* Try to drain output buffer, with 5 sec timeout.
  230. * Added on request from users of ~600 baud serial interface
  231. * with biggish buffer on a 90MHz CPU.
  232. * They were losing hundreds of bytes of buffered output
  233. * on tcflush.
  234. */
  235. signal_no_SA_RESTART_empty_mask(SIGALRM, record_signo);
  236. alarm(5);
  237. tcdrain(STDIN_FILENO);
  238. alarm(0);
  239. /* Flush input and output queues, important for modems! */
  240. tcflush(STDIN_FILENO, TCIOFLUSH);
  241. /* Set speed if it wasn't specified as "0" on command line */
  242. if (speed != B0)
  243. cfsetspeed(&G.tty_attrs, speed);
  244. /* Initial settings: 8-bit characters, raw mode, blocking i/o.
  245. * Special characters are set after we have read the login name; all
  246. * reads will be done in raw mode anyway.
  247. */
  248. /* Clear all bits except: */
  249. G.tty_attrs.c_cflag &= (0
  250. /* 2 stop bits (1 otherwise)
  251. * Enable parity bit (both on input and output)
  252. * Odd parity (else even)
  253. */
  254. | CSTOPB | PARENB | PARODD
  255. #ifdef CMSPAR
  256. | CMSPAR /* mark or space parity */
  257. #endif
  258. #ifdef CBAUD
  259. | CBAUD /* (output) baud rate */
  260. #endif
  261. #ifdef CBAUDEX
  262. | CBAUDEX /* (output) baud rate */
  263. #endif
  264. #ifdef CIBAUD
  265. | CIBAUD /* input baud rate */
  266. #endif
  267. );
  268. /* Set: 8 bits; hang up (drop DTR) on last close; enable receive */
  269. G.tty_attrs.c_cflag |= CS8 | HUPCL | CREAD;
  270. if (option_mask32 & F_LOCAL) {
  271. /* ignore Carrier Detect pin:
  272. * opens don't block when CD is low,
  273. * losing CD doesn't hang up processes whose ctty is this tty
  274. */
  275. G.tty_attrs.c_cflag |= CLOCAL;
  276. }
  277. #ifdef CRTSCTS
  278. if (option_mask32 & F_RTSCTS)
  279. G.tty_attrs.c_cflag |= CRTSCTS; /* flow control using RTS/CTS pins */
  280. #endif
  281. G.tty_attrs.c_iflag = 0;
  282. G.tty_attrs.c_lflag = 0;
  283. /* non-raw output; add CR to each NL */
  284. G.tty_attrs.c_oflag = OPOST | ONLCR;
  285. /* reads would block only if < 1 char is available */
  286. G.tty_attrs.c_cc[VMIN] = 1;
  287. /* no timeout (reads block forever) */
  288. G.tty_attrs.c_cc[VTIME] = 0;
  289. #ifdef __linux__
  290. G.tty_attrs.c_line = 0;
  291. #endif
  292. set_tty_attrs();
  293. debug("term_io 2\n");
  294. }
  295. static void finalize_tty_attrs(void)
  296. {
  297. /* software flow control on output (stop sending if XOFF is recvd);
  298. * and on input (send XOFF when buffer is full)
  299. */
  300. G.tty_attrs.c_iflag |= IXON | IXOFF;
  301. if (G.eol == '\r') {
  302. G.tty_attrs.c_iflag |= ICRNL; /* map CR on input to NL */
  303. }
  304. /* Other bits in c_iflag:
  305. * IXANY Any recvd char enables output (any char is also a XON)
  306. * INPCK Enable parity check
  307. * IGNPAR Ignore parity errors (drop bad bytes)
  308. * PARMRK Mark parity errors with 0xff, 0x00 prefix
  309. * (else bad byte is received as 0x00)
  310. * ISTRIP Strip parity bit
  311. * IGNBRK Ignore break condition
  312. * BRKINT Send SIGINT on break - maybe set this?
  313. * INLCR Map NL to CR
  314. * IGNCR Ignore CR
  315. * ICRNL Map CR to NL
  316. * IUCLC Map uppercase to lowercase
  317. * IMAXBEL Echo BEL on input line too long
  318. * IUTF8 Appears to affect tty's idea of char widths,
  319. * observed to improve backspacing through Unicode chars
  320. */
  321. /* ICANON line buffered input (NL or EOL or EOF chars end a line);
  322. * ISIG recognize INT/QUIT/SUSP chars;
  323. * ECHO echo input chars;
  324. * ECHOE echo BS-SP-BS on erase character;
  325. * ECHOK echo kill char specially, not as ^c (ECHOKE controls how exactly);
  326. * ECHOKE erase all input via BS-SP-BS on kill char (else go to next line)
  327. * ECHOCTL Echo ctrl chars as ^c (else echo verbatim:
  328. * e.g. up arrow emits "ESC-something" and thus moves cursor up!)
  329. */
  330. G.tty_attrs.c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL;
  331. /* Other bits in c_lflag:
  332. * XCASE Map uppercase to \lowercase [tried, doesn't work]
  333. * ECHONL Echo NL even if ECHO is not set
  334. * ECHOPRT On erase, echo erased chars
  335. * [qwe<BS><BS><BS> input looks like "qwe\ewq/" on screen]
  336. * NOFLSH Don't flush input buffer after interrupt or quit chars
  337. * IEXTEN Enable extended functions (??)
  338. * [glibc says it enables c_cc[LNEXT] "enter literal char"
  339. * and c_cc[VDISCARD] "toggle discard buffered output" chars]
  340. * FLUSHO Output being flushed (c_cc[VDISCARD] is in effect)
  341. * PENDIN Retype pending input at next read or input char
  342. * (c_cc[VREPRINT] is being processed)
  343. * TOSTOP Send SIGTTOU for background output
  344. * (why "stty sane" unsets this bit?)
  345. */
  346. G.tty_attrs.c_cc[VINTR] = CTL('C');
  347. G.tty_attrs.c_cc[VQUIT] = CTL('\\');
  348. G.tty_attrs.c_cc[VEOF] = CTL('D');
  349. G.tty_attrs.c_cc[VEOL] = '\n';
  350. #ifdef VSWTC
  351. G.tty_attrs.c_cc[VSWTC] = 0;
  352. #endif
  353. #ifdef VSWTCH
  354. G.tty_attrs.c_cc[VSWTCH] = 0;
  355. #endif
  356. G.tty_attrs.c_cc[VKILL] = CTL('U');
  357. /* Other control chars:
  358. * VEOL2
  359. * VERASE, VWERASE - (word) erase. we may set VERASE in get_logname
  360. * VREPRINT - reprint current input buffer
  361. * VLNEXT, VDISCARD, VSTATUS
  362. * VSUSP, VDSUSP - send (delayed) SIGTSTP
  363. * VSTART, VSTOP - chars used for IXON/IXOFF
  364. */
  365. set_tty_attrs();
  366. /* Now the newline character should be properly written */
  367. full_write(STDOUT_FILENO, "\n", 1);
  368. }
  369. /* extract baud rate from modem status message */
  370. static void auto_baud(void)
  371. {
  372. int nread;
  373. /*
  374. * This works only if the modem produces its status code AFTER raising
  375. * the DCD line, and if the computer is fast enough to set the proper
  376. * baud rate before the message has gone by. We expect a message of the
  377. * following format:
  378. *
  379. * <junk><number><junk>
  380. *
  381. * The number is interpreted as the baud rate of the incoming call. If the
  382. * modem does not tell us the baud rate within one second, we will keep
  383. * using the current baud rate. It is advisable to enable BREAK
  384. * processing (comma-separated list of baud rates) if the processing of
  385. * modem status messages is enabled.
  386. */
  387. G.tty_attrs.c_cc[VMIN] = 0; /* don't block reads (min read is 0 chars) */
  388. set_tty_attrs();
  389. /*
  390. * Wait for a while, then read everything the modem has said so far and
  391. * try to extract the speed of the dial-in call.
  392. */
  393. sleep(1);
  394. nread = safe_read(STDIN_FILENO, G.line_buf, sizeof(G.line_buf) - 1);
  395. if (nread > 0) {
  396. int speed;
  397. char *bp;
  398. G.line_buf[nread] = '\0';
  399. for (bp = G.line_buf; bp < G.line_buf + nread; bp++) {
  400. if (isdigit(*bp)) {
  401. speed = bcode(bp);
  402. if (speed > 0)
  403. cfsetspeed(&G.tty_attrs, speed);
  404. break;
  405. }
  406. }
  407. }
  408. /* Restore terminal settings */
  409. G.tty_attrs.c_cc[VMIN] = 1; /* restore to value set by init_tty_attrs */
  410. set_tty_attrs();
  411. }
  412. /* get user name, establish parity, speed, erase, kill, eol;
  413. * return NULL on BREAK, logname on success
  414. */
  415. static char *get_logname(void)
  416. {
  417. char *bp;
  418. char c;
  419. /* Flush pending input (esp. after parsing or switching the baud rate) */
  420. usleep(100*1000); /* 0.1 sec */
  421. tcflush(STDIN_FILENO, TCIFLUSH);
  422. /* Prompt for and read a login name */
  423. do {
  424. /* Write issue file and prompt */
  425. #ifdef ISSUE
  426. if (!(option_mask32 & F_NOISSUE))
  427. print_login_issue(G.issue, G.tty_name);
  428. #endif
  429. print_login_prompt();
  430. /* Read name, watch for break, erase, kill, end-of-line */
  431. bp = G.line_buf;
  432. while (1) {
  433. /* Do not report trivial EINTR/EIO errors */
  434. errno = EINTR; /* make read of 0 bytes be silent too */
  435. if (read(STDIN_FILENO, &c, 1) < 1) {
  436. finalize_tty_attrs();
  437. if (errno == EINTR || errno == EIO)
  438. exit(EXIT_SUCCESS);
  439. bb_perror_msg_and_die(bb_msg_read_error);
  440. }
  441. switch (c) {
  442. case '\r':
  443. case '\n':
  444. *bp = '\0';
  445. G.eol = c;
  446. goto got_logname;
  447. case CTL('H'):
  448. case 0x7f:
  449. G.tty_attrs.c_cc[VERASE] = c;
  450. if (bp > G.line_buf) {
  451. full_write(STDOUT_FILENO, "\010 \010", 3);
  452. bp--;
  453. }
  454. break;
  455. case CTL('U'):
  456. while (bp > G.line_buf) {
  457. full_write(STDOUT_FILENO, "\010 \010", 3);
  458. bp--;
  459. }
  460. break;
  461. case CTL('C'):
  462. case CTL('D'):
  463. finalize_tty_attrs();
  464. exit(EXIT_SUCCESS);
  465. case '\0':
  466. /* BREAK. If we have speeds to try,
  467. * return NULL (will switch speeds and return here) */
  468. if (G.numspeed > 1)
  469. return NULL;
  470. /* fall through and ignore it */
  471. default:
  472. if ((unsigned char)c < ' ') {
  473. /* ignore garbage characters */
  474. } else if ((int)(bp - G.line_buf) < sizeof(G.line_buf) - 1) {
  475. /* echo and store the character */
  476. full_write(STDOUT_FILENO, &c, 1);
  477. *bp++ = c;
  478. }
  479. break;
  480. }
  481. } /* end of get char loop */
  482. got_logname: ;
  483. } while (G.line_buf[0] == '\0'); /* while logname is empty */
  484. return G.line_buf;
  485. }
  486. static void alarm_handler(int sig UNUSED_PARAM)
  487. {
  488. finalize_tty_attrs();
  489. _exit(EXIT_SUCCESS);
  490. }
  491. static void sleep10(void)
  492. {
  493. sleep(10);
  494. }
  495. int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  496. int getty_main(int argc UNUSED_PARAM, char **argv)
  497. {
  498. int n;
  499. pid_t pid, tsid;
  500. char *logname;
  501. INIT_G();
  502. G.login = _PATH_LOGIN; /* default login program */
  503. #ifdef ISSUE
  504. G.issue = ISSUE; /* default issue file */
  505. #endif
  506. G.eol = '\r';
  507. /* Parse command-line arguments */
  508. parse_args(argv);
  509. /* Create new session and pgrp, lose controlling tty */
  510. pid = setsid(); /* this also gives us our pid :) */
  511. if (pid < 0) {
  512. int fd;
  513. /* :(
  514. * docs/ctty.htm says:
  515. * "This is allowed only when the current process
  516. * is not a process group leader".
  517. * Thus, setsid() will fail if we _already_ are
  518. * a session leader - which is quite possible for getty!
  519. */
  520. pid = getpid();
  521. if (getsid(0) != pid) {
  522. //for debugging:
  523. //bb_perror_msg_and_die("setsid failed:"
  524. // " pid %d ppid %d"
  525. // " sid %d pgid %d",
  526. // pid, getppid(),
  527. // getsid(0), getpgid(0));
  528. bb_perror_msg_and_die("setsid");
  529. /*
  530. * When we can end up here?
  531. * Example: setsid() fails when run alone in interactive shell:
  532. * # getty 115200 /dev/tty2
  533. * because shell's child (getty) is put in a new process group.
  534. * But doesn't fail if shell is not interactive
  535. * (and therefore doesn't create process groups for pipes),
  536. * or if getty is not the first process in the process group:
  537. * # true | getty 115200 /dev/tty2
  538. */
  539. }
  540. /* Looks like we are already a session leader.
  541. * In this case (setsid failed) we may still have ctty,
  542. * and it may be different from tty we need to control!
  543. * If we still have ctty, on Linux ioctl(TIOCSCTTY)
  544. * (which we are going to use a bit later) always fails -
  545. * even if we try to take ctty which is already ours!
  546. * Try to drop old ctty now to prevent that.
  547. * Use O_NONBLOCK: old ctty may be a serial line.
  548. */
  549. fd = open("/dev/tty", O_RDWR | O_NONBLOCK);
  550. if (fd >= 0) {
  551. /* TIOCNOTTY sends SIGHUP to the foreground
  552. * process group - which may include us!
  553. * Make sure to not die on it:
  554. */
  555. sighandler_t old = signal(SIGHUP, SIG_IGN);
  556. ioctl(fd, TIOCNOTTY);
  557. close(fd);
  558. signal(SIGHUP, old);
  559. }
  560. }
  561. /* Close stdio, and stray descriptors, just in case */
  562. n = xopen(bb_dev_null, O_RDWR);
  563. /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
  564. xdup2(n, 1);
  565. xdup2(n, 2);
  566. while (n > 2)
  567. close(n--);
  568. /* Logging. We want special flavor of error_msg_and_die */
  569. die_func = sleep10;
  570. msg_eol = "\r\n";
  571. /* most likely will internally use fd #3 in CLOEXEC mode: */
  572. openlog(applet_name, LOG_PID, LOG_AUTH);
  573. logmode = LOGMODE_BOTH;
  574. #ifdef DEBUGGING
  575. dbf = xfopen_for_write(DEBUGTERM);
  576. for (n = 1; argv[n]; n++) {
  577. debug(argv[n]);
  578. debug("\n");
  579. }
  580. #endif
  581. /* Open the tty as standard input, if it is not "-" */
  582. debug("calling open_tty\n");
  583. open_tty();
  584. ndelay_off(STDIN_FILENO);
  585. debug("duping\n");
  586. xdup2(STDIN_FILENO, 1);
  587. xdup2(STDIN_FILENO, 2);
  588. /* Steal ctty if we don't have it yet */
  589. tsid = tcgetsid(STDIN_FILENO);
  590. if (tsid < 0 || pid != tsid) {
  591. if (ioctl(STDIN_FILENO, TIOCSCTTY, /*force:*/ (long)1) < 0)
  592. bb_perror_msg_and_die("TIOCSCTTY");
  593. }
  594. #ifdef __linux__
  595. /* Make ourself a foreground process group within our session */
  596. if (tcsetpgrp(STDIN_FILENO, pid) < 0)
  597. bb_perror_msg_and_die("tcsetpgrp");
  598. #endif
  599. /*
  600. * The following ioctl will fail if stdin is not a tty, but also when
  601. * there is noise on the modem control lines. In the latter case, the
  602. * common course of action is (1) fix your cables (2) give the modem more
  603. * time to properly reset after hanging up. SunOS users can achieve (2)
  604. * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
  605. * 5 seconds seems to be a good value.
  606. */
  607. if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0)
  608. bb_perror_msg_and_die("tcgetattr");
  609. /* Update the utmp file. This tty is ours now! */
  610. update_utmp(pid, LOGIN_PROCESS, G.tty_name, "LOGIN", G.fakehost);
  611. /* Initialize tty attrs (raw mode, eight-bit, blocking i/o) */
  612. debug("calling init_tty_attrs\n");
  613. init_tty_attrs(G.speeds[0]);
  614. /* Write the modem init string and DON'T flush the buffers */
  615. if (option_mask32 & F_INITSTRING) {
  616. debug("writing init string\n");
  617. full_write1_str(G.initstring);
  618. }
  619. /* Optionally detect the baud rate from the modem status message */
  620. debug("before autobaud\n");
  621. if (option_mask32 & F_PARSE)
  622. auto_baud();
  623. /* Set the optional timer */
  624. signal(SIGALRM, alarm_handler);
  625. alarm(G.timeout); /* if 0, alarm is not set */
  626. /* Optionally wait for CR or LF before writing /etc/issue */
  627. if (option_mask32 & F_WAITCRLF) {
  628. char ch;
  629. debug("waiting for cr-lf\n");
  630. while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
  631. debug("read %x\n", (unsigned char)ch);
  632. if (ch == '\n' || ch == '\r')
  633. break;
  634. }
  635. }
  636. logname = NULL;
  637. if (!(option_mask32 & F_NOPROMPT)) {
  638. /* NB: init_tty_attrs already set line speed
  639. * to G.speeds[0] */
  640. int baud_index = 0;
  641. while (1) {
  642. /* Read the login name */
  643. debug("reading login name\n");
  644. logname = get_logname();
  645. if (logname)
  646. break;
  647. /* We are here only if G.numspeed > 1 */
  648. baud_index = (baud_index + 1) % G.numspeed;
  649. cfsetspeed(&G.tty_attrs, G.speeds[baud_index]);
  650. set_tty_attrs();
  651. }
  652. }
  653. /* Disable timer */
  654. alarm(0);
  655. finalize_tty_attrs();
  656. /* Let the login program take care of password validation */
  657. /* We use PATH because we trust that root doesn't set "bad" PATH,
  658. * and getty is not suid-root applet */
  659. /* With -n, logname == NULL, and login will ask for username instead */
  660. BB_EXECLP(G.login, G.login, "--", logname, (char *)0);
  661. bb_error_msg_and_die("can't execute '%s'", G.login);
  662. }