getty.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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 (10 kb)"
  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. #define OPT_STR "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. flags = getopt32(argv, "^" OPT_STR "\0" "-2"/* at least 2 args*/,
  162. &G.initstring, &G.fakehost, &G.issue,
  163. &G.login, &G.timeout
  164. );
  165. if (flags & F_INITSTRING) {
  166. G.initstring = xstrdup(G.initstring);
  167. /* decode \ddd octal codes into chars */
  168. strcpy_and_process_escape_sequences(G.initstring, G.initstring);
  169. }
  170. argv += optind;
  171. debug("after getopt\n");
  172. /* We loosen up a bit and accept both "baudrate tty" and "tty baudrate" */
  173. G.tty_name = argv[0];
  174. ts = argv[1]; /* baud rate(s) */
  175. if (isdigit(argv[0][0])) {
  176. /* A number first, assume it's a speed (BSD style) */
  177. G.tty_name = ts; /* tty name is in argv[1] */
  178. ts = argv[0]; /* baud rate(s) */
  179. }
  180. parse_speeds(ts);
  181. if (argv[2])
  182. xsetenv("TERM", argv[2]);
  183. debug("exiting parse_args\n");
  184. }
  185. /* set up tty as standard input, output, error */
  186. static void open_tty(void)
  187. {
  188. /* Set up new standard input, unless we are given an already opened port */
  189. if (NOT_LONE_DASH(G.tty_name)) {
  190. if (G.tty_name[0] != '/')
  191. G.tty_name = xasprintf("/dev/%s", G.tty_name); /* will leak it */
  192. /* Open the tty as standard input */
  193. debug("open(2)\n");
  194. close(0);
  195. xopen(G.tty_name, O_RDWR | O_NONBLOCK); /* uses fd 0 */
  196. /* Set proper protections and ownership */
  197. fchown(0, 0, 0); /* 0:0 */
  198. fchmod(0, 0620); /* crw--w---- */
  199. } else {
  200. char *n;
  201. /*
  202. * Standard input should already be connected to an open port.
  203. * Make sure it is open for read/write.
  204. */
  205. if ((fcntl(0, F_GETFL) & (O_RDWR|O_RDONLY|O_WRONLY)) != O_RDWR)
  206. bb_error_msg_and_die("stdin is not open for read/write");
  207. /* Try to get real tty name instead of "-" */
  208. n = xmalloc_ttyname(0);
  209. if (n)
  210. G.tty_name = n;
  211. }
  212. applet_name = xasprintf("getty: %s", skip_dev_pfx(G.tty_name));
  213. }
  214. static void set_tty_attrs(void)
  215. {
  216. if (tcsetattr_stdin_TCSANOW(&G.tty_attrs) < 0)
  217. bb_perror_msg_and_die("tcsetattr");
  218. }
  219. /* We manipulate tty_attrs this way:
  220. * - first, we read existing tty_attrs
  221. * - init_tty_attrs modifies some parts and sets it
  222. * - auto_baud and/or BREAK processing can set different speed and set tty attrs
  223. * - finalize_tty_attrs again modifies some parts and sets tty attrs before
  224. * execing login
  225. */
  226. static void init_tty_attrs(int speed)
  227. {
  228. /* Try to drain output buffer, with 5 sec timeout.
  229. * Added on request from users of ~600 baud serial interface
  230. * with biggish buffer on a 90MHz CPU.
  231. * They were losing hundreds of bytes of buffered output
  232. * on tcflush.
  233. */
  234. signal_no_SA_RESTART_empty_mask(SIGALRM, record_signo);
  235. alarm(5);
  236. tcdrain(STDIN_FILENO);
  237. alarm(0);
  238. /* Flush input and output queues, important for modems! */
  239. tcflush(STDIN_FILENO, TCIOFLUSH);
  240. /* Set speed if it wasn't specified as "0" on command line */
  241. if (speed != B0)
  242. cfsetspeed(&G.tty_attrs, speed);
  243. /* Initial settings: 8-bit characters, raw mode, blocking i/o.
  244. * Special characters are set after we have read the login name; all
  245. * reads will be done in raw mode anyway.
  246. */
  247. /* Clear all bits except: */
  248. G.tty_attrs.c_cflag &= (0
  249. /* 2 stop bits (1 otherwise)
  250. * Enable parity bit (both on input and output)
  251. * Odd parity (else even)
  252. */
  253. | CSTOPB | PARENB | PARODD
  254. #ifdef CMSPAR
  255. | CMSPAR /* mark or space parity */
  256. #endif
  257. #ifdef CBAUD
  258. | CBAUD /* (output) baud rate */
  259. #endif
  260. #ifdef CBAUDEX
  261. | CBAUDEX /* (output) baud rate */
  262. #endif
  263. #ifdef CIBAUD
  264. | CIBAUD /* input baud rate */
  265. #endif
  266. );
  267. /* Set: 8 bits; hang up (drop DTR) on last close; enable receive */
  268. G.tty_attrs.c_cflag |= CS8 | HUPCL | CREAD;
  269. if (option_mask32 & F_LOCAL) {
  270. /* ignore Carrier Detect pin:
  271. * opens don't block when CD is low,
  272. * losing CD doesn't hang up processes whose ctty is this tty
  273. */
  274. G.tty_attrs.c_cflag |= CLOCAL;
  275. }
  276. #ifdef CRTSCTS
  277. if (option_mask32 & F_RTSCTS)
  278. G.tty_attrs.c_cflag |= CRTSCTS; /* flow control using RTS/CTS pins */
  279. #endif
  280. G.tty_attrs.c_iflag = 0;
  281. G.tty_attrs.c_lflag = 0;
  282. /* non-raw output; add CR to each NL */
  283. G.tty_attrs.c_oflag = OPOST | ONLCR;
  284. /* reads will block only if < 1 char is available */
  285. G.tty_attrs.c_cc[VMIN] = 1;
  286. /* no timeout (reads block forever) */
  287. G.tty_attrs.c_cc[VTIME] = 0;
  288. #ifdef __linux__
  289. G.tty_attrs.c_line = 0;
  290. #endif
  291. set_tty_attrs();
  292. debug("term_io 2\n");
  293. }
  294. static void finalize_tty_attrs(void)
  295. {
  296. /* software flow control on output (stop sending if XOFF is recvd);
  297. * and on input (send XOFF when buffer is full)
  298. */
  299. G.tty_attrs.c_iflag |= IXON | IXOFF;
  300. if (G.eol == '\r') {
  301. G.tty_attrs.c_iflag |= ICRNL; /* map CR on input to NL */
  302. }
  303. /* Other bits in c_iflag:
  304. * IXANY Any recvd char enables output (any char is also a XON)
  305. * INPCK Enable parity check
  306. * IGNPAR Ignore parity errors (drop bad bytes)
  307. * PARMRK Mark parity errors with 0xff, 0x00 prefix
  308. * (else bad byte is received as 0x00)
  309. * ISTRIP Strip parity bit
  310. * IGNBRK Ignore break condition
  311. * BRKINT Send SIGINT on break - maybe set this?
  312. * INLCR Map NL to CR
  313. * IGNCR Ignore CR
  314. * ICRNL Map CR to NL
  315. * IUCLC Map uppercase to lowercase
  316. * IMAXBEL Echo BEL on input line too long
  317. * IUTF8 Appears to affect tty's idea of char widths,
  318. * observed to improve backspacing through Unicode chars
  319. */
  320. /* ICANON line buffered input (NL or EOL or EOF chars end a line);
  321. * ISIG recognize INT/QUIT/SUSP chars;
  322. * ECHO echo input chars;
  323. * ECHOE echo BS-SP-BS on erase character;
  324. * ECHOK echo kill char specially, not as ^c (ECHOKE controls how exactly);
  325. * ECHOKE erase all input via BS-SP-BS on kill char (else go to next line)
  326. * ECHOCTL Echo ctrl chars as ^c (else echo verbatim:
  327. * e.g. up arrow emits "ESC-something" and thus moves cursor up!)
  328. */
  329. G.tty_attrs.c_lflag |= ICANON | ISIG | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL;
  330. /* Other bits in c_lflag:
  331. * XCASE Map uppercase to \lowercase [tried, doesn't work]
  332. * ECHONL Echo NL even if ECHO is not set
  333. * ECHOPRT On erase, echo erased chars
  334. * [qwe<BS><BS><BS> input looks like "qwe\ewq/" on screen]
  335. * NOFLSH Don't flush input buffer after interrupt or quit chars
  336. * IEXTEN Enable extended functions (??)
  337. * [glibc says it enables c_cc[LNEXT] "enter literal char"
  338. * and c_cc[VDISCARD] "toggle discard buffered output" chars]
  339. * FLUSHO Output being flushed (c_cc[VDISCARD] is in effect)
  340. * PENDIN Retype pending input at next read or input char
  341. * (c_cc[VREPRINT] is being processed)
  342. * TOSTOP Send SIGTTOU for background output
  343. * (why "stty sane" unsets this bit?)
  344. */
  345. G.tty_attrs.c_cc[VINTR] = CTL('C');
  346. G.tty_attrs.c_cc[VQUIT] = CTL('\\');
  347. G.tty_attrs.c_cc[VEOF] = CTL('D');
  348. G.tty_attrs.c_cc[VEOL] = '\n';
  349. #ifdef VSWTC
  350. G.tty_attrs.c_cc[VSWTC] = 0;
  351. #endif
  352. #ifdef VSWTCH
  353. G.tty_attrs.c_cc[VSWTCH] = 0;
  354. #endif
  355. G.tty_attrs.c_cc[VKILL] = CTL('U');
  356. /* Other control chars:
  357. * VEOL2
  358. * VERASE, VWERASE - (word) erase. we may set VERASE in get_logname
  359. * VREPRINT - reprint current input buffer
  360. * VLNEXT, VDISCARD, VSTATUS
  361. * VSUSP, VDSUSP - send (delayed) SIGTSTP
  362. * VSTART, VSTOP - chars used for IXON/IXOFF
  363. */
  364. set_tty_attrs();
  365. /* Now the newline character should be properly written */
  366. full_write(STDOUT_FILENO, "\n", 1);
  367. }
  368. /* extract baud rate from modem status message */
  369. static void auto_baud(void)
  370. {
  371. int nread;
  372. /*
  373. * This works only if the modem produces its status code AFTER raising
  374. * the DCD line, and if the computer is fast enough to set the proper
  375. * baud rate before the message has gone by. We expect a message of the
  376. * following format:
  377. *
  378. * <junk><number><junk>
  379. *
  380. * The number is interpreted as the baud rate of the incoming call. If the
  381. * modem does not tell us the baud rate within one second, we will keep
  382. * using the current baud rate. It is advisable to enable BREAK
  383. * processing (comma-separated list of baud rates) if the processing of
  384. * modem status messages is enabled.
  385. */
  386. G.tty_attrs.c_cc[VMIN] = 0; /* don't block reads (min read is 0 chars) */
  387. set_tty_attrs();
  388. /*
  389. * Wait for a while, then read everything the modem has said so far and
  390. * try to extract the speed of the dial-in call.
  391. */
  392. sleep(1);
  393. nread = safe_read(STDIN_FILENO, G.line_buf, sizeof(G.line_buf) - 1);
  394. if (nread > 0) {
  395. int speed;
  396. char *bp;
  397. G.line_buf[nread] = '\0';
  398. for (bp = G.line_buf; bp < G.line_buf + nread; bp++) {
  399. if (isdigit(*bp)) {
  400. speed = bcode(bp);
  401. if (speed > 0)
  402. cfsetspeed(&G.tty_attrs, speed);
  403. break;
  404. }
  405. }
  406. }
  407. /* Restore terminal settings */
  408. G.tty_attrs.c_cc[VMIN] = 1; /* restore to value set by init_tty_attrs */
  409. set_tty_attrs();
  410. }
  411. /* get user name, establish parity, speed, erase, kill, eol;
  412. * return NULL on BREAK, logname on success
  413. */
  414. static char *get_logname(void)
  415. {
  416. char *bp;
  417. char c;
  418. /* Flush pending input (esp. after parsing or switching the baud rate) */
  419. usleep(100*1000); /* 0.1 sec */
  420. tcflush(STDIN_FILENO, TCIFLUSH);
  421. /* Prompt for and read a login name */
  422. do {
  423. /* Write issue file and prompt */
  424. #ifdef ISSUE
  425. if (!(option_mask32 & F_NOISSUE))
  426. print_login_issue(G.issue, G.tty_name);
  427. #endif
  428. print_login_prompt();
  429. /* Read name, watch for break, erase, kill, end-of-line */
  430. bp = G.line_buf;
  431. while (1) {
  432. /* Do not report trivial EINTR/EIO errors */
  433. errno = EINTR; /* make read of 0 bytes be silent too */
  434. if (read(STDIN_FILENO, &c, 1) < 1) {
  435. finalize_tty_attrs();
  436. if (errno == EINTR || errno == EIO)
  437. exit(EXIT_SUCCESS);
  438. bb_perror_msg_and_die(bb_msg_read_error);
  439. }
  440. switch (c) {
  441. case '\r':
  442. case '\n':
  443. *bp = '\0';
  444. G.eol = c;
  445. goto got_logname;
  446. case CTL('H'):
  447. case 0x7f:
  448. G.tty_attrs.c_cc[VERASE] = c;
  449. if (bp > G.line_buf) {
  450. full_write(STDOUT_FILENO, "\010 \010", 3);
  451. bp--;
  452. }
  453. break;
  454. case CTL('U'):
  455. while (bp > G.line_buf) {
  456. full_write(STDOUT_FILENO, "\010 \010", 3);
  457. bp--;
  458. }
  459. break;
  460. case CTL('C'):
  461. case CTL('D'):
  462. finalize_tty_attrs();
  463. exit(EXIT_SUCCESS);
  464. case '\0':
  465. /* BREAK. If we have speeds to try,
  466. * return NULL (will switch speeds and return here) */
  467. if (G.numspeed > 1)
  468. return NULL;
  469. /* fall through and ignore it */
  470. default:
  471. if ((unsigned char)c < ' ') {
  472. /* ignore garbage characters */
  473. } else if ((int)(bp - G.line_buf) < sizeof(G.line_buf) - 1) {
  474. /* echo and store the character */
  475. full_write(STDOUT_FILENO, &c, 1);
  476. *bp++ = c;
  477. }
  478. break;
  479. }
  480. } /* end of get char loop */
  481. got_logname: ;
  482. } while (G.line_buf[0] == '\0'); /* while logname is empty */
  483. return G.line_buf;
  484. }
  485. static void alarm_handler(int sig UNUSED_PARAM)
  486. {
  487. finalize_tty_attrs();
  488. _exit(EXIT_SUCCESS);
  489. }
  490. static void sleep10(void)
  491. {
  492. sleep(10);
  493. }
  494. int getty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  495. int getty_main(int argc UNUSED_PARAM, char **argv)
  496. {
  497. int n;
  498. pid_t pid, tsid;
  499. char *logname;
  500. INIT_G();
  501. G.login = _PATH_LOGIN; /* default login program */
  502. #ifdef ISSUE
  503. G.issue = ISSUE; /* default issue file */
  504. #endif
  505. G.eol = '\r';
  506. /* Parse command-line arguments */
  507. parse_args(argv);
  508. /* Create new session and pgrp, lose controlling tty */
  509. pid = setsid(); /* this also gives us our pid :) */
  510. if (pid < 0) {
  511. int fd;
  512. /* :(
  513. * docs/ctty.htm says:
  514. * "This is allowed only when the current process
  515. * is not a process group leader".
  516. * Thus, setsid() will fail if we _already_ are
  517. * a session leader - which is quite possible for getty!
  518. */
  519. pid = getpid();
  520. if (getsid(0) != pid) {
  521. //for debugging:
  522. //bb_perror_msg_and_die("setsid failed:"
  523. // " pid %d ppid %d"
  524. // " sid %d pgid %d",
  525. // pid, getppid(),
  526. // getsid(0), getpgid(0));
  527. bb_perror_msg_and_die("setsid");
  528. /*
  529. * When we can end up here?
  530. * Example: setsid() fails when run alone in interactive shell:
  531. * # getty 115200 /dev/tty2
  532. * because shell's child (getty) is put in a new process group.
  533. * But doesn't fail if shell is not interactive
  534. * (and therefore doesn't create process groups for pipes),
  535. * or if getty is not the first process in the process group:
  536. * # true | getty 115200 /dev/tty2
  537. */
  538. }
  539. /* Looks like we are already a session leader.
  540. * In this case (setsid failed) we may still have ctty,
  541. * and it may be different from tty we need to control!
  542. * If we still have ctty, on Linux ioctl(TIOCSCTTY)
  543. * (which we are going to use a bit later) always fails -
  544. * even if we try to take ctty which is already ours!
  545. * Try to drop old ctty now to prevent that.
  546. * Use O_NONBLOCK: old ctty may be a serial line.
  547. */
  548. fd = open("/dev/tty", O_RDWR | O_NONBLOCK);
  549. if (fd >= 0) {
  550. /* TIOCNOTTY sends SIGHUP to the foreground
  551. * process group - which may include us!
  552. * Make sure to not die on it:
  553. */
  554. sighandler_t old = signal(SIGHUP, SIG_IGN);
  555. ioctl(fd, TIOCNOTTY);
  556. close(fd);
  557. signal(SIGHUP, old);
  558. }
  559. }
  560. /* Close stdio, and stray descriptors, just in case */
  561. n = xopen(bb_dev_null, O_RDWR);
  562. /* dup2(n, 0); - no, we need to handle "getty - 9600" too */
  563. xdup2(n, 1);
  564. xdup2(n, 2);
  565. while (n > 2)
  566. close(n--);
  567. /* Logging. We want special flavor of error_msg_and_die */
  568. die_func = sleep10;
  569. msg_eol = "\r\n";
  570. /* most likely will internally use fd #3 in CLOEXEC mode: */
  571. openlog(applet_name, LOG_PID, LOG_AUTH);
  572. logmode = LOGMODE_BOTH;
  573. #ifdef DEBUGGING
  574. dbf = xfopen_for_write(DEBUGTERM);
  575. for (n = 1; argv[n]; n++) {
  576. debug(argv[n]);
  577. debug("\n");
  578. }
  579. #endif
  580. /* Open the tty as standard input, if it is not "-" */
  581. debug("calling open_tty\n");
  582. open_tty();
  583. ndelay_off(STDIN_FILENO);
  584. debug("duping\n");
  585. xdup2(STDIN_FILENO, 1);
  586. xdup2(STDIN_FILENO, 2);
  587. /* Steal ctty if we don't have it yet */
  588. tsid = tcgetsid(STDIN_FILENO);
  589. if (tsid < 0 || pid != tsid) {
  590. if (ioctl(STDIN_FILENO, TIOCSCTTY, /*force:*/ (long)1) < 0)
  591. bb_perror_msg_and_die("TIOCSCTTY");
  592. }
  593. #ifdef __linux__
  594. /* Make ourself a foreground process group within our session */
  595. if (tcsetpgrp(STDIN_FILENO, pid) < 0)
  596. bb_perror_msg_and_die("tcsetpgrp");
  597. #endif
  598. /*
  599. * The following ioctl will fail if stdin is not a tty, but also when
  600. * there is noise on the modem control lines. In the latter case, the
  601. * common course of action is (1) fix your cables (2) give the modem more
  602. * time to properly reset after hanging up. SunOS users can achieve (2)
  603. * by patching the SunOS kernel variable "zsadtrlow" to a larger value;
  604. * 5 seconds seems to be a good value.
  605. */
  606. if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0)
  607. bb_perror_msg_and_die("tcgetattr");
  608. /* Update the utmp file. This tty is ours now! */
  609. update_utmp(pid, LOGIN_PROCESS, G.tty_name, "LOGIN", G.fakehost);
  610. /* Initialize tty attrs (raw mode, eight-bit, blocking i/o) */
  611. debug("calling init_tty_attrs\n");
  612. init_tty_attrs(G.speeds[0]);
  613. /* Write the modem init string and DON'T flush the buffers */
  614. if (option_mask32 & F_INITSTRING) {
  615. debug("writing init string\n");
  616. full_write1_str(G.initstring);
  617. }
  618. /* Optionally detect the baud rate from the modem status message */
  619. debug("before autobaud\n");
  620. if (option_mask32 & F_PARSE)
  621. auto_baud();
  622. /* Set the optional timer */
  623. signal(SIGALRM, alarm_handler);
  624. alarm(G.timeout); /* if 0, alarm is not set */
  625. /* Optionally wait for CR or LF before writing /etc/issue */
  626. if (option_mask32 & F_WAITCRLF) {
  627. char ch;
  628. debug("waiting for cr-lf\n");
  629. while (safe_read(STDIN_FILENO, &ch, 1) == 1) {
  630. debug("read %x\n", (unsigned char)ch);
  631. if (ch == '\n' || ch == '\r')
  632. break;
  633. }
  634. }
  635. logname = NULL;
  636. if (!(option_mask32 & F_NOPROMPT)) {
  637. /* NB: init_tty_attrs already set line speed
  638. * to G.speeds[0] */
  639. int baud_index = 0;
  640. while (1) {
  641. /* Read the login name */
  642. debug("reading login name\n");
  643. logname = get_logname();
  644. if (logname)
  645. break;
  646. /* We are here only if G.numspeed > 1 */
  647. baud_index = (baud_index + 1) % G.numspeed;
  648. cfsetspeed(&G.tty_attrs, G.speeds[baud_index]);
  649. set_tty_attrs();
  650. }
  651. }
  652. /* Disable timer */
  653. alarm(0);
  654. finalize_tty_attrs();
  655. /* Let the login program take care of password validation */
  656. /* We use PATH because we trust that root doesn't set "bad" PATH,
  657. * and getty is not suid-root applet */
  658. /* With -n, logname == NULL, and login will ask for username instead */
  659. BB_EXECLP(G.login, G.login, "--", logname, (char *)0);
  660. bb_error_msg_and_die("can't execute '%s'", G.login);
  661. }