pty.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  1. /*
  2. * Pseudo-tty backend for pterm.
  3. */
  4. #define _GNU_SOURCE
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9. #include <signal.h>
  10. #include <assert.h>
  11. #include <fcntl.h>
  12. #include <termios.h>
  13. #include <grp.h>
  14. #if HAVE_UTMP_H
  15. #include <utmp.h>
  16. #endif
  17. #include <pwd.h>
  18. #include <time.h>
  19. #include <sys/types.h>
  20. #include <sys/stat.h>
  21. #include <sys/wait.h>
  22. #include <sys/ioctl.h>
  23. #include <errno.h>
  24. #include <termios.h>
  25. #include "putty.h"
  26. #include "ssh.h"
  27. #include "ssh/server.h" /* to check the prototypes of server-needed things */
  28. #include "tree234.h"
  29. #ifndef OMIT_UTMP
  30. #include <utmpx.h>
  31. #endif
  32. /* updwtmpx() needs the name of the wtmp file. Try to find it. */
  33. #ifndef WTMPX_FILE
  34. #ifdef _PATH_WTMPX
  35. #define WTMPX_FILE _PATH_WTMPX
  36. #else
  37. #define WTMPX_FILE "/var/log/wtmpx"
  38. #endif
  39. #endif
  40. #ifndef LASTLOG_FILE
  41. #ifdef _PATH_LASTLOG
  42. #define LASTLOG_FILE _PATH_LASTLOG
  43. #else
  44. #define LASTLOG_FILE "/var/log/lastlog"
  45. #endif
  46. #endif
  47. typedef struct Pty Pty;
  48. /*
  49. * The pty_signal_pipe, along with the SIGCHLD handler, must be
  50. * process-global rather than session-specific.
  51. */
  52. static int pty_signal_pipe[2] = { -1, -1 }; /* obviously bogus initial val */
  53. typedef struct PtyFd {
  54. int fd;
  55. Pty *pty;
  56. } PtyFd;
  57. struct Pty {
  58. Conf *conf;
  59. int master_fd, slave_fd;
  60. int pipefds[6];
  61. PtyFd fds[3];
  62. int master_i, master_o, master_e;
  63. Seat *seat;
  64. size_t output_backlog;
  65. char name[FILENAME_MAX];
  66. pid_t child_pid;
  67. int term_width, term_height;
  68. bool child_dead, finished;
  69. int exit_code;
  70. bufchain output_data;
  71. bool pending_eof;
  72. Backend backend;
  73. };
  74. #define PTY_MAX_BACKLOG 32768
  75. /*
  76. * We store all the (active) PtyFd structures in a tree sorted by fd,
  77. * so that when we get an uxsel notification we know which backend
  78. * instance is the owner of the pty that caused it, and then we can
  79. * find out which fd is the relevant one too.
  80. */
  81. static int ptyfd_compare(void *av, void *bv)
  82. {
  83. PtyFd *a = (PtyFd *)av;
  84. PtyFd *b = (PtyFd *)bv;
  85. if (a->fd < b->fd)
  86. return -1;
  87. else if (a->fd > b->fd)
  88. return +1;
  89. return 0;
  90. }
  91. static int ptyfd_find(void *av, void *bv)
  92. {
  93. int a = *(int *)av;
  94. PtyFd *b = (PtyFd *)bv;
  95. if (a < b->fd)
  96. return -1;
  97. else if (a > b->fd)
  98. return +1;
  99. return 0;
  100. }
  101. static tree234 *ptyfds = NULL;
  102. /*
  103. * We also have a tree of Pty structures themselves, sorted by child
  104. * pid, so that when we wait() in response to the signal we know which
  105. * backend instance is the owner of the process that caused the
  106. * signal.
  107. */
  108. static int pty_compare_by_pid(void *av, void *bv)
  109. {
  110. Pty *a = (Pty *)av;
  111. Pty *b = (Pty *)bv;
  112. if (a->child_pid < b->child_pid)
  113. return -1;
  114. else if (a->child_pid > b->child_pid)
  115. return +1;
  116. return 0;
  117. }
  118. static int pty_find_by_pid(void *av, void *bv)
  119. {
  120. pid_t a = *(pid_t *)av;
  121. Pty *b = (Pty *)bv;
  122. if (a < b->child_pid)
  123. return -1;
  124. else if (a > b->child_pid)
  125. return +1;
  126. return 0;
  127. }
  128. static tree234 *ptys_by_pid = NULL;
  129. /*
  130. * If we are using pty_pre_init(), it will need to have already
  131. * allocated a pty structure, which we must then return from
  132. * pty_init() rather than allocating a new one. Here we store that
  133. * structure between allocation and use.
  134. *
  135. * Note that although most of this module is entirely capable of
  136. * handling multiple ptys in a single process, pty_pre_init() is
  137. * fundamentally _dependent_ on there being at most one pty per
  138. * process, so the normal static-data constraints don't apply.
  139. *
  140. * Likewise, since utmp is only used via pty_pre_init, it too must
  141. * be single-instance, so we can declare utmp-related variables
  142. * here.
  143. */
  144. static Pty *single_pty = NULL;
  145. #ifndef OMIT_UTMP
  146. static pid_t pty_utmp_helper_pid = -1;
  147. static int pty_utmp_helper_pipe = -1;
  148. static bool pty_stamped_utmp;
  149. static struct utmpx utmp_entry;
  150. #endif
  151. /*
  152. * pty_argv is a grievous hack to allow a proper argv to be passed
  153. * through from the Unix command line. Again, it doesn't really
  154. * make sense outside a one-pty-per-process setup.
  155. */
  156. char **pty_argv;
  157. char *pty_osx_envrestore_prefix;
  158. static void pty_close(Pty *pty);
  159. static void pty_try_write(Pty *pty);
  160. #ifndef OMIT_UTMP
  161. static void setup_utmp(char *ttyname, char *location)
  162. {
  163. #if HAVE_LASTLOG
  164. struct lastlog lastlog_entry;
  165. FILE *lastlog;
  166. #endif
  167. struct passwd *pw;
  168. struct timeval tv;
  169. pw = getpwuid(getuid());
  170. if (!pw)
  171. return; /* can't stamp utmp if we don't have a username */
  172. memset(&utmp_entry, 0, sizeof(utmp_entry));
  173. utmp_entry.ut_type = USER_PROCESS;
  174. utmp_entry.ut_pid = getpid();
  175. #if __GNUC__ >= 8
  176. # pragma GCC diagnostic push
  177. # pragma GCC diagnostic ignored "-Wstringop-truncation"
  178. #endif // __GNUC__ >= 8
  179. strncpy(utmp_entry.ut_line, ttyname+5, lenof(utmp_entry.ut_line));
  180. strncpy(utmp_entry.ut_id, ttyname+8, lenof(utmp_entry.ut_id));
  181. strncpy(utmp_entry.ut_user, pw->pw_name, lenof(utmp_entry.ut_user));
  182. strncpy(utmp_entry.ut_host, location, lenof(utmp_entry.ut_host));
  183. #if __GNUC__ >= 8
  184. # pragma GCC diagnostic pop
  185. #endif // __GNUC__ >= 8
  186. /*
  187. * Apparently there are some architectures where (struct
  188. * utmpx).ut_tv is not essentially struct timeval (e.g. Linux
  189. * amd64). Hence the temporary.
  190. */
  191. gettimeofday(&tv, NULL);
  192. utmp_entry.ut_tv.tv_sec = tv.tv_sec;
  193. utmp_entry.ut_tv.tv_usec = tv.tv_usec;
  194. setutxent();
  195. pututxline(&utmp_entry);
  196. endutxent();
  197. #if HAVE_UPDWTMPX
  198. /* Reportedly, AIX 5.1 has <utmpx.h> and pututxline(), but no
  199. * updwtmpx(). */
  200. updwtmpx(WTMPX_FILE, &utmp_entry);
  201. #endif
  202. #if HAVE_LASTLOG
  203. memset(&lastlog_entry, 0, sizeof(lastlog_entry));
  204. strncpy(lastlog_entry.ll_line, ttyname+5, lenof(lastlog_entry.ll_line));
  205. strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host));
  206. time(&lastlog_entry.ll_time);
  207. if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) {
  208. fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET);
  209. fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog);
  210. fclose(lastlog);
  211. }
  212. #endif
  213. pty_stamped_utmp = true;
  214. }
  215. static void cleanup_utmp(void)
  216. {
  217. struct timeval tv;
  218. if (!pty_stamped_utmp)
  219. return;
  220. utmp_entry.ut_type = DEAD_PROCESS;
  221. memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user));
  222. gettimeofday(&tv, NULL);
  223. utmp_entry.ut_tv.tv_sec = tv.tv_sec;
  224. utmp_entry.ut_tv.tv_usec = tv.tv_usec;
  225. #if HAVE_UPDWTMPX
  226. updwtmpx(WTMPX_FILE, &utmp_entry);
  227. #endif
  228. memset(utmp_entry.ut_line, 0, lenof(utmp_entry.ut_line));
  229. utmp_entry.ut_tv.tv_sec = 0;
  230. utmp_entry.ut_tv.tv_usec = 0;
  231. setutxent();
  232. pututxline(&utmp_entry);
  233. endutxent();
  234. pty_stamped_utmp = false; /* ensure we never double-cleanup */
  235. }
  236. #endif
  237. static void sigchld_handler(int signum)
  238. {
  239. if (write(pty_signal_pipe[1], "x", 1) <= 0)
  240. /* not much we can do about it */;
  241. }
  242. static void pty_setup_sigchld_handler(void)
  243. {
  244. static bool setup = false;
  245. if (!setup) {
  246. putty_signal(SIGCHLD, sigchld_handler);
  247. setup = true;
  248. }
  249. }
  250. #ifndef OMIT_UTMP
  251. static void fatal_sig_handler(int signum)
  252. {
  253. putty_signal(signum, SIG_DFL);
  254. cleanup_utmp();
  255. raise(signum);
  256. }
  257. #endif
  258. static int pty_open_slave(Pty *pty)
  259. {
  260. if (pty->slave_fd < 0) {
  261. pty->slave_fd = open(pty->name, O_RDWR);
  262. cloexec(pty->slave_fd);
  263. }
  264. return pty->slave_fd;
  265. }
  266. static void pty_open_master(Pty *pty)
  267. {
  268. #ifdef BSD_PTYS
  269. const char chars1[] = "pqrstuvwxyz";
  270. const char chars2[] = "0123456789abcdef";
  271. const char *p1, *p2;
  272. char master_name[20];
  273. struct group *gp;
  274. for (p1 = chars1; *p1; p1++)
  275. for (p2 = chars2; *p2; p2++) {
  276. sprintf(master_name, "/dev/pty%c%c", *p1, *p2);
  277. pty->master_fd = open(master_name, O_RDWR);
  278. if (pty->master_fd >= 0) {
  279. if (geteuid() == 0 ||
  280. access(master_name, R_OK | W_OK) == 0) {
  281. /*
  282. * We must also check at this point that we are
  283. * able to open the slave side of the pty. We
  284. * wouldn't want to allocate the wrong master,
  285. * get all the way down to forking, and _then_
  286. * find we're unable to open the slave.
  287. */
  288. strcpy(pty->name, master_name);
  289. pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */
  290. cloexec(pty->master_fd);
  291. if (pty_open_slave(pty) >= 0 &&
  292. access(pty->name, R_OK | W_OK) == 0)
  293. goto got_one;
  294. if (pty->slave_fd > 0)
  295. close(pty->slave_fd);
  296. pty->slave_fd = -1;
  297. }
  298. close(pty->master_fd);
  299. }
  300. }
  301. /* If we get here, we couldn't get a tty at all. */
  302. fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n");
  303. exit(1);
  304. got_one:
  305. /* We need to chown/chmod the /dev/ttyXX device. */
  306. gp = getgrnam("tty");
  307. chown(pty->name, getuid(), gp ? gp->gr_gid : -1);
  308. chmod(pty->name, 0600);
  309. #else
  310. const int flags = O_RDWR
  311. #ifdef O_NOCTTY
  312. | O_NOCTTY
  313. #endif
  314. ;
  315. #if HAVE_POSIX_OPENPT
  316. #ifdef SET_NONBLOCK_VIA_OPENPT
  317. /*
  318. * OS X, as of 10.10 at least, doesn't permit me to set O_NONBLOCK
  319. * on pty master fds via the usual fcntl mechanism. Fortunately,
  320. * it does let me work around this by adding O_NONBLOCK to the
  321. * posix_openpt flags parameter, which isn't a documented use of
  322. * the API but seems to work. So we'll do that for now.
  323. */
  324. pty->master_fd = posix_openpt(flags | O_NONBLOCK);
  325. #else
  326. pty->master_fd = posix_openpt(flags);
  327. #endif
  328. if (pty->master_fd < 0) {
  329. perror("posix_openpt");
  330. exit(1);
  331. }
  332. #else
  333. pty->master_fd = open("/dev/ptmx", flags);
  334. if (pty->master_fd < 0) {
  335. perror("/dev/ptmx: open");
  336. exit(1);
  337. }
  338. #endif
  339. if (grantpt(pty->master_fd) < 0) {
  340. perror("grantpt");
  341. exit(1);
  342. }
  343. if (unlockpt(pty->master_fd) < 0) {
  344. perror("unlockpt");
  345. exit(1);
  346. }
  347. cloexec(pty->master_fd);
  348. pty->name[FILENAME_MAX-1] = '\0';
  349. strncpy(pty->name, ptsname(pty->master_fd), FILENAME_MAX-1);
  350. #endif
  351. #ifndef SET_NONBLOCK_VIA_OPENPT
  352. nonblock(pty->master_fd);
  353. #endif
  354. }
  355. static Pty *new_pty_struct(void)
  356. {
  357. Pty *pty = snew(Pty);
  358. memset(pty, 0, sizeof(Pty));
  359. pty->conf = NULL;
  360. pty->pending_eof = false;
  361. bufchain_init(&pty->output_data);
  362. return pty;
  363. }
  364. /*
  365. * Pre-initialisation. This is here to get around the fact that GTK
  366. * doesn't like being run in setuid/setgid programs (probably
  367. * sensibly). So before we initialise GTK - and therefore before we
  368. * even process the command line - we check to see if we're running
  369. * set[ug]id. If so, we open our pty master _now_, chown it as
  370. * necessary, and drop privileges. We can always close it again
  371. * later. If we're potentially going to be doing utmp as well, we
  372. * also fork off a utmp helper process and communicate with it by
  373. * means of a pipe; the utmp helper will keep privileges in order
  374. * to clean up utmp when we exit (i.e. when its end of our pipe
  375. * closes).
  376. */
  377. void pty_pre_init(void)
  378. {
  379. #ifndef NO_PTY_PRE_INIT
  380. Pty *pty;
  381. #ifndef OMIT_UTMP
  382. pid_t pid;
  383. int pipefd[2];
  384. #endif
  385. pty = single_pty = new_pty_struct();
  386. /* set the child signal handler straight away; it needs to be set
  387. * before we ever fork. */
  388. pty_setup_sigchld_handler();
  389. pty->master_fd = pty->slave_fd = -1;
  390. #ifndef OMIT_UTMP
  391. pty_stamped_utmp = false;
  392. #endif
  393. if (geteuid() != getuid() || getegid() != getgid()) {
  394. pty_open_master(pty);
  395. #ifndef OMIT_UTMP
  396. /*
  397. * Fork off the utmp helper.
  398. */
  399. if (pipe(pipefd) < 0) {
  400. perror("pterm: pipe");
  401. exit(1);
  402. }
  403. cloexec(pipefd[0]);
  404. cloexec(pipefd[1]);
  405. pid = fork();
  406. if (pid < 0) {
  407. perror("pterm: fork");
  408. exit(1);
  409. } else if (pid == 0) {
  410. char display[128], buffer[128];
  411. int dlen, ret;
  412. close(pipefd[1]);
  413. /*
  414. * Now sit here until we receive a display name from the
  415. * other end of the pipe, and then stamp utmp. Unstamp utmp
  416. * again, and exit, when the pipe closes.
  417. */
  418. dlen = 0;
  419. while (1) {
  420. ret = read(pipefd[0], buffer, lenof(buffer));
  421. if (ret <= 0) {
  422. cleanup_utmp();
  423. _exit(0);
  424. } else if (!pty_stamped_utmp) {
  425. if (dlen < lenof(display))
  426. memcpy(display+dlen, buffer,
  427. min(ret, lenof(display)-dlen));
  428. if (buffer[ret-1] == '\0') {
  429. /*
  430. * Now we have a display name. NUL-terminate
  431. * it, and stamp utmp.
  432. */
  433. display[lenof(display)-1] = '\0';
  434. /*
  435. * Trap as many fatal signals as we can in the
  436. * hope of having the best possible chance to
  437. * clean up utmp before termination. We are
  438. * unfortunately unprotected against SIGKILL,
  439. * but that's life.
  440. */
  441. putty_signal(SIGHUP, fatal_sig_handler);
  442. putty_signal(SIGINT, fatal_sig_handler);
  443. putty_signal(SIGQUIT, fatal_sig_handler);
  444. putty_signal(SIGILL, fatal_sig_handler);
  445. putty_signal(SIGABRT, fatal_sig_handler);
  446. putty_signal(SIGFPE, fatal_sig_handler);
  447. putty_signal(SIGPIPE, fatal_sig_handler);
  448. putty_signal(SIGALRM, fatal_sig_handler);
  449. putty_signal(SIGTERM, fatal_sig_handler);
  450. putty_signal(SIGSEGV, fatal_sig_handler);
  451. putty_signal(SIGUSR1, fatal_sig_handler);
  452. putty_signal(SIGUSR2, fatal_sig_handler);
  453. #ifdef SIGBUS
  454. putty_signal(SIGBUS, fatal_sig_handler);
  455. #endif
  456. #ifdef SIGPOLL
  457. putty_signal(SIGPOLL, fatal_sig_handler);
  458. #endif
  459. #ifdef SIGPROF
  460. putty_signal(SIGPROF, fatal_sig_handler);
  461. #endif
  462. #ifdef SIGSYS
  463. putty_signal(SIGSYS, fatal_sig_handler);
  464. #endif
  465. #ifdef SIGTRAP
  466. putty_signal(SIGTRAP, fatal_sig_handler);
  467. #endif
  468. #ifdef SIGVTALRM
  469. putty_signal(SIGVTALRM, fatal_sig_handler);
  470. #endif
  471. #ifdef SIGXCPU
  472. putty_signal(SIGXCPU, fatal_sig_handler);
  473. #endif
  474. #ifdef SIGXFSZ
  475. putty_signal(SIGXFSZ, fatal_sig_handler);
  476. #endif
  477. #ifdef SIGIO
  478. putty_signal(SIGIO, fatal_sig_handler);
  479. #endif
  480. setup_utmp(pty->name, display);
  481. }
  482. }
  483. }
  484. } else {
  485. close(pipefd[0]);
  486. pty_utmp_helper_pid = pid;
  487. pty_utmp_helper_pipe = pipefd[1];
  488. }
  489. #endif
  490. }
  491. /* Drop privs. */
  492. {
  493. #if HAVE_SETRESUID && HAVE_SETRESGID
  494. int gid = getgid(), uid = getuid();
  495. int setresgid(gid_t, gid_t, gid_t);
  496. int setresuid(uid_t, uid_t, uid_t);
  497. if (setresgid(gid, gid, gid) < 0) {
  498. perror("setresgid");
  499. exit(1);
  500. }
  501. if (setresuid(uid, uid, uid) < 0) {
  502. perror("setresuid");
  503. exit(1);
  504. }
  505. #else
  506. if (setgid(getgid()) < 0) {
  507. perror("setgid");
  508. exit(1);
  509. }
  510. if (setuid(getuid()) < 0) {
  511. perror("setuid");
  512. exit(1);
  513. }
  514. #endif
  515. }
  516. #endif /* NO_PTY_PRE_INIT */
  517. }
  518. static void pty_try_wait(void);
  519. static void pty_uxsel_setup(Pty *pty);
  520. static void pty_real_select_result(Pty *pty, int fd, int event, int status)
  521. {
  522. char buf[4096];
  523. int ret;
  524. bool finished = false;
  525. if (event < 0) {
  526. /*
  527. * We've been called because our child process did
  528. * something. `status' tells us what.
  529. */
  530. if ((WIFEXITED(status) || WIFSIGNALED(status))) {
  531. /*
  532. * The primary child process died.
  533. */
  534. pty->child_dead = true;
  535. del234(ptys_by_pid, pty);
  536. pty->exit_code = status;
  537. /*
  538. * If this is an ordinary pty session, this is also the
  539. * moment to terminate the whole backend.
  540. *
  541. * We _could_ instead keep the terminal open for remaining
  542. * subprocesses to output to, but conventional wisdom
  543. * seems to feel that that's the Wrong Thing for an
  544. * xterm-alike, so we bail out now (though we don't
  545. * necessarily _close_ the window, depending on the state
  546. * of Close On Exit). This would be easy enough to change
  547. * or make configurable if necessary.
  548. */
  549. if (pty->master_fd >= 0)
  550. finished = true;
  551. }
  552. } else {
  553. if (event == SELECT_R) {
  554. bool is_stdout = (fd == pty->master_o);
  555. ret = read(fd, buf, sizeof(buf));
  556. /*
  557. * Treat EIO on a pty master as equivalent to EOF (because
  558. * that's how the kernel seems to report the event where
  559. * the last process connected to the other end of the pty
  560. * went away).
  561. */
  562. if (fd == pty->master_fd && ret < 0 && errno == EIO)
  563. ret = 0;
  564. if (ret == 0) {
  565. /*
  566. * EOF on this input fd, so to begin with, we may as
  567. * well close it, and remove all references to it in
  568. * the pty's fd fields.
  569. */
  570. uxsel_del(fd);
  571. close(fd);
  572. if (pty->master_fd == fd)
  573. pty->master_fd = -1;
  574. if (pty->master_o == fd)
  575. pty->master_o = -1;
  576. if (pty->master_e == fd)
  577. pty->master_e = -1;
  578. if (is_stdout) {
  579. /*
  580. * We assume a clean exit if the pty (or stdout
  581. * pipe) has closed, but the actual child process
  582. * hasn't. The only way I can imagine this
  583. * happening is if it detaches itself from the pty
  584. * and goes daemonic - in which case the expected
  585. * usage model would precisely _not_ be for the
  586. * pterm window to hang around!
  587. */
  588. finished = true;
  589. pty_try_wait(); /* one last effort to collect exit code */
  590. if (!pty->child_dead)
  591. pty->exit_code = 0;
  592. }
  593. } else if (ret < 0) {
  594. perror("read pty master");
  595. exit(1);
  596. } else if (ret > 0) {
  597. pty->output_backlog = seat_output(
  598. pty->seat, !is_stdout, buf, ret);
  599. pty_uxsel_setup(pty);
  600. }
  601. } else if (event == SELECT_W) {
  602. /*
  603. * Attempt to send data down the pty.
  604. */
  605. pty_try_write(pty);
  606. }
  607. }
  608. if (finished && !pty->finished) {
  609. int close_on_exit;
  610. int i;
  611. for (i = 0; i < 3; i++)
  612. if (pty->fds[i].fd >= 0)
  613. uxsel_del(pty->fds[i].fd);
  614. pty_close(pty);
  615. pty->finished = true;
  616. /*
  617. * This is a slight layering-violation sort of hack: only
  618. * if we're not closing on exit (COE is set to Never, or to
  619. * Only On Clean and it wasn't a clean exit) do we output a
  620. * `terminated' message.
  621. */
  622. close_on_exit = conf_get_int(pty->conf, CONF_close_on_exit);
  623. if (close_on_exit == FORCE_OFF ||
  624. (close_on_exit == AUTO && pty->exit_code != 0)) {
  625. char *message;
  626. if (WIFEXITED(pty->exit_code)) {
  627. message = dupprintf(
  628. "\r\n[pterm: process terminated with exit code %d]\r\n",
  629. WEXITSTATUS(pty->exit_code));
  630. } else if (WIFSIGNALED(pty->exit_code)) {
  631. #if !HAVE_STRSIGNAL
  632. message = dupprintf(
  633. "\r\n[pterm: process terminated on signal %d]\r\n",
  634. WTERMSIG(pty->exit_code));
  635. #else
  636. message = dupprintf(
  637. "\r\n[pterm: process terminated on signal %d (%s)]\r\n",
  638. WTERMSIG(pty->exit_code),
  639. strsignal(WTERMSIG(pty->exit_code)));
  640. #endif
  641. } else {
  642. /* _Shouldn't_ happen, but if it does, a vague message
  643. * is better than no message at all */
  644. message = dupprintf("\r\n[pterm: process terminated]\r\n");
  645. }
  646. seat_stdout_pl(pty->seat, ptrlen_from_asciz(message));
  647. sfree(message);
  648. }
  649. seat_eof(pty->seat);
  650. seat_notify_remote_exit(pty->seat);
  651. }
  652. }
  653. static void pty_try_wait(void)
  654. {
  655. Pty *pty;
  656. pid_t pid;
  657. int status;
  658. do {
  659. pid = waitpid(-1, &status, WNOHANG);
  660. pty = find234(ptys_by_pid, &pid, pty_find_by_pid);
  661. if (pty)
  662. pty_real_select_result(pty, -1, -1, status);
  663. } while (pid > 0);
  664. }
  665. void pty_select_result(int fd, int event)
  666. {
  667. if (fd == pty_signal_pipe[0]) {
  668. char c[1];
  669. if (read(pty_signal_pipe[0], c, 1) <= 0)
  670. /* ignore error */;
  671. /* ignore its value; it'll be `x' */
  672. pty_try_wait();
  673. } else {
  674. PtyFd *ptyfd = find234(ptyfds, &fd, ptyfd_find);
  675. if (ptyfd)
  676. pty_real_select_result(ptyfd->pty, fd, event, 0);
  677. }
  678. }
  679. static void pty_uxsel_setup_fd(Pty *pty, int fd)
  680. {
  681. int rwx = 0;
  682. if (fd < 0)
  683. return;
  684. /* read from standard output and standard error pipes, assuming
  685. * we're not too backlogged */
  686. if ((pty->master_o == fd || pty->master_e == fd) &&
  687. pty->output_backlog < PTY_MAX_BACKLOG)
  688. rwx |= SELECT_R;
  689. /* write to standard input pipe if we have any data */
  690. if (pty->master_i == fd && bufchain_size(&pty->output_data))
  691. rwx |= SELECT_W;
  692. uxsel_set(fd, rwx, pty_select_result);
  693. }
  694. static void pty_uxsel_setup(Pty *pty)
  695. {
  696. /*
  697. * We potentially have three separate fds here, but on the other
  698. * hand, some of them might be the same (if they're a pty master).
  699. * So we can't just call uxsel_set(master_o, SELECT_R) and then
  700. * uxsel_set(master_i, SELECT_W), without the latter potentially
  701. * undoing the work of the former if master_o == master_i.
  702. *
  703. * Instead, here we call a single uxsel on each one of these fds
  704. * (if it exists at all), and for each one, check it against all
  705. * three to see which bits to set.
  706. */
  707. pty_uxsel_setup_fd(pty, pty->master_o);
  708. pty_uxsel_setup_fd(pty, pty->master_e);
  709. pty_uxsel_setup_fd(pty, pty->master_i);
  710. /*
  711. * In principle this only needs calling once for all pty
  712. * backend instances, but it's simplest just to call it every
  713. * time; uxsel won't mind.
  714. */
  715. uxsel_set(pty_signal_pipe[0], SELECT_R, pty_select_result);
  716. }
  717. static void copy_ttymodes_into_termios(
  718. struct termios *attrs, struct ssh_ttymodes modes)
  719. {
  720. #define TTYMODE_CHAR(name, ssh_opcode, cc_index) { \
  721. if (modes.have_mode[ssh_opcode]) { \
  722. unsigned value = modes.mode_val[ssh_opcode]; \
  723. /* normalise wire value of 255 to local _POSIX_VDISABLE */ \
  724. attrs->c_cc[cc_index] = (value == 255 ? \
  725. _POSIX_VDISABLE : value); \
  726. } \
  727. }
  728. #define TTYMODE_FLAG(flagval, ssh_opcode, field, flagmask) { \
  729. if (modes.have_mode[ssh_opcode]) { \
  730. attrs->c_##field##flag &= ~flagmask; \
  731. if (modes.mode_val[ssh_opcode]) \
  732. attrs->c_##field##flag |= flagval; \
  733. } \
  734. }
  735. #define TTYMODES_LOCAL_ONLY /* omit any that this platform doesn't know */
  736. #include "ssh/ttymode-list.h"
  737. #undef TTYMODES_LOCAL_ONLY
  738. #undef TTYMODE_CHAR
  739. #undef TTYMODE_FLAG
  740. if (modes.have_mode[TTYMODE_ISPEED])
  741. cfsetispeed(attrs, modes.mode_val[TTYMODE_ISPEED]);
  742. if (modes.have_mode[TTYMODE_OSPEED])
  743. cfsetospeed(attrs, modes.mode_val[TTYMODE_OSPEED]);
  744. }
  745. /*
  746. * The main setup function for the pty back end. This doesn't match
  747. * the signature of backend_init(), partly because it has to be able
  748. * to take extra arguments such as an argv array, and also because
  749. * once we're changing the type signature _anyway_ we can discard the
  750. * stuff that's not really applicable to this backend like host names
  751. * and port numbers.
  752. */
  753. Backend *pty_backend_create(
  754. Seat *seat, LogContext *logctx, Conf *conf, char **argv, const char *cmd,
  755. struct ssh_ttymodes ttymodes, bool pipes_instead, const char *dir,
  756. const char *const *env_vars_to_unset)
  757. {
  758. int slavefd;
  759. pid_t pid, pgrp;
  760. #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
  761. bool got_windowid;
  762. long windowid;
  763. #endif
  764. Pty *pty;
  765. int i;
  766. /* No local authentication phase in this protocol */
  767. seat_set_trust_status(seat, false);
  768. if (single_pty) {
  769. pty = single_pty;
  770. assert(pty->conf == NULL);
  771. } else {
  772. pty = new_pty_struct();
  773. pty->master_fd = pty->slave_fd = -1;
  774. #ifndef OMIT_UTMP
  775. pty_stamped_utmp = false;
  776. #endif
  777. }
  778. for (i = 0; i < 6; i++)
  779. pty->pipefds[i] = -1;
  780. for (i = 0; i < 3; i++) {
  781. pty->fds[i].fd = -1;
  782. pty->fds[i].pty = pty;
  783. }
  784. if (pty_signal_pipe[0] < 0) {
  785. if (pipe(pty_signal_pipe) < 0) {
  786. perror("pipe");
  787. exit(1);
  788. }
  789. cloexec(pty_signal_pipe[0]);
  790. cloexec(pty_signal_pipe[1]);
  791. }
  792. pty->seat = seat;
  793. pty->backend.vt = &pty_backend;
  794. pty->conf = conf_copy(conf);
  795. pty->term_width = conf_get_int(conf, CONF_width);
  796. pty->term_height = conf_get_int(conf, CONF_height);
  797. if (!ptyfds)
  798. ptyfds = newtree234(ptyfd_compare);
  799. if (pipes_instead) {
  800. if (pty->master_fd >= 0) {
  801. /* If somehow we've got a pty master already and don't
  802. * need it, throw it away! */
  803. close(pty->master_fd);
  804. #ifndef OMIT_UTMP
  805. if (pty_utmp_helper_pipe >= 0) {
  806. close(pty_utmp_helper_pipe); /* don't need this either */
  807. pty_utmp_helper_pipe = -1;
  808. }
  809. #endif
  810. }
  811. for (i = 0; i < 6; i += 2) {
  812. if (pipe(pty->pipefds + i) < 0) {
  813. backend_free(&pty->backend);
  814. return NULL;
  815. }
  816. }
  817. pty->fds[0].fd = pty->master_i = pty->pipefds[1];
  818. pty->fds[1].fd = pty->master_o = pty->pipefds[2];
  819. pty->fds[2].fd = pty->master_e = pty->pipefds[4];
  820. add234(ptyfds, &pty->fds[0]);
  821. add234(ptyfds, &pty->fds[1]);
  822. add234(ptyfds, &pty->fds[2]);
  823. } else {
  824. if (pty->master_fd < 0)
  825. pty_open_master(pty);
  826. #ifndef OMIT_UTMP
  827. /*
  828. * Stamp utmp (that is, tell the utmp helper process to do so),
  829. * or not.
  830. */
  831. if (pty_utmp_helper_pipe >= 0) { /* if it's < 0, we can't anyway */
  832. if (!conf_get_bool(conf, CONF_stamp_utmp)) {
  833. /* We're not stamping utmp, so just let the child
  834. * process die that was waiting to unstamp it later. */
  835. close(pty_utmp_helper_pipe);
  836. pty_utmp_helper_pipe = -1;
  837. } else {
  838. const char *location = seat_get_x_display(pty->seat);
  839. int len = strlen(location)+1, pos = 0; /* +1 to include NUL */
  840. while (pos < len) {
  841. int ret = write(pty_utmp_helper_pipe,
  842. location + pos, len - pos);
  843. if (ret < 0) {
  844. perror("pterm: writing to utmp helper process");
  845. close(pty_utmp_helper_pipe); /* arrgh, just give up */
  846. pty_utmp_helper_pipe = -1;
  847. break;
  848. }
  849. pos += ret;
  850. }
  851. }
  852. }
  853. #endif
  854. pty->master_i = pty->master_fd;
  855. pty->master_o = pty->master_fd;
  856. pty->master_e = -1;
  857. pty->fds[0].fd = pty->master_fd;
  858. add234(ptyfds, &pty->fds[0]);
  859. }
  860. #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
  861. got_windowid = seat_get_windowid(pty->seat, &windowid);
  862. #endif
  863. /*
  864. * Set up the signal handler to catch SIGCHLD, if pty_pre_init
  865. * didn't already do it.
  866. */
  867. pty_setup_sigchld_handler();
  868. /*
  869. * Fork and execute the command.
  870. */
  871. pid = fork();
  872. if (pid < 0) {
  873. perror("fork");
  874. exit(1);
  875. }
  876. if (pid == 0) {
  877. struct termios attrs;
  878. /*
  879. * We are the child.
  880. */
  881. if (pty_osx_envrestore_prefix) {
  882. int plen = strlen(pty_osx_envrestore_prefix);
  883. extern char **environ;
  884. char **ep;
  885. restart_osx_env_restore:
  886. for (ep = environ; *ep; ep++) {
  887. char *e = *ep;
  888. if (!strncmp(e, pty_osx_envrestore_prefix, plen)) {
  889. bool unset = (e[plen] == 'u');
  890. char *pname = dupprintf("%.*s", (int)strcspn(e, "="), e);
  891. char *name = pname + plen + 1;
  892. char *value = e + strcspn(e, "=");
  893. if (*value) value++;
  894. value = dupstr(value);
  895. if (unset)
  896. unsetenv(name);
  897. else
  898. setenv(name, value, 1);
  899. unsetenv(pname);
  900. sfree(pname);
  901. sfree(value);
  902. goto restart_osx_env_restore;
  903. }
  904. }
  905. }
  906. pgrp = getpid();
  907. if (pipes_instead) {
  908. int i;
  909. dup2(pty->pipefds[0], 0);
  910. dup2(pty->pipefds[3], 1);
  911. dup2(pty->pipefds[5], 2);
  912. for (i = 0; i < 6; i++)
  913. close(pty->pipefds[i]);
  914. setsid();
  915. } else {
  916. slavefd = pty_open_slave(pty);
  917. if (slavefd < 0) {
  918. perror("slave pty: open");
  919. _exit(1);
  920. }
  921. close(pty->master_fd);
  922. noncloexec(slavefd);
  923. dup2(slavefd, 0);
  924. dup2(slavefd, 1);
  925. dup2(slavefd, 2);
  926. close(slavefd);
  927. setsid();
  928. #ifdef TIOCSCTTY
  929. ioctl(0, TIOCSCTTY, 1);
  930. #endif
  931. tcsetpgrp(0, pgrp);
  932. /*
  933. * Set up configuration-dependent termios settings on the new
  934. * pty. Linux would have let us do this on the pty master
  935. * before we forked, but that fails on OS X, so we do it here
  936. * instead.
  937. */
  938. if (tcgetattr(0, &attrs) == 0) {
  939. /*
  940. * Set the backspace character to be whichever of ^H and
  941. * ^? is specified by bksp_is_delete.
  942. */
  943. attrs.c_cc[VERASE] = conf_get_bool(conf, CONF_bksp_is_delete)
  944. ? '\177' : '\010';
  945. /*
  946. * Set the IUTF8 bit iff the character set is UTF-8.
  947. */
  948. #ifdef IUTF8
  949. if (seat_is_utf8(seat))
  950. attrs.c_iflag |= IUTF8;
  951. else
  952. attrs.c_iflag &= ~IUTF8;
  953. #endif
  954. copy_ttymodes_into_termios(&attrs, ttymodes);
  955. tcsetattr(0, TCSANOW, &attrs);
  956. }
  957. }
  958. setpgid(pgrp, pgrp);
  959. if (!pipes_instead) {
  960. int ptyfd = open(pty->name, O_WRONLY, 0);
  961. if (ptyfd >= 0)
  962. close(ptyfd);
  963. }
  964. setpgid(pgrp, pgrp);
  965. if (env_vars_to_unset)
  966. for (const char *const *p = env_vars_to_unset; *p; p++)
  967. unsetenv(*p);
  968. if (!pipes_instead) {
  969. char *term_env_var = dupprintf("TERM=%s",
  970. conf_get_str(conf, CONF_termtype));
  971. putenv(term_env_var);
  972. /* We mustn't free term_env_var, as putenv links it into the
  973. * environment in place.
  974. */
  975. }
  976. #ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */
  977. if (got_windowid) {
  978. char *windowid_env_var = dupprintf("WINDOWID=%ld", windowid);
  979. putenv(windowid_env_var);
  980. /* We mustn't free windowid_env_var, as putenv links it into the
  981. * environment in place.
  982. */
  983. }
  984. {
  985. /*
  986. * In case we were invoked with a --display argument that
  987. * doesn't match DISPLAY in our actual environment, we
  988. * should set DISPLAY for processes running inside the
  989. * terminal to match the display the terminal itself is
  990. * on.
  991. */
  992. const char *x_display = seat_get_x_display(pty->seat);
  993. if (x_display) {
  994. char *x_display_env_var = dupprintf("DISPLAY=%s", x_display);
  995. putenv(x_display_env_var);
  996. /* As above, we don't free this. */
  997. }
  998. }
  999. #endif
  1000. {
  1001. char *key, *val;
  1002. for (val = conf_get_str_strs(conf, CONF_environmt, NULL, &key);
  1003. val != NULL;
  1004. val = conf_get_str_strs(conf, CONF_environmt, key, &key)) {
  1005. char *varval = dupcat(key, "=", val);
  1006. putenv(varval);
  1007. /*
  1008. * We must not free varval, since putenv links it
  1009. * into the environment _in place_. Weird, but
  1010. * there we go. Memory usage will be rationalised
  1011. * as soon as we exec anyway.
  1012. */
  1013. }
  1014. }
  1015. if (dir) {
  1016. if (chdir(dir) < 0) {
  1017. /* Ignore the error - nothing we can sensibly do about it,
  1018. * and our existing cwd is as good a fallback as any. */
  1019. }
  1020. }
  1021. /*
  1022. * SIGINT, SIGQUIT and SIGPIPE may have been set to ignored by
  1023. * our parent, particularly by things like sh -c 'pterm &' and
  1024. * some window or session managers. SIGPIPE was also
  1025. * (potentially) blocked by us during startup. Reverse all
  1026. * this for our child process.
  1027. */
  1028. putty_signal(SIGINT, SIG_DFL);
  1029. putty_signal(SIGQUIT, SIG_DFL);
  1030. putty_signal(SIGPIPE, SIG_DFL);
  1031. block_signal(SIGPIPE, false);
  1032. if (argv || cmd) {
  1033. /*
  1034. * If we were given a separated argument list, try to exec
  1035. * it.
  1036. */
  1037. if (argv) {
  1038. execvp(argv[0], argv);
  1039. }
  1040. /*
  1041. * Otherwise, if we were given a single command string,
  1042. * try passing that to $SHELL -c.
  1043. *
  1044. * In the case of pterm, this system of fallbacks arranges
  1045. * that we can _either_ follow 'pterm -e' with a list of
  1046. * argv elements to be fed directly to exec, _or_ with a
  1047. * single argument containing a command to be parsed by a
  1048. * shell (but, in cases of doubt, the former is more
  1049. * reliable). We arrange this by setting argv to the full
  1050. * argument list, and also setting cmd to the single
  1051. * element of argv if it's a length-1 list.
  1052. *
  1053. * A quick survey of other terminal emulators' -e options
  1054. * (as of Debian squeeze) suggests that:
  1055. *
  1056. * - xterm supports both modes, more or less like this
  1057. * - gnome-terminal will only accept a one-string shell command
  1058. * - Eterm, kterm and rxvt will only accept a list of
  1059. * argv elements (as did older versions of pterm).
  1060. *
  1061. * It therefore seems important to support both usage
  1062. * modes in order to be a drop-in replacement for either
  1063. * xterm or gnome-terminal, and hence for anyone's
  1064. * plausible uses of the Debian-style alias
  1065. * 'x-terminal-emulator'.
  1066. *
  1067. * In other use cases, a caller can set only one of argv
  1068. * and cmd to get a fixed handling of the input.
  1069. */
  1070. if (cmd) {
  1071. char *shell = getenv("SHELL");
  1072. if (shell)
  1073. execl(shell, shell, "-c", cmd, (void *)NULL);
  1074. }
  1075. } else {
  1076. const char *shell = getenv("SHELL");
  1077. if (!shell)
  1078. shell = "/bin/sh";
  1079. char *shellname;
  1080. if (conf_get_bool(conf, CONF_login_shell)) {
  1081. const char *p = strrchr(shell, '/');
  1082. p = p ? p+1 : shell;
  1083. shellname = dupprintf("-%s", p);
  1084. } else
  1085. shellname = (char *)shell;
  1086. execl(shell, shellname, (void *)NULL);
  1087. }
  1088. /*
  1089. * If we're here, exec has gone badly foom.
  1090. */
  1091. perror("exec");
  1092. _exit(127);
  1093. } else {
  1094. pty->child_pid = pid;
  1095. pty->child_dead = false;
  1096. pty->finished = false;
  1097. if (pty->slave_fd > 0)
  1098. close(pty->slave_fd);
  1099. if (!ptys_by_pid)
  1100. ptys_by_pid = newtree234(pty_compare_by_pid);
  1101. if (pty->pipefds[0] >= 0) {
  1102. close(pty->pipefds[0]);
  1103. pty->pipefds[0] = -1;
  1104. }
  1105. if (pty->pipefds[3] >= 0) {
  1106. close(pty->pipefds[3]);
  1107. pty->pipefds[3] = -1;
  1108. }
  1109. if (pty->pipefds[5] >= 0) {
  1110. close(pty->pipefds[5]);
  1111. pty->pipefds[5] = -1;
  1112. }
  1113. add234(ptys_by_pid, pty);
  1114. }
  1115. pty_uxsel_setup(pty);
  1116. return &pty->backend;
  1117. }
  1118. /*
  1119. * This is the pty backend's _official_ init method, for BackendVtable
  1120. * purposes. Its job is just to be an API converter, ignoring the
  1121. * irrelevant input parameters and making up auxiliary outputs. Also
  1122. * it gets the argv array from the global variable pty_argv, expecting
  1123. * that it will have been invoked by pterm.
  1124. */
  1125. static char *pty_init(const BackendVtable *vt, Seat *seat,
  1126. Backend **backend_handle, LogContext *logctx,
  1127. Conf *conf, const char *host, int port,
  1128. char **realhost, bool nodelay, bool keepalive)
  1129. {
  1130. const char *cmd = NULL;
  1131. struct ssh_ttymodes modes;
  1132. memset(&modes, 0, sizeof(modes));
  1133. if (pty_argv && pty_argv[0] && !pty_argv[1])
  1134. cmd = pty_argv[0];
  1135. assert(vt == &pty_backend);
  1136. *backend_handle = pty_backend_create(
  1137. seat, logctx, conf, pty_argv, cmd, modes, false, NULL, NULL);
  1138. *realhost = dupstr("");
  1139. return NULL;
  1140. }
  1141. static void pty_reconfig(Backend *be, Conf *conf)
  1142. {
  1143. Pty *pty = container_of(be, Pty, backend);
  1144. /*
  1145. * We don't have much need to reconfigure this backend, but
  1146. * unfortunately we do need to pick up the setting of Close On
  1147. * Exit so we know whether to give a `terminated' message.
  1148. */
  1149. conf_copy_into(pty->conf, conf);
  1150. }
  1151. /*
  1152. * Stub routine (never called in pterm).
  1153. */
  1154. static void pty_free(Backend *be)
  1155. {
  1156. Pty *pty = container_of(be, Pty, backend);
  1157. int i;
  1158. pty_close(pty);
  1159. /* Either of these may fail `not found'. That's fine with us. */
  1160. del234(ptys_by_pid, pty);
  1161. for (i = 0; i < 3; i++)
  1162. if (pty->fds[i].fd >= 0)
  1163. del234(ptyfds, &pty->fds[i]);
  1164. bufchain_clear(&pty->output_data);
  1165. conf_free(pty->conf);
  1166. pty->conf = NULL;
  1167. if (pty == single_pty) {
  1168. /*
  1169. * Leave this structure around in case we need to Restart
  1170. * Session.
  1171. */
  1172. } else {
  1173. sfree(pty);
  1174. }
  1175. }
  1176. static void pty_try_write(Pty *pty)
  1177. {
  1178. ssize_t ret;
  1179. assert(pty->master_i >= 0);
  1180. while (bufchain_size(&pty->output_data) > 0) {
  1181. ptrlen data = bufchain_prefix(&pty->output_data);
  1182. ret = write(pty->master_i, data.ptr, data.len);
  1183. if (ret < 0 && (errno == EWOULDBLOCK)) {
  1184. /*
  1185. * We've sent all we can for the moment.
  1186. */
  1187. break;
  1188. }
  1189. if (ret < 0) {
  1190. perror("write pty master");
  1191. exit(1);
  1192. }
  1193. bufchain_consume(&pty->output_data, ret);
  1194. }
  1195. if (pty->pending_eof && bufchain_size(&pty->output_data) == 0) {
  1196. /* This should only happen if pty->master_i is a pipe that
  1197. * doesn't alias either output fd */
  1198. assert(pty->master_i != pty->master_o);
  1199. assert(pty->master_i != pty->master_e);
  1200. uxsel_del(pty->master_i);
  1201. close(pty->master_i);
  1202. pty->master_i = -1;
  1203. pty->pending_eof = false;
  1204. }
  1205. pty_uxsel_setup(pty);
  1206. }
  1207. /*
  1208. * Called to send data down the pty.
  1209. */
  1210. static void pty_send(Backend *be, const char *buf, size_t len)
  1211. {
  1212. Pty *pty = container_of(be, Pty, backend);
  1213. if (pty->master_i < 0 || pty->pending_eof)
  1214. return; /* ignore all writes if fd closed */
  1215. bufchain_add(&pty->output_data, buf, len);
  1216. pty_try_write(pty);
  1217. }
  1218. static void pty_close(Pty *pty)
  1219. {
  1220. int i;
  1221. if (pty->master_o >= 0)
  1222. uxsel_del(pty->master_o);
  1223. if (pty->master_e >= 0)
  1224. uxsel_del(pty->master_e);
  1225. if (pty->master_i >= 0)
  1226. uxsel_del(pty->master_i);
  1227. if (pty->master_fd >= 0) {
  1228. close(pty->master_fd);
  1229. pty->master_fd = -1;
  1230. }
  1231. for (i = 0; i < 6; i++) {
  1232. if (pty->pipefds[i] >= 0)
  1233. close(pty->pipefds[i]);
  1234. pty->pipefds[i] = -1;
  1235. }
  1236. pty->master_i = pty->master_o = pty->master_e = -1;
  1237. #ifndef OMIT_UTMP
  1238. if (pty_utmp_helper_pipe >= 0) {
  1239. close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */
  1240. pty_utmp_helper_pipe = -1;
  1241. }
  1242. #endif
  1243. }
  1244. /*
  1245. * Called to query the current socket sendability status.
  1246. */
  1247. static size_t pty_sendbuffer(Backend *be)
  1248. {
  1249. Pty *pty = container_of(be, Pty, backend);
  1250. return bufchain_size(&pty->output_data);
  1251. }
  1252. /*
  1253. * Called to set the size of the window
  1254. */
  1255. static void pty_size(Backend *be, int width, int height)
  1256. {
  1257. Pty *pty = container_of(be, Pty, backend);
  1258. struct winsize size;
  1259. int xpixel = 0, ypixel = 0;
  1260. pty->term_width = width;
  1261. pty->term_height = height;
  1262. if (pty->master_fd < 0)
  1263. return;
  1264. seat_get_window_pixel_size(pty->seat, &xpixel, &ypixel);
  1265. size.ws_row = (unsigned short)pty->term_height;
  1266. size.ws_col = (unsigned short)pty->term_width;
  1267. size.ws_xpixel = (unsigned short)xpixel;
  1268. size.ws_ypixel = (unsigned short)ypixel;
  1269. ioctl(pty->master_fd, TIOCSWINSZ, (void *)&size);
  1270. return;
  1271. }
  1272. /*
  1273. * Send special codes.
  1274. */
  1275. static void pty_special(Backend *be, SessionSpecialCode code, int arg)
  1276. {
  1277. Pty *pty = container_of(be, Pty, backend);
  1278. if (code == SS_BRK) {
  1279. if (pty->master_fd >= 0)
  1280. tcsendbreak(pty->master_fd, 0);
  1281. return;
  1282. }
  1283. if (code == SS_EOF) {
  1284. if (pty->master_i >= 0 && pty->master_i != pty->master_fd) {
  1285. pty->pending_eof = true;
  1286. pty_try_write(pty);
  1287. }
  1288. return;
  1289. }
  1290. {
  1291. int sig = -1;
  1292. #define SIGNAL_SUB(name) if (code == SS_SIG ## name) sig = SIG ## name;
  1293. #define SIGNAL_MAIN(name, text) SIGNAL_SUB(name)
  1294. #define SIGNALS_LOCAL_ONLY
  1295. #include "ssh/signal-list.h"
  1296. #undef SIGNAL_SUB
  1297. #undef SIGNAL_MAIN
  1298. #undef SIGNALS_LOCAL_ONLY
  1299. if (sig != -1) {
  1300. if (!pty->child_dead)
  1301. kill(pty->child_pid, sig);
  1302. return;
  1303. }
  1304. }
  1305. return;
  1306. }
  1307. /*
  1308. * Return a list of the special codes that make sense in this
  1309. * protocol.
  1310. */
  1311. static const SessionSpecial *pty_get_specials(Backend *be)
  1312. {
  1313. /* Pty *pty = container_of(be, Pty, backend); */
  1314. /*
  1315. * Hmm. When I get round to having this actually usable, it
  1316. * might be quite nice to have the ability to deliver a few
  1317. * well chosen signals to the child process - SIGINT, SIGTERM,
  1318. * SIGKILL at least.
  1319. */
  1320. return NULL;
  1321. }
  1322. static bool pty_connected(Backend *be)
  1323. {
  1324. /* Pty *pty = container_of(be, Pty, backend); */
  1325. return true;
  1326. }
  1327. static bool pty_sendok(Backend *be)
  1328. {
  1329. /* Pty *pty = container_of(be, Pty, backend); */
  1330. return true;
  1331. }
  1332. static void pty_unthrottle(Backend *be, size_t backlog)
  1333. {
  1334. Pty *pty = container_of(be, Pty, backend);
  1335. pty->output_backlog = backlog;
  1336. pty_uxsel_setup(pty);
  1337. }
  1338. static bool pty_ldisc(Backend *be, int option)
  1339. {
  1340. /* Pty *pty = container_of(be, Pty, backend); */
  1341. return false; /* neither editing nor echoing */
  1342. }
  1343. static void pty_provide_ldisc(Backend *be, Ldisc *ldisc)
  1344. {
  1345. /* Pty *pty = container_of(be, Pty, backend); */
  1346. /* This is a stub. */
  1347. }
  1348. static int pty_exitcode(Backend *be)
  1349. {
  1350. Pty *pty = container_of(be, Pty, backend);
  1351. if (!pty->finished)
  1352. return -1; /* not dead yet */
  1353. else if (WIFSIGNALED(pty->exit_code))
  1354. return 128 + WTERMSIG(pty->exit_code);
  1355. else
  1356. return WEXITSTATUS(pty->exit_code);
  1357. }
  1358. int pty_backend_exit_signum(Backend *be)
  1359. {
  1360. Pty *pty = container_of(be, Pty, backend);
  1361. if (!pty->finished || !WIFSIGNALED(pty->exit_code))
  1362. return -1;
  1363. return WTERMSIG(pty->exit_code);
  1364. }
  1365. ptrlen pty_backend_exit_signame(Backend *be, char **aux_msg)
  1366. {
  1367. *aux_msg = NULL;
  1368. int sig = pty_backend_exit_signum(be);
  1369. if (sig < 0)
  1370. return PTRLEN_LITERAL("");
  1371. #define SIGNAL_SUB(s) { \
  1372. if (sig == SIG ## s) \
  1373. return PTRLEN_LITERAL(#s); \
  1374. }
  1375. #define SIGNAL_MAIN(s, desc) SIGNAL_SUB(s)
  1376. #define SIGNALS_LOCAL_ONLY
  1377. #include "ssh/signal-list.h"
  1378. #undef SIGNAL_MAIN
  1379. #undef SIGNAL_SUB
  1380. #undef SIGNALS_LOCAL_ONLY
  1381. *aux_msg = dupprintf("untranslatable signal number %d: %s",
  1382. sig, strsignal(sig));
  1383. return PTRLEN_LITERAL("HUP"); /* need some kind of default */
  1384. }
  1385. static int pty_cfg_info(Backend *be)
  1386. {
  1387. /* Pty *pty = container_of(be, Pty, backend); */
  1388. return 0;
  1389. }
  1390. const BackendVtable pty_backend = {
  1391. .init = pty_init,
  1392. .free = pty_free,
  1393. .reconfig = pty_reconfig,
  1394. .send = pty_send,
  1395. .sendbuffer = pty_sendbuffer,
  1396. .size = pty_size,
  1397. .special = pty_special,
  1398. .get_specials = pty_get_specials,
  1399. .connected = pty_connected,
  1400. .exitcode = pty_exitcode,
  1401. .sendok = pty_sendok,
  1402. .ldisc_option_state = pty_ldisc,
  1403. .provide_ldisc = pty_provide_ldisc,
  1404. .unthrottle = pty_unthrottle,
  1405. .cfg_info = pty_cfg_info,
  1406. .id = "pty",
  1407. .displayname_tc = "pty",
  1408. .displayname_lc = "pty",
  1409. .protocol = -1,
  1410. };