main.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226
  1. /*
  2. * main.c - Point-to-Point Protocol main module
  3. *
  4. * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in
  15. * the documentation and/or other materials provided with the
  16. * distribution.
  17. *
  18. * 3. The name "Carnegie Mellon University" must not be used to
  19. * endorse or promote products derived from this software without
  20. * prior written permission. For permission or any legal
  21. * details, please contact
  22. * Office of Technology Transfer
  23. * Carnegie Mellon University
  24. * 5000 Forbes Avenue
  25. * Pittsburgh, PA 15213-3890
  26. * (412) 268-4387, fax: (412) 268-7395
  27. * tech-transfer@andrew.cmu.edu
  28. *
  29. * 4. Redistributions of any form whatsoever must retain the following
  30. * acknowledgment:
  31. * "This product includes software developed by Computing Services
  32. * at Carnegie Mellon University (http://www.cmu.edu/computing/)."
  33. *
  34. * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
  35. * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  36. * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
  37. * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  38. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
  39. * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
  40. * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  41. *
  42. * Copyright (c) 1999-2004 Paul Mackerras. All rights reserved.
  43. *
  44. * Redistribution and use in source and binary forms, with or without
  45. * modification, are permitted provided that the following conditions
  46. * are met:
  47. *
  48. * 1. Redistributions of source code must retain the above copyright
  49. * notice, this list of conditions and the following disclaimer.
  50. *
  51. * 2. The name(s) of the authors of this software must not be used to
  52. * endorse or promote products derived from this software without
  53. * prior written permission.
  54. *
  55. * 3. Redistributions of any form whatsoever must retain the following
  56. * acknowledgment:
  57. * "This product includes software developed by Paul Mackerras
  58. * <paulus@samba.org>".
  59. *
  60. * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
  61. * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  62. * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
  63. * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  64. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
  65. * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
  66. * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  67. */
  68. #define RCSID "$Id: main.c,v 1.156 2008/06/23 11:47:18 paulus Exp $"
  69. #include <stdio.h>
  70. #include <ctype.h>
  71. #include <stdlib.h>
  72. #include <string.h>
  73. #include <unistd.h>
  74. #include <signal.h>
  75. #include <errno.h>
  76. #include <fcntl.h>
  77. #include <syslog.h>
  78. #include <netdb.h>
  79. #include <utmp.h>
  80. #include <pwd.h>
  81. #include <setjmp.h>
  82. #include <sys/param.h>
  83. #include <sys/types.h>
  84. #include <sys/wait.h>
  85. #include <sys/time.h>
  86. #include <sys/resource.h>
  87. #include <sys/stat.h>
  88. #include <sys/socket.h>
  89. #include <netinet/in.h>
  90. #include <arpa/inet.h>
  91. #include "pppd.h"
  92. #include "magic.h"
  93. #include "fsm.h"
  94. #include "lcp.h"
  95. #include "ipcp.h"
  96. #ifdef INET6
  97. #include "ipv6cp.h"
  98. #endif
  99. #include "upap.h"
  100. #include "chap-new.h"
  101. #include "eap.h"
  102. #include "ccp.h"
  103. #include "ecp.h"
  104. #include "pathnames.h"
  105. #ifdef USE_TDB
  106. #include "tdb.h"
  107. #endif
  108. #ifdef CBCP_SUPPORT
  109. #include "cbcp.h"
  110. #endif
  111. #ifdef IPX_CHANGE
  112. #include "ipxcp.h"
  113. #endif /* IPX_CHANGE */
  114. #ifdef AT_CHANGE
  115. #include "atcp.h"
  116. #endif
  117. static const char rcsid[] = RCSID;
  118. /* interface vars */
  119. char ifname[32]; /* Interface name */
  120. int ifunit; /* Interface unit number */
  121. struct channel *the_channel;
  122. char *progname; /* Name of this program */
  123. char hostname[MAXNAMELEN]; /* Our hostname */
  124. static char pidfilename[MAXPATHLEN]; /* name of pid file */
  125. static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
  126. char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
  127. uid_t uid; /* Our real user-id */
  128. struct notifier *pidchange = NULL;
  129. struct notifier *phasechange = NULL;
  130. struct notifier *exitnotify = NULL;
  131. struct notifier *sigreceived = NULL;
  132. struct notifier *fork_notifier = NULL;
  133. int hungup; /* terminal has been hung up */
  134. int privileged; /* we're running as real uid root */
  135. int need_holdoff; /* need holdoff period before restarting */
  136. int detached; /* have detached from terminal */
  137. volatile int status; /* exit status for pppd */
  138. int unsuccess; /* # unsuccessful connection attempts */
  139. int do_callback; /* != 0 if we should do callback next */
  140. int doing_callback; /* != 0 if we are doing callback */
  141. int ppp_session_number; /* Session number, for channels with such a
  142. concept (eg PPPoE) */
  143. int childwait_done; /* have timed out waiting for children */
  144. #ifdef USE_TDB
  145. TDB_CONTEXT *pppdb; /* database for storing status etc. */
  146. #endif
  147. char db_key[32];
  148. int (*holdoff_hook) __P((void)) = NULL;
  149. int (*new_phase_hook) __P((int)) = NULL;
  150. void (*snoop_recv_hook) __P((unsigned char *p, int len)) = NULL;
  151. void (*snoop_send_hook) __P((unsigned char *p, int len)) = NULL;
  152. static int conn_running; /* we have a [dis]connector running */
  153. static int fd_loop; /* fd for getting demand-dial packets */
  154. int fd_devnull; /* fd for /dev/null */
  155. int devfd = -1; /* fd of underlying device */
  156. int fd_ppp = -1; /* fd for talking PPP */
  157. int phase; /* where the link is at */
  158. int kill_link;
  159. int asked_to_quit;
  160. int open_ccp_flag;
  161. int listen_time;
  162. int got_sigusr2;
  163. int got_sigterm;
  164. int got_sighup;
  165. static sigset_t signals_handled;
  166. static int waiting;
  167. static sigjmp_buf sigjmp;
  168. char **script_env; /* Env. variable values for scripts */
  169. int s_env_nalloc; /* # words avail at script_env */
  170. u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
  171. u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
  172. static int n_children; /* # child processes still running */
  173. static int got_sigchld; /* set if we have received a SIGCHLD */
  174. int privopen; /* don't lock, open device as root */
  175. char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
  176. GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
  177. int ngroups; /* How many groups valid in groups */
  178. static struct timeval start_time; /* Time when link was started. */
  179. static struct pppd_stats old_link_stats;
  180. struct pppd_stats link_stats;
  181. unsigned link_connect_time;
  182. int link_stats_valid;
  183. int error_count;
  184. bool bundle_eof;
  185. bool bundle_terminating;
  186. /*
  187. * We maintain a list of child process pids and
  188. * functions to call when they exit.
  189. */
  190. struct subprocess {
  191. pid_t pid;
  192. char *prog;
  193. void (*done) __P((void *));
  194. void *arg;
  195. int killable;
  196. struct subprocess *next;
  197. };
  198. static struct subprocess *children;
  199. /* Prototypes for procedures local to this file. */
  200. static void setup_signals __P((void));
  201. static void create_pidfile __P((int pid));
  202. static void create_linkpidfile __P((int pid));
  203. static void cleanup __P((void));
  204. static void get_input __P((void));
  205. static void calltimeout __P((void));
  206. static struct timeval *timeleft __P((struct timeval *));
  207. static void kill_my_pg __P((int));
  208. static void hup __P((int));
  209. static void term __P((int));
  210. static void chld __P((int));
  211. static void toggle_debug __P((int));
  212. static void open_ccp __P((int));
  213. static void bad_signal __P((int));
  214. static void holdoff_end __P((void *));
  215. static void forget_child __P((int pid, int status));
  216. static int reap_kids __P((void));
  217. static void childwait_end __P((void *));
  218. #ifdef USE_TDB
  219. static void update_db_entry __P((void));
  220. static void add_db_key __P((const char *));
  221. static void delete_db_key __P((const char *));
  222. static void cleanup_db __P((void));
  223. #endif
  224. static void handle_events __P((void));
  225. void print_link_stats __P((void));
  226. extern char *ttyname __P((int));
  227. extern char *getlogin __P((void));
  228. int main __P((int, char *[]));
  229. #ifdef ultrix
  230. #undef O_NONBLOCK
  231. #define O_NONBLOCK O_NDELAY
  232. #endif
  233. #ifdef ULTRIX
  234. #define setlogmask(x)
  235. #endif
  236. /*
  237. * PPP Data Link Layer "protocol" table.
  238. * One entry per supported protocol.
  239. * The last entry must be NULL.
  240. */
  241. struct protent *protocols[] = {
  242. &lcp_protent,
  243. &pap_protent,
  244. &chap_protent,
  245. #ifdef CBCP_SUPPORT
  246. &cbcp_protent,
  247. #endif
  248. &ipcp_protent,
  249. #ifdef INET6
  250. &ipv6cp_protent,
  251. #endif
  252. &ccp_protent,
  253. &ecp_protent,
  254. #ifdef IPX_CHANGE
  255. &ipxcp_protent,
  256. #endif
  257. #ifdef AT_CHANGE
  258. &atcp_protent,
  259. #endif
  260. &eap_protent,
  261. NULL
  262. };
  263. /*
  264. * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
  265. */
  266. #if !defined(PPP_DRV_NAME)
  267. #define PPP_DRV_NAME "ppp"
  268. #endif /* !defined(PPP_DRV_NAME) */
  269. int
  270. main(argc, argv)
  271. int argc;
  272. char *argv[];
  273. {
  274. int i, t;
  275. char *p;
  276. struct passwd *pw;
  277. struct protent *protp;
  278. char numbuf[16];
  279. link_stats_valid = 0;
  280. new_phase(PHASE_INITIALIZE);
  281. script_env = NULL;
  282. /* Initialize syslog facilities */
  283. reopen_log();
  284. if (gethostname(hostname, MAXNAMELEN) < 0 ) {
  285. option_error("Couldn't get hostname: %m");
  286. exit(1);
  287. }
  288. hostname[MAXNAMELEN-1] = 0;
  289. /* make sure we don't create world or group writable files. */
  290. umask(umask(0777) | 022);
  291. uid = getuid();
  292. privileged = uid == 0;
  293. slprintf(numbuf, sizeof(numbuf), "%d", uid);
  294. script_setenv("ORIG_UID", numbuf, 0);
  295. ngroups = getgroups(NGROUPS_MAX, groups);
  296. /*
  297. * Initialize magic number generator now so that protocols may
  298. * use magic numbers in initialization.
  299. */
  300. magic_init();
  301. /*
  302. * Initialize each protocol.
  303. */
  304. for (i = 0; (protp = protocols[i]) != NULL; ++i)
  305. (*protp->init)(0);
  306. /*
  307. * Initialize the default channel.
  308. */
  309. tty_init();
  310. progname = *argv;
  311. /*
  312. * Parse, in order, the system options file, the user's options file,
  313. * and the command line arguments.
  314. */
  315. if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
  316. || !options_from_user()
  317. || !parse_args(argc-1, argv+1))
  318. exit(EXIT_OPTION_ERROR);
  319. devnam_fixed = 1; /* can no longer change device name */
  320. /*
  321. * Work out the device name, if it hasn't already been specified,
  322. * and parse the tty's options file.
  323. */
  324. if (the_channel->process_extra_options)
  325. (*the_channel->process_extra_options)();
  326. if (debug)
  327. setlogmask(LOG_UPTO(LOG_DEBUG));
  328. /*
  329. * Check that we are running as root.
  330. */
  331. if (geteuid() != 0) {
  332. option_error("must be root to run %s, since it is not setuid-root",
  333. argv[0]);
  334. exit(EXIT_NOT_ROOT);
  335. }
  336. if (!ppp_available()) {
  337. option_error("%s", no_ppp_msg);
  338. exit(EXIT_NO_KERNEL_SUPPORT);
  339. }
  340. /*
  341. * Check that the options given are valid and consistent.
  342. */
  343. check_options();
  344. if (!sys_check_options())
  345. exit(EXIT_OPTION_ERROR);
  346. auth_check_options();
  347. #ifdef HAVE_MULTILINK
  348. mp_check_options();
  349. #endif
  350. for (i = 0; (protp = protocols[i]) != NULL; ++i)
  351. if (protp->check_options != NULL)
  352. (*protp->check_options)();
  353. if (the_channel->check_options)
  354. (*the_channel->check_options)();
  355. if (dump_options || dryrun) {
  356. init_pr_log(NULL, LOG_INFO);
  357. print_options(pr_log, NULL);
  358. end_pr_log();
  359. }
  360. if (dryrun)
  361. die(0);
  362. /* Make sure fds 0, 1, 2 are open to somewhere. */
  363. fd_devnull = open(_PATH_DEVNULL, O_RDWR);
  364. if (fd_devnull < 0)
  365. fatal("Couldn't open %s: %m", _PATH_DEVNULL);
  366. while (fd_devnull <= 2) {
  367. i = dup(fd_devnull);
  368. if (i < 0)
  369. fatal("Critical shortage of file descriptors: dup failed: %m");
  370. fd_devnull = i;
  371. }
  372. /*
  373. * Initialize system-dependent stuff.
  374. */
  375. sys_init();
  376. #ifdef USE_TDB
  377. pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
  378. if (pppdb != NULL) {
  379. slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
  380. update_db_entry();
  381. } else {
  382. warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
  383. if (multilink) {
  384. warn("Warning: disabling multilink");
  385. multilink = 0;
  386. }
  387. }
  388. #endif
  389. /*
  390. * Detach ourselves from the terminal, if required,
  391. * and identify who is running us.
  392. */
  393. if (!nodetach && !updetach)
  394. detach();
  395. p = getlogin();
  396. if (p == NULL) {
  397. pw = getpwuid(uid);
  398. if (pw != NULL && pw->pw_name != NULL)
  399. p = pw->pw_name;
  400. else
  401. p = "(unknown)";
  402. }
  403. syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
  404. script_setenv("PPPLOGNAME", p, 0);
  405. if (devnam[0])
  406. script_setenv("DEVICE", devnam, 1);
  407. slprintf(numbuf, sizeof(numbuf), "%d", getpid());
  408. script_setenv("PPPD_PID", numbuf, 1);
  409. setup_signals();
  410. create_linkpidfile(getpid());
  411. waiting = 0;
  412. /*
  413. * If we're doing dial-on-demand, set up the interface now.
  414. */
  415. if (demand) {
  416. /*
  417. * Open the loopback channel and set it up to be the ppp interface.
  418. */
  419. fd_loop = open_ppp_loopback();
  420. set_ifunit(1);
  421. /*
  422. * Configure the interface and mark it up, etc.
  423. */
  424. demand_conf();
  425. }
  426. do_callback = 0;
  427. for (;;) {
  428. bundle_eof = 0;
  429. bundle_terminating = 0;
  430. listen_time = 0;
  431. need_holdoff = 1;
  432. devfd = -1;
  433. status = EXIT_OK;
  434. ++unsuccess;
  435. doing_callback = do_callback;
  436. do_callback = 0;
  437. if (demand && !doing_callback) {
  438. /*
  439. * Don't do anything until we see some activity.
  440. */
  441. new_phase(PHASE_DORMANT);
  442. demand_unblock();
  443. add_fd(fd_loop);
  444. for (;;) {
  445. handle_events();
  446. if (asked_to_quit)
  447. break;
  448. if (get_loop_output())
  449. break;
  450. }
  451. remove_fd(fd_loop);
  452. if (asked_to_quit)
  453. break;
  454. /*
  455. * Now we want to bring up the link.
  456. */
  457. demand_block();
  458. info("Starting link");
  459. }
  460. gettimeofday(&start_time, NULL);
  461. script_unsetenv("CONNECT_TIME");
  462. script_unsetenv("BYTES_SENT");
  463. script_unsetenv("BYTES_RCVD");
  464. lcp_open(0); /* Start protocol */
  465. start_link(0);
  466. while (phase != PHASE_DEAD) {
  467. handle_events();
  468. get_input();
  469. if (kill_link)
  470. lcp_close(0, "User request");
  471. if (asked_to_quit) {
  472. bundle_terminating = 1;
  473. if (phase == PHASE_MASTER)
  474. mp_bundle_terminated();
  475. }
  476. if (open_ccp_flag) {
  477. if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
  478. ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
  479. (*ccp_protent.open)(0);
  480. }
  481. }
  482. }
  483. /* restore FSMs to original state */
  484. lcp_close(0, "");
  485. if (!persist || asked_to_quit || (maxfail > 0 && unsuccess >= maxfail))
  486. break;
  487. if (demand)
  488. demand_discard();
  489. t = need_holdoff? holdoff: 0;
  490. if (holdoff_hook)
  491. t = (*holdoff_hook)();
  492. if (t > 0) {
  493. new_phase(PHASE_HOLDOFF);
  494. TIMEOUT(holdoff_end, NULL, t);
  495. do {
  496. handle_events();
  497. if (kill_link)
  498. new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
  499. } while (phase == PHASE_HOLDOFF);
  500. if (!persist)
  501. break;
  502. }
  503. }
  504. /* Wait for scripts to finish */
  505. reap_kids();
  506. if (n_children > 0) {
  507. if (child_wait > 0)
  508. TIMEOUT(childwait_end, NULL, child_wait);
  509. if (debug) {
  510. struct subprocess *chp;
  511. dbglog("Waiting for %d child processes...", n_children);
  512. for (chp = children; chp != NULL; chp = chp->next)
  513. dbglog(" script %s, pid %d", chp->prog, chp->pid);
  514. }
  515. while (n_children > 0 && !childwait_done) {
  516. handle_events();
  517. if (kill_link && !childwait_done)
  518. childwait_end(NULL);
  519. }
  520. }
  521. die(status);
  522. return 0;
  523. }
  524. /*
  525. * handle_events - wait for something to happen and respond to it.
  526. */
  527. static void
  528. handle_events()
  529. {
  530. struct timeval timo;
  531. kill_link = open_ccp_flag = 0;
  532. if (sigsetjmp(sigjmp, 1) == 0) {
  533. sigprocmask(SIG_BLOCK, &signals_handled, NULL);
  534. if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
  535. sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
  536. } else {
  537. waiting = 1;
  538. sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
  539. wait_input(timeleft(&timo));
  540. }
  541. }
  542. waiting = 0;
  543. calltimeout();
  544. if (got_sighup) {
  545. info("Hangup (SIGHUP)");
  546. kill_link = 1;
  547. got_sighup = 0;
  548. if (status != EXIT_HANGUP)
  549. status = EXIT_USER_REQUEST;
  550. }
  551. if (got_sigterm) {
  552. info("Terminating on signal %d", got_sigterm);
  553. kill_link = 1;
  554. asked_to_quit = 1;
  555. persist = 0;
  556. status = EXIT_USER_REQUEST;
  557. got_sigterm = 0;
  558. }
  559. if (got_sigchld) {
  560. got_sigchld = 0;
  561. reap_kids(); /* Don't leave dead kids lying around */
  562. }
  563. if (got_sigusr2) {
  564. open_ccp_flag = 1;
  565. got_sigusr2 = 0;
  566. }
  567. }
  568. /*
  569. * setup_signals - initialize signal handling.
  570. */
  571. static void
  572. setup_signals()
  573. {
  574. struct sigaction sa;
  575. /*
  576. * Compute mask of all interesting signals and install signal handlers
  577. * for each. Only one signal handler may be active at a time. Therefore,
  578. * all other signals should be masked when any handler is executing.
  579. */
  580. sigemptyset(&signals_handled);
  581. sigaddset(&signals_handled, SIGHUP);
  582. sigaddset(&signals_handled, SIGINT);
  583. sigaddset(&signals_handled, SIGTERM);
  584. sigaddset(&signals_handled, SIGCHLD);
  585. sigaddset(&signals_handled, SIGUSR2);
  586. #define SIGNAL(s, handler) do { \
  587. sa.sa_handler = handler; \
  588. if (sigaction(s, &sa, NULL) < 0) \
  589. fatal("Couldn't establish signal handler (%d): %m", s); \
  590. } while (0)
  591. sa.sa_mask = signals_handled;
  592. sa.sa_flags = 0;
  593. SIGNAL(SIGHUP, hup); /* Hangup */
  594. SIGNAL(SIGINT, term); /* Interrupt */
  595. SIGNAL(SIGTERM, term); /* Terminate */
  596. SIGNAL(SIGCHLD, chld);
  597. SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
  598. SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
  599. /*
  600. * Install a handler for other signals which would otherwise
  601. * cause pppd to exit without cleaning up.
  602. */
  603. SIGNAL(SIGABRT, bad_signal);
  604. SIGNAL(SIGALRM, bad_signal);
  605. SIGNAL(SIGFPE, bad_signal);
  606. SIGNAL(SIGILL, bad_signal);
  607. SIGNAL(SIGPIPE, bad_signal);
  608. SIGNAL(SIGQUIT, bad_signal);
  609. SIGNAL(SIGSEGV, bad_signal);
  610. #ifdef SIGBUS
  611. SIGNAL(SIGBUS, bad_signal);
  612. #endif
  613. #ifdef SIGEMT
  614. SIGNAL(SIGEMT, bad_signal);
  615. #endif
  616. #ifdef SIGPOLL
  617. SIGNAL(SIGPOLL, bad_signal);
  618. #endif
  619. #ifdef SIGPROF
  620. SIGNAL(SIGPROF, bad_signal);
  621. #endif
  622. #ifdef SIGSYS
  623. SIGNAL(SIGSYS, bad_signal);
  624. #endif
  625. #ifdef SIGTRAP
  626. SIGNAL(SIGTRAP, bad_signal);
  627. #endif
  628. #ifdef SIGVTALRM
  629. SIGNAL(SIGVTALRM, bad_signal);
  630. #endif
  631. #ifdef SIGXCPU
  632. SIGNAL(SIGXCPU, bad_signal);
  633. #endif
  634. #ifdef SIGXFSZ
  635. SIGNAL(SIGXFSZ, bad_signal);
  636. #endif
  637. /*
  638. * Apparently we can get a SIGPIPE when we call syslog, if
  639. * syslogd has died and been restarted. Ignoring it seems
  640. * be sufficient.
  641. */
  642. signal(SIGPIPE, SIG_IGN);
  643. }
  644. /*
  645. * set_ifunit - do things we need to do once we know which ppp
  646. * unit we are using.
  647. */
  648. void
  649. set_ifunit(iskey)
  650. int iskey;
  651. {
  652. info("Using interface %s%d", PPP_DRV_NAME, ifunit);
  653. slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
  654. script_setenv("IFNAME", ifname, iskey);
  655. if (iskey) {
  656. create_pidfile(getpid()); /* write pid to file */
  657. create_linkpidfile(getpid());
  658. }
  659. }
  660. /*
  661. * detach - detach us from the controlling terminal.
  662. */
  663. void
  664. detach()
  665. {
  666. int pid;
  667. char numbuf[16];
  668. int pipefd[2];
  669. if (detached)
  670. return;
  671. if (pipe(pipefd) == -1)
  672. pipefd[0] = pipefd[1] = -1;
  673. if ((pid = fork()) < 0) {
  674. error("Couldn't detach (fork failed: %m)");
  675. die(1); /* or just return? */
  676. }
  677. if (pid != 0) {
  678. /* parent */
  679. notify(pidchange, pid);
  680. /* update pid files if they have been written already */
  681. if (pidfilename[0])
  682. create_pidfile(pid);
  683. if (linkpidfile[0])
  684. create_linkpidfile(pid);
  685. exit(0); /* parent dies */
  686. }
  687. setsid();
  688. chdir("/");
  689. dup2(fd_devnull, 0);
  690. dup2(fd_devnull, 1);
  691. dup2(fd_devnull, 2);
  692. detached = 1;
  693. if (log_default)
  694. log_to_fd = -1;
  695. slprintf(numbuf, sizeof(numbuf), "%d", getpid());
  696. script_setenv("PPPD_PID", numbuf, 1);
  697. /* wait for parent to finish updating pid & lock files and die */
  698. close(pipefd[1]);
  699. complete_read(pipefd[0], numbuf, 1);
  700. close(pipefd[0]);
  701. }
  702. /*
  703. * reopen_log - (re)open our connection to syslog.
  704. */
  705. void
  706. reopen_log()
  707. {
  708. openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
  709. setlogmask(LOG_UPTO(LOG_INFO));
  710. }
  711. /*
  712. * Create a file containing our process ID.
  713. */
  714. static void
  715. create_pidfile(pid)
  716. int pid;
  717. {
  718. FILE *pidfile;
  719. slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
  720. _PATH_VARRUN, ifname);
  721. if ((pidfile = fopen(pidfilename, "w")) != NULL) {
  722. fprintf(pidfile, "%d\n", pid);
  723. (void) fclose(pidfile);
  724. } else {
  725. error("Failed to create pid file %s: %m", pidfilename);
  726. pidfilename[0] = 0;
  727. }
  728. }
  729. void
  730. create_linkpidfile(pid)
  731. int pid;
  732. {
  733. FILE *pidfile;
  734. if (linkname[0] == 0)
  735. return;
  736. script_setenv("LINKNAME", linkname, 1);
  737. slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
  738. _PATH_VARRUN, linkname);
  739. if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
  740. fprintf(pidfile, "%d\n", pid);
  741. if (ifname[0])
  742. fprintf(pidfile, "%s\n", ifname);
  743. (void) fclose(pidfile);
  744. } else {
  745. error("Failed to create pid file %s: %m", linkpidfile);
  746. linkpidfile[0] = 0;
  747. }
  748. }
  749. /*
  750. * remove_pidfile - remove our pid files
  751. */
  752. void remove_pidfiles()
  753. {
  754. if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
  755. warn("unable to delete pid file %s: %m", pidfilename);
  756. pidfilename[0] = 0;
  757. if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
  758. warn("unable to delete pid file %s: %m", linkpidfile);
  759. linkpidfile[0] = 0;
  760. }
  761. /*
  762. * holdoff_end - called via a timeout when the holdoff period ends.
  763. */
  764. static void
  765. holdoff_end(arg)
  766. void *arg;
  767. {
  768. new_phase(PHASE_DORMANT);
  769. }
  770. /* List of protocol names, to make our messages a little more informative. */
  771. struct protocol_list {
  772. u_short proto;
  773. const char *name;
  774. } protocol_list[] = {
  775. { 0x21, "IP" },
  776. { 0x23, "OSI Network Layer" },
  777. { 0x25, "Xerox NS IDP" },
  778. { 0x27, "DECnet Phase IV" },
  779. { 0x29, "Appletalk" },
  780. { 0x2b, "Novell IPX" },
  781. { 0x2d, "VJ compressed TCP/IP" },
  782. { 0x2f, "VJ uncompressed TCP/IP" },
  783. { 0x31, "Bridging PDU" },
  784. { 0x33, "Stream Protocol ST-II" },
  785. { 0x35, "Banyan Vines" },
  786. { 0x39, "AppleTalk EDDP" },
  787. { 0x3b, "AppleTalk SmartBuffered" },
  788. { 0x3d, "Multi-Link" },
  789. { 0x3f, "NETBIOS Framing" },
  790. { 0x41, "Cisco Systems" },
  791. { 0x43, "Ascom Timeplex" },
  792. { 0x45, "Fujitsu Link Backup and Load Balancing (LBLB)" },
  793. { 0x47, "DCA Remote Lan" },
  794. { 0x49, "Serial Data Transport Protocol (PPP-SDTP)" },
  795. { 0x4b, "SNA over 802.2" },
  796. { 0x4d, "SNA" },
  797. { 0x4f, "IP6 Header Compression" },
  798. { 0x51, "KNX Bridging Data" },
  799. { 0x53, "Encryption" },
  800. { 0x55, "Individual Link Encryption" },
  801. { 0x57, "IPv6" },
  802. { 0x59, "PPP Muxing" },
  803. { 0x5b, "Vendor-Specific Network Protocol" },
  804. { 0x61, "RTP IPHC Full Header" },
  805. { 0x63, "RTP IPHC Compressed TCP" },
  806. { 0x65, "RTP IPHC Compressed non-TCP" },
  807. { 0x67, "RTP IPHC Compressed UDP 8" },
  808. { 0x69, "RTP IPHC Compressed RTP 8" },
  809. { 0x6f, "Stampede Bridging" },
  810. { 0x73, "MP+" },
  811. { 0xc1, "NTCITS IPI" },
  812. { 0xfb, "single-link compression" },
  813. { 0xfd, "Compressed Datagram" },
  814. { 0x0201, "802.1d Hello Packets" },
  815. { 0x0203, "IBM Source Routing BPDU" },
  816. { 0x0205, "DEC LANBridge100 Spanning Tree" },
  817. { 0x0207, "Cisco Discovery Protocol" },
  818. { 0x0209, "Netcs Twin Routing" },
  819. { 0x020b, "STP - Scheduled Transfer Protocol" },
  820. { 0x020d, "EDP - Extreme Discovery Protocol" },
  821. { 0x0211, "Optical Supervisory Channel Protocol" },
  822. { 0x0213, "Optical Supervisory Channel Protocol" },
  823. { 0x0231, "Luxcom" },
  824. { 0x0233, "Sigma Network Systems" },
  825. { 0x0235, "Apple Client Server Protocol" },
  826. { 0x0281, "MPLS Unicast" },
  827. { 0x0283, "MPLS Multicast" },
  828. { 0x0285, "IEEE p1284.4 standard - data packets" },
  829. { 0x0287, "ETSI TETRA Network Protocol Type 1" },
  830. { 0x0289, "Multichannel Flow Treatment Protocol" },
  831. { 0x2063, "RTP IPHC Compressed TCP No Delta" },
  832. { 0x2065, "RTP IPHC Context State" },
  833. { 0x2067, "RTP IPHC Compressed UDP 16" },
  834. { 0x2069, "RTP IPHC Compressed RTP 16" },
  835. { 0x4001, "Cray Communications Control Protocol" },
  836. { 0x4003, "CDPD Mobile Network Registration Protocol" },
  837. { 0x4005, "Expand accelerator protocol" },
  838. { 0x4007, "ODSICP NCP" },
  839. { 0x4009, "DOCSIS DLL" },
  840. { 0x400B, "Cetacean Network Detection Protocol" },
  841. { 0x4021, "Stacker LZS" },
  842. { 0x4023, "RefTek Protocol" },
  843. { 0x4025, "Fibre Channel" },
  844. { 0x4027, "EMIT Protocols" },
  845. { 0x405b, "Vendor-Specific Protocol (VSP)" },
  846. { 0x8021, "Internet Protocol Control Protocol" },
  847. { 0x8023, "OSI Network Layer Control Protocol" },
  848. { 0x8025, "Xerox NS IDP Control Protocol" },
  849. { 0x8027, "DECnet Phase IV Control Protocol" },
  850. { 0x8029, "Appletalk Control Protocol" },
  851. { 0x802b, "Novell IPX Control Protocol" },
  852. { 0x8031, "Bridging NCP" },
  853. { 0x8033, "Stream Protocol Control Protocol" },
  854. { 0x8035, "Banyan Vines Control Protocol" },
  855. { 0x803d, "Multi-Link Control Protocol" },
  856. { 0x803f, "NETBIOS Framing Control Protocol" },
  857. { 0x8041, "Cisco Systems Control Protocol" },
  858. { 0x8043, "Ascom Timeplex" },
  859. { 0x8045, "Fujitsu LBLB Control Protocol" },
  860. { 0x8047, "DCA Remote Lan Network Control Protocol (RLNCP)" },
  861. { 0x8049, "Serial Data Control Protocol (PPP-SDCP)" },
  862. { 0x804b, "SNA over 802.2 Control Protocol" },
  863. { 0x804d, "SNA Control Protocol" },
  864. { 0x804f, "IP6 Header Compression Control Protocol" },
  865. { 0x8051, "KNX Bridging Control Protocol" },
  866. { 0x8053, "Encryption Control Protocol" },
  867. { 0x8055, "Individual Link Encryption Control Protocol" },
  868. { 0x8057, "IPv6 Control Protocol" },
  869. { 0x8059, "PPP Muxing Control Protocol" },
  870. { 0x805b, "Vendor-Specific Network Control Protocol (VSNCP)" },
  871. { 0x806f, "Stampede Bridging Control Protocol" },
  872. { 0x8073, "MP+ Control Protocol" },
  873. { 0x80c1, "NTCITS IPI Control Protocol" },
  874. { 0x80fb, "Single Link Compression Control Protocol" },
  875. { 0x80fd, "Compression Control Protocol" },
  876. { 0x8207, "Cisco Discovery Protocol Control" },
  877. { 0x8209, "Netcs Twin Routing" },
  878. { 0x820b, "STP - Control Protocol" },
  879. { 0x820d, "EDPCP - Extreme Discovery Protocol Ctrl Prtcl" },
  880. { 0x8235, "Apple Client Server Protocol Control" },
  881. { 0x8281, "MPLSCP" },
  882. { 0x8285, "IEEE p1284.4 standard - Protocol Control" },
  883. { 0x8287, "ETSI TETRA TNP1 Control Protocol" },
  884. { 0x8289, "Multichannel Flow Treatment Protocol" },
  885. { 0xc021, "Link Control Protocol" },
  886. { 0xc023, "Password Authentication Protocol" },
  887. { 0xc025, "Link Quality Report" },
  888. { 0xc027, "Shiva Password Authentication Protocol" },
  889. { 0xc029, "CallBack Control Protocol (CBCP)" },
  890. { 0xc02b, "BACP Bandwidth Allocation Control Protocol" },
  891. { 0xc02d, "BAP" },
  892. { 0xc05b, "Vendor-Specific Authentication Protocol (VSAP)" },
  893. { 0xc081, "Container Control Protocol" },
  894. { 0xc223, "Challenge Handshake Authentication Protocol" },
  895. { 0xc225, "RSA Authentication Protocol" },
  896. { 0xc227, "Extensible Authentication Protocol" },
  897. { 0xc229, "Mitsubishi Security Info Exch Ptcl (SIEP)" },
  898. { 0xc26f, "Stampede Bridging Authorization Protocol" },
  899. { 0xc281, "Proprietary Authentication Protocol" },
  900. { 0xc283, "Proprietary Authentication Protocol" },
  901. { 0xc481, "Proprietary Node ID Authentication Protocol" },
  902. { 0, NULL },
  903. };
  904. /*
  905. * protocol_name - find a name for a PPP protocol.
  906. */
  907. const char *
  908. protocol_name(proto)
  909. int proto;
  910. {
  911. struct protocol_list *lp;
  912. for (lp = protocol_list; lp->proto != 0; ++lp)
  913. if (proto == lp->proto)
  914. return lp->name;
  915. return NULL;
  916. }
  917. /*
  918. * get_input - called when incoming data is available.
  919. */
  920. static void
  921. get_input()
  922. {
  923. int len, i;
  924. u_char *p;
  925. u_short protocol;
  926. struct protent *protp;
  927. p = inpacket_buf; /* point to beginning of packet buffer */
  928. len = read_packet(inpacket_buf);
  929. if (len < 0)
  930. return;
  931. if (len == 0) {
  932. if (bundle_eof && multilink_master) {
  933. notice("Last channel has disconnected");
  934. mp_bundle_terminated();
  935. return;
  936. }
  937. notice("Modem hangup");
  938. hungup = 1;
  939. status = EXIT_HANGUP;
  940. lcp_lowerdown(0); /* serial link is no longer available */
  941. link_terminated(0);
  942. return;
  943. }
  944. if (len < PPP_HDRLEN) {
  945. dbglog("received short packet:%.*B", len, p);
  946. return;
  947. }
  948. dump_packet("rcvd", p, len);
  949. if (snoop_recv_hook) snoop_recv_hook(p, len);
  950. p += 2; /* Skip address and control */
  951. GETSHORT(protocol, p);
  952. len -= PPP_HDRLEN;
  953. /*
  954. * Toss all non-LCP packets unless LCP is OPEN.
  955. */
  956. if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
  957. dbglog("Discarded non-LCP packet when LCP not open");
  958. return;
  959. }
  960. /*
  961. * Until we get past the authentication phase, toss all packets
  962. * except LCP, LQR and authentication packets.
  963. */
  964. if (phase <= PHASE_AUTHENTICATE
  965. && !(protocol == PPP_LCP || protocol == PPP_LQR
  966. || protocol == PPP_PAP || protocol == PPP_CHAP ||
  967. protocol == PPP_EAP)) {
  968. dbglog("discarding proto 0x%x in phase %d",
  969. protocol, phase);
  970. return;
  971. }
  972. /*
  973. * Upcall the proper protocol input routine.
  974. */
  975. for (i = 0; (protp = protocols[i]) != NULL; ++i) {
  976. if (protp->protocol == protocol && protp->enabled_flag) {
  977. (*protp->input)(0, p, len);
  978. return;
  979. }
  980. if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
  981. && protp->datainput != NULL) {
  982. (*protp->datainput)(0, p, len);
  983. return;
  984. }
  985. }
  986. if (debug) {
  987. const char *pname = protocol_name(protocol);
  988. if (pname != NULL)
  989. warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
  990. else
  991. warn("Unsupported protocol 0x%x received", protocol);
  992. }
  993. lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
  994. }
  995. /*
  996. * ppp_send_config - configure the transmit-side characteristics of
  997. * the ppp interface. Returns -1, indicating an error, if the channel
  998. * send_config procedure called error() (or incremented error_count
  999. * itself), otherwise 0.
  1000. */
  1001. int
  1002. ppp_send_config(unit, mtu, accm, pcomp, accomp)
  1003. int unit, mtu;
  1004. u_int32_t accm;
  1005. int pcomp, accomp;
  1006. {
  1007. int errs;
  1008. if (the_channel->send_config == NULL)
  1009. return 0;
  1010. errs = error_count;
  1011. (*the_channel->send_config)(mtu, accm, pcomp, accomp);
  1012. return (error_count != errs)? -1: 0;
  1013. }
  1014. /*
  1015. * ppp_recv_config - configure the receive-side characteristics of
  1016. * the ppp interface. Returns -1, indicating an error, if the channel
  1017. * recv_config procedure called error() (or incremented error_count
  1018. * itself), otherwise 0.
  1019. */
  1020. int
  1021. ppp_recv_config(unit, mru, accm, pcomp, accomp)
  1022. int unit, mru;
  1023. u_int32_t accm;
  1024. int pcomp, accomp;
  1025. {
  1026. int errs;
  1027. if (the_channel->recv_config == NULL)
  1028. return 0;
  1029. errs = error_count;
  1030. (*the_channel->recv_config)(mru, accm, pcomp, accomp);
  1031. return (error_count != errs)? -1: 0;
  1032. }
  1033. /*
  1034. * new_phase - signal the start of a new phase of pppd's operation.
  1035. */
  1036. void
  1037. new_phase(p)
  1038. int p;
  1039. {
  1040. phase = p;
  1041. if (new_phase_hook)
  1042. (*new_phase_hook)(p);
  1043. notify(phasechange, p);
  1044. }
  1045. /*
  1046. * die - clean up state and exit with the specified status.
  1047. */
  1048. void
  1049. die(status)
  1050. int status;
  1051. {
  1052. if (!doing_multilink || multilink_master)
  1053. print_link_stats();
  1054. cleanup();
  1055. notify(exitnotify, status);
  1056. syslog(LOG_INFO, "Exit.");
  1057. exit(status);
  1058. }
  1059. /*
  1060. * cleanup - restore anything which needs to be restored before we exit
  1061. */
  1062. /* ARGSUSED */
  1063. static void
  1064. cleanup()
  1065. {
  1066. sys_cleanup();
  1067. if (fd_ppp >= 0)
  1068. the_channel->disestablish_ppp(devfd);
  1069. if (the_channel->cleanup)
  1070. (*the_channel->cleanup)();
  1071. remove_pidfiles();
  1072. #ifdef USE_TDB
  1073. if (pppdb != NULL)
  1074. cleanup_db();
  1075. #endif
  1076. }
  1077. void
  1078. print_link_stats()
  1079. {
  1080. /*
  1081. * Print connect time and statistics.
  1082. */
  1083. if (link_stats_valid) {
  1084. int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
  1085. info("Connect time %d.%d minutes.", t/10, t%10);
  1086. info("Sent %u bytes, received %u bytes.",
  1087. link_stats.bytes_out, link_stats.bytes_in);
  1088. link_stats_valid = 0;
  1089. }
  1090. }
  1091. /*
  1092. * reset_link_stats - "reset" stats when link goes up.
  1093. */
  1094. void
  1095. reset_link_stats(u)
  1096. int u;
  1097. {
  1098. if (!get_ppp_stats(u, &old_link_stats))
  1099. return;
  1100. gettimeofday(&start_time, NULL);
  1101. }
  1102. /*
  1103. * update_link_stats - get stats at link termination.
  1104. */
  1105. void
  1106. update_link_stats(u)
  1107. int u;
  1108. {
  1109. struct timeval now;
  1110. char numbuf[32];
  1111. if (!get_ppp_stats(u, &link_stats)
  1112. || gettimeofday(&now, NULL) < 0)
  1113. return;
  1114. link_connect_time = now.tv_sec - start_time.tv_sec;
  1115. link_stats_valid = 1;
  1116. link_stats.bytes_in -= old_link_stats.bytes_in;
  1117. link_stats.bytes_out -= old_link_stats.bytes_out;
  1118. link_stats.pkts_in -= old_link_stats.pkts_in;
  1119. link_stats.pkts_out -= old_link_stats.pkts_out;
  1120. slprintf(numbuf, sizeof(numbuf), "%u", link_connect_time);
  1121. script_setenv("CONNECT_TIME", numbuf, 0);
  1122. slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_out);
  1123. script_setenv("BYTES_SENT", numbuf, 0);
  1124. slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_in);
  1125. script_setenv("BYTES_RCVD", numbuf, 0);
  1126. }
  1127. struct callout {
  1128. struct timeval c_time; /* time at which to call routine */
  1129. void *c_arg; /* argument to routine */
  1130. void (*c_func) __P((void *)); /* routine */
  1131. struct callout *c_next;
  1132. };
  1133. static struct callout *callout = NULL; /* Callout list */
  1134. static struct timeval timenow; /* Current time */
  1135. /*
  1136. * timeout - Schedule a timeout.
  1137. */
  1138. void
  1139. timeout(func, arg, secs, usecs)
  1140. void (*func) __P((void *));
  1141. void *arg;
  1142. int secs, usecs;
  1143. {
  1144. struct callout *newp, *p, **pp;
  1145. /*
  1146. * Allocate timeout.
  1147. */
  1148. if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
  1149. fatal("Out of memory in timeout()!");
  1150. newp->c_arg = arg;
  1151. newp->c_func = func;
  1152. gettimeofday(&timenow, NULL);
  1153. newp->c_time.tv_sec = timenow.tv_sec + secs;
  1154. newp->c_time.tv_usec = timenow.tv_usec + usecs;
  1155. if (newp->c_time.tv_usec >= 1000000) {
  1156. newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
  1157. newp->c_time.tv_usec %= 1000000;
  1158. }
  1159. /*
  1160. * Find correct place and link it in.
  1161. */
  1162. for (pp = &callout; (p = *pp); pp = &p->c_next)
  1163. if (newp->c_time.tv_sec < p->c_time.tv_sec
  1164. || (newp->c_time.tv_sec == p->c_time.tv_sec
  1165. && newp->c_time.tv_usec < p->c_time.tv_usec))
  1166. break;
  1167. newp->c_next = p;
  1168. *pp = newp;
  1169. }
  1170. /*
  1171. * untimeout - Unschedule a timeout.
  1172. */
  1173. void
  1174. untimeout(func, arg)
  1175. void (*func) __P((void *));
  1176. void *arg;
  1177. {
  1178. struct callout **copp, *freep;
  1179. /*
  1180. * Find first matching timeout and remove it from the list.
  1181. */
  1182. for (copp = &callout; (freep = *copp); copp = &freep->c_next)
  1183. if (freep->c_func == func && freep->c_arg == arg) {
  1184. *copp = freep->c_next;
  1185. free((char *) freep);
  1186. break;
  1187. }
  1188. }
  1189. /*
  1190. * calltimeout - Call any timeout routines which are now due.
  1191. */
  1192. static void
  1193. calltimeout()
  1194. {
  1195. struct callout *p;
  1196. while (callout != NULL) {
  1197. p = callout;
  1198. if (gettimeofday(&timenow, NULL) < 0)
  1199. fatal("Failed to get time of day: %m");
  1200. if (!(p->c_time.tv_sec < timenow.tv_sec
  1201. || (p->c_time.tv_sec == timenow.tv_sec
  1202. && p->c_time.tv_usec <= timenow.tv_usec)))
  1203. break; /* no, it's not time yet */
  1204. callout = p->c_next;
  1205. (*p->c_func)(p->c_arg);
  1206. free((char *) p);
  1207. }
  1208. }
  1209. /*
  1210. * timeleft - return the length of time until the next timeout is due.
  1211. */
  1212. static struct timeval *
  1213. timeleft(tvp)
  1214. struct timeval *tvp;
  1215. {
  1216. if (callout == NULL)
  1217. return NULL;
  1218. gettimeofday(&timenow, NULL);
  1219. tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
  1220. tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
  1221. if (tvp->tv_usec < 0) {
  1222. tvp->tv_usec += 1000000;
  1223. tvp->tv_sec -= 1;
  1224. }
  1225. if (tvp->tv_sec < 0)
  1226. tvp->tv_sec = tvp->tv_usec = 0;
  1227. return tvp;
  1228. }
  1229. /*
  1230. * kill_my_pg - send a signal to our process group, and ignore it ourselves.
  1231. * We assume that sig is currently blocked.
  1232. */
  1233. static void
  1234. kill_my_pg(sig)
  1235. int sig;
  1236. {
  1237. struct sigaction act, oldact;
  1238. struct subprocess *chp;
  1239. if (!detached) {
  1240. /*
  1241. * There might be other things in our process group that we
  1242. * didn't start that would get hit if we did a kill(0), so
  1243. * just send the signal individually to our children.
  1244. */
  1245. for (chp = children; chp != NULL; chp = chp->next)
  1246. if (chp->killable)
  1247. kill(chp->pid, sig);
  1248. return;
  1249. }
  1250. /* We've done a setsid(), so we can just use a kill(0) */
  1251. sigemptyset(&act.sa_mask); /* unnecessary in fact */
  1252. act.sa_handler = SIG_IGN;
  1253. act.sa_flags = 0;
  1254. kill(0, sig);
  1255. /*
  1256. * The kill() above made the signal pending for us, as well as
  1257. * the rest of our process group, but we don't want it delivered
  1258. * to us. It is blocked at the moment. Setting it to be ignored
  1259. * will cause the pending signal to be discarded. If we did the
  1260. * kill() after setting the signal to be ignored, it is unspecified
  1261. * (by POSIX) whether the signal is immediately discarded or left
  1262. * pending, and in fact Linux would leave it pending, and so it
  1263. * would be delivered after the current signal handler exits,
  1264. * leading to an infinite loop.
  1265. */
  1266. sigaction(sig, &act, &oldact);
  1267. sigaction(sig, &oldact, NULL);
  1268. }
  1269. /*
  1270. * hup - Catch SIGHUP signal.
  1271. *
  1272. * Indicates that the physical layer has been disconnected.
  1273. * We don't rely on this indication; if the user has sent this
  1274. * signal, we just take the link down.
  1275. */
  1276. static void
  1277. hup(sig)
  1278. int sig;
  1279. {
  1280. /* can't log a message here, it can deadlock */
  1281. got_sighup = 1;
  1282. if (conn_running)
  1283. /* Send the signal to the [dis]connector process(es) also */
  1284. kill_my_pg(sig);
  1285. notify(sigreceived, sig);
  1286. if (waiting)
  1287. siglongjmp(sigjmp, 1);
  1288. }
  1289. /*
  1290. * term - Catch SIGTERM signal and SIGINT signal (^C/del).
  1291. *
  1292. * Indicates that we should initiate a graceful disconnect and exit.
  1293. */
  1294. /*ARGSUSED*/
  1295. static void
  1296. term(sig)
  1297. int sig;
  1298. {
  1299. /* can't log a message here, it can deadlock */
  1300. got_sigterm = sig;
  1301. if (conn_running)
  1302. /* Send the signal to the [dis]connector process(es) also */
  1303. kill_my_pg(sig);
  1304. notify(sigreceived, sig);
  1305. if (waiting)
  1306. siglongjmp(sigjmp, 1);
  1307. }
  1308. /*
  1309. * chld - Catch SIGCHLD signal.
  1310. * Sets a flag so we will call reap_kids in the mainline.
  1311. */
  1312. static void
  1313. chld(sig)
  1314. int sig;
  1315. {
  1316. got_sigchld = 1;
  1317. if (waiting)
  1318. siglongjmp(sigjmp, 1);
  1319. }
  1320. /*
  1321. * toggle_debug - Catch SIGUSR1 signal.
  1322. *
  1323. * Toggle debug flag.
  1324. */
  1325. /*ARGSUSED*/
  1326. static void
  1327. toggle_debug(sig)
  1328. int sig;
  1329. {
  1330. debug = !debug;
  1331. if (debug) {
  1332. setlogmask(LOG_UPTO(LOG_DEBUG));
  1333. } else {
  1334. setlogmask(LOG_UPTO(LOG_WARNING));
  1335. }
  1336. }
  1337. /*
  1338. * open_ccp - Catch SIGUSR2 signal.
  1339. *
  1340. * Try to (re)negotiate compression.
  1341. */
  1342. /*ARGSUSED*/
  1343. static void
  1344. open_ccp(sig)
  1345. int sig;
  1346. {
  1347. got_sigusr2 = 1;
  1348. if (waiting)
  1349. siglongjmp(sigjmp, 1);
  1350. }
  1351. /*
  1352. * bad_signal - We've caught a fatal signal. Clean up state and exit.
  1353. */
  1354. static void
  1355. bad_signal(sig)
  1356. int sig;
  1357. {
  1358. static int crashed = 0;
  1359. if (crashed)
  1360. _exit(127);
  1361. crashed = 1;
  1362. error("Fatal signal %d", sig);
  1363. if (conn_running)
  1364. kill_my_pg(SIGTERM);
  1365. notify(sigreceived, sig);
  1366. die(127);
  1367. }
  1368. /*
  1369. * safe_fork - Create a child process. The child closes all the
  1370. * file descriptors that we don't want to leak to a script.
  1371. * The parent waits for the child to do this before returning.
  1372. * This also arranges for the specified fds to be dup'd to
  1373. * fds 0, 1, 2 in the child.
  1374. */
  1375. pid_t
  1376. safe_fork(int infd, int outfd, int errfd)
  1377. {
  1378. pid_t pid;
  1379. int fd, pipefd[2];
  1380. char buf[1];
  1381. /* make sure fds 0, 1, 2 are occupied (probably not necessary) */
  1382. while ((fd = dup(fd_devnull)) >= 0) {
  1383. if (fd > 2) {
  1384. close(fd);
  1385. break;
  1386. }
  1387. }
  1388. if (pipe(pipefd) == -1)
  1389. pipefd[0] = pipefd[1] = -1;
  1390. pid = fork();
  1391. if (pid < 0) {
  1392. error("fork failed: %m");
  1393. return -1;
  1394. }
  1395. if (pid > 0) {
  1396. /* parent */
  1397. close(pipefd[1]);
  1398. /* this read() blocks until the close(pipefd[1]) below */
  1399. complete_read(pipefd[0], buf, 1);
  1400. close(pipefd[0]);
  1401. return pid;
  1402. }
  1403. /* Executing in the child */
  1404. sys_close();
  1405. #ifdef USE_TDB
  1406. tdb_close(pppdb);
  1407. #endif
  1408. /* make sure infd, outfd and errfd won't get tromped on below */
  1409. if (infd == 1 || infd == 2)
  1410. infd = dup(infd);
  1411. if (outfd == 0 || outfd == 2)
  1412. outfd = dup(outfd);
  1413. if (errfd == 0 || errfd == 1)
  1414. errfd = dup(errfd);
  1415. closelog();
  1416. /* dup the in, out, err fds to 0, 1, 2 */
  1417. if (infd != 0)
  1418. dup2(infd, 0);
  1419. if (outfd != 1)
  1420. dup2(outfd, 1);
  1421. if (errfd != 2)
  1422. dup2(errfd, 2);
  1423. if (log_to_fd > 2)
  1424. close(log_to_fd);
  1425. if (the_channel->close)
  1426. (*the_channel->close)();
  1427. else
  1428. close(devfd); /* some plugins don't have a close function */
  1429. close(fd_ppp);
  1430. close(fd_devnull);
  1431. if (infd != 0)
  1432. close(infd);
  1433. if (outfd != 1)
  1434. close(outfd);
  1435. if (errfd != 2)
  1436. close(errfd);
  1437. notify(fork_notifier, 0);
  1438. close(pipefd[0]);
  1439. /* this close unblocks the read() call above in the parent */
  1440. close(pipefd[1]);
  1441. return 0;
  1442. }
  1443. static bool
  1444. add_script_env(pos, newstring)
  1445. int pos;
  1446. char *newstring;
  1447. {
  1448. if (pos + 1 >= s_env_nalloc) {
  1449. int new_n = pos + 17;
  1450. char **newenv = realloc(script_env, new_n * sizeof(char *));
  1451. if (newenv == NULL) {
  1452. free(newstring - 1);
  1453. return 0;
  1454. }
  1455. script_env = newenv;
  1456. s_env_nalloc = new_n;
  1457. }
  1458. script_env[pos] = newstring;
  1459. script_env[pos + 1] = NULL;
  1460. return 1;
  1461. }
  1462. static void
  1463. remove_script_env(pos)
  1464. int pos;
  1465. {
  1466. free(script_env[pos] - 1);
  1467. while ((script_env[pos] = script_env[pos + 1]) != NULL)
  1468. pos++;
  1469. }
  1470. /*
  1471. * update_system_environment - process the list of set/unset options
  1472. * and update the system environment.
  1473. */
  1474. static void
  1475. update_system_environment()
  1476. {
  1477. struct userenv *uep;
  1478. for (uep = userenv_list; uep != NULL; uep = uep->ue_next) {
  1479. if (uep->ue_isset)
  1480. setenv(uep->ue_name, uep->ue_value, 1);
  1481. else
  1482. unsetenv(uep->ue_name);
  1483. }
  1484. }
  1485. /*
  1486. * device_script - run a program to talk to the specified fds
  1487. * (e.g. to run the connector or disconnector script).
  1488. * stderr gets connected to the log fd or to the _PATH_CONNERRS file.
  1489. */
  1490. int
  1491. device_script(program, in, out, dont_wait)
  1492. char *program;
  1493. int in, out;
  1494. int dont_wait;
  1495. {
  1496. int pid;
  1497. int status = -1;
  1498. int errfd;
  1499. if (log_to_fd >= 0)
  1500. errfd = log_to_fd;
  1501. else
  1502. errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
  1503. ++conn_running;
  1504. pid = safe_fork(in, out, errfd);
  1505. if (pid != 0 && log_to_fd < 0)
  1506. close(errfd);
  1507. if (pid < 0) {
  1508. --conn_running;
  1509. error("Failed to create child process: %m");
  1510. return -1;
  1511. }
  1512. if (pid != 0) {
  1513. record_child(pid, program, NULL, NULL, 1);
  1514. status = 0;
  1515. if (!dont_wait) {
  1516. while (waitpid(pid, &status, 0) < 0) {
  1517. if (errno == EINTR)
  1518. continue;
  1519. fatal("error waiting for (dis)connection process: %m");
  1520. }
  1521. forget_child(pid, status);
  1522. --conn_running;
  1523. }
  1524. return (status == 0 ? 0 : -1);
  1525. }
  1526. /* here we are executing in the child */
  1527. setgid(getgid());
  1528. setuid(uid);
  1529. if (getuid() != uid) {
  1530. fprintf(stderr, "pppd: setuid failed\n");
  1531. exit(1);
  1532. }
  1533. update_system_environment();
  1534. execl("/bin/sh", "sh", "-c", program, (char *)0);
  1535. perror("pppd: could not exec /bin/sh");
  1536. _exit(99);
  1537. /* NOTREACHED */
  1538. }
  1539. /*
  1540. * update_script_environment - process the list of set/unset options
  1541. * and update the script environment. Note that we intentionally do
  1542. * not update the TDB. These changes are layered on top right before
  1543. * exec. It is not possible to use script_setenv() or
  1544. * script_unsetenv() safely after this routine is run.
  1545. */
  1546. static void
  1547. update_script_environment()
  1548. {
  1549. struct userenv *uep;
  1550. for (uep = userenv_list; uep != NULL; uep = uep->ue_next) {
  1551. int i;
  1552. char *p, *newstring;
  1553. int nlen = strlen(uep->ue_name);
  1554. for (i = 0; (p = script_env[i]) != NULL; i++) {
  1555. if (strncmp(p, uep->ue_name, nlen) == 0 && p[nlen] == '=')
  1556. break;
  1557. }
  1558. if (uep->ue_isset) {
  1559. nlen += strlen(uep->ue_value) + 2;
  1560. newstring = malloc(nlen + 1);
  1561. if (newstring == NULL)
  1562. continue;
  1563. *newstring++ = 0;
  1564. slprintf(newstring, nlen, "%s=%s", uep->ue_name, uep->ue_value);
  1565. if (p != NULL)
  1566. script_env[i] = newstring;
  1567. else
  1568. add_script_env(i, newstring);
  1569. } else {
  1570. remove_script_env(i);
  1571. }
  1572. }
  1573. }
  1574. /*
  1575. * run_program - execute a program with given arguments,
  1576. * but don't wait for it unless wait is non-zero.
  1577. * If the program can't be executed, logs an error unless
  1578. * must_exist is 0 and the program file doesn't exist.
  1579. * Returns -1 if it couldn't fork, 0 if the file doesn't exist
  1580. * or isn't an executable plain file, or the process ID of the child.
  1581. * If done != NULL, (*done)(arg) will be called later (within
  1582. * reap_kids) iff the return value is > 0.
  1583. */
  1584. pid_t
  1585. run_program(prog, args, must_exist, done, arg, wait)
  1586. char *prog;
  1587. char **args;
  1588. int must_exist;
  1589. void (*done) __P((void *));
  1590. void *arg;
  1591. int wait;
  1592. {
  1593. int pid, status;
  1594. struct stat sbuf;
  1595. /*
  1596. * First check if the file exists and is executable.
  1597. * We don't use access() because that would use the
  1598. * real user-id, which might not be root, and the script
  1599. * might be accessible only to root.
  1600. */
  1601. errno = EINVAL;
  1602. if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
  1603. || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
  1604. if (must_exist || errno != ENOENT)
  1605. warn("Can't execute %s: %m", prog);
  1606. return 0;
  1607. }
  1608. pid = safe_fork(fd_devnull, fd_devnull, fd_devnull);
  1609. if (pid == -1) {
  1610. error("Failed to create child process for %s: %m", prog);
  1611. return -1;
  1612. }
  1613. if (pid != 0) {
  1614. if (debug)
  1615. dbglog("Script %s started (pid %d)", prog, pid);
  1616. record_child(pid, prog, done, arg, 0);
  1617. if (wait) {
  1618. while (waitpid(pid, &status, 0) < 0) {
  1619. if (errno == EINTR)
  1620. continue;
  1621. fatal("error waiting for script %s: %m", prog);
  1622. }
  1623. forget_child(pid, status);
  1624. }
  1625. return pid;
  1626. }
  1627. /* Leave the current location */
  1628. (void) setsid(); /* No controlling tty. */
  1629. (void) umask (S_IRWXG|S_IRWXO);
  1630. (void) chdir ("/"); /* no current directory. */
  1631. setuid(0); /* set real UID = root */
  1632. setgid(getegid());
  1633. #ifdef BSD
  1634. /* Force the priority back to zero if pppd is running higher. */
  1635. if (setpriority (PRIO_PROCESS, 0, 0) < 0)
  1636. warn("can't reset priority to 0: %m");
  1637. #endif
  1638. /* run the program */
  1639. update_script_environment();
  1640. execve(prog, args, script_env);
  1641. if (must_exist || errno != ENOENT) {
  1642. /* have to reopen the log, there's nowhere else
  1643. for the message to go. */
  1644. reopen_log();
  1645. syslog(LOG_ERR, "Can't execute %s: %m", prog);
  1646. closelog();
  1647. }
  1648. _exit(99);
  1649. }
  1650. /*
  1651. * record_child - add a child process to the list for reap_kids
  1652. * to use.
  1653. */
  1654. void
  1655. record_child(pid, prog, done, arg, killable)
  1656. int pid;
  1657. char *prog;
  1658. void (*done) __P((void *));
  1659. void *arg;
  1660. int killable;
  1661. {
  1662. struct subprocess *chp;
  1663. ++n_children;
  1664. chp = (struct subprocess *) malloc(sizeof(struct subprocess));
  1665. if (chp == NULL) {
  1666. warn("losing track of %s process", prog);
  1667. } else {
  1668. chp->pid = pid;
  1669. chp->prog = prog;
  1670. chp->done = done;
  1671. chp->arg = arg;
  1672. chp->next = children;
  1673. chp->killable = killable;
  1674. children = chp;
  1675. }
  1676. }
  1677. /*
  1678. * childwait_end - we got fed up waiting for the child processes to
  1679. * exit, send them all a SIGTERM.
  1680. */
  1681. static void
  1682. childwait_end(arg)
  1683. void *arg;
  1684. {
  1685. struct subprocess *chp;
  1686. for (chp = children; chp != NULL; chp = chp->next) {
  1687. if (debug)
  1688. dbglog("sending SIGTERM to process %d", chp->pid);
  1689. kill(chp->pid, SIGTERM);
  1690. }
  1691. childwait_done = 1;
  1692. }
  1693. /*
  1694. * forget_child - clean up after a dead child
  1695. */
  1696. static void
  1697. forget_child(pid, status)
  1698. int pid, status;
  1699. {
  1700. struct subprocess *chp, **prevp;
  1701. for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
  1702. if (chp->pid == pid) {
  1703. --n_children;
  1704. *prevp = chp->next;
  1705. break;
  1706. }
  1707. }
  1708. if (WIFSIGNALED(status)) {
  1709. warn("Child process %s (pid %d) terminated with signal %d",
  1710. (chp? chp->prog: "??"), pid, WTERMSIG(status));
  1711. } else if (debug)
  1712. dbglog("Script %s finished (pid %d), status = 0x%x",
  1713. (chp? chp->prog: "??"), pid,
  1714. WIFEXITED(status) ? WEXITSTATUS(status) : status);
  1715. if (chp && chp->done)
  1716. (*chp->done)(chp->arg);
  1717. if (chp)
  1718. free(chp);
  1719. }
  1720. /*
  1721. * reap_kids - get status from any dead child processes,
  1722. * and log a message for abnormal terminations.
  1723. */
  1724. static int
  1725. reap_kids()
  1726. {
  1727. int pid, status;
  1728. if (n_children == 0)
  1729. return 0;
  1730. while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
  1731. forget_child(pid, status);
  1732. }
  1733. if (pid == -1) {
  1734. if (errno == ECHILD)
  1735. return -1;
  1736. if (errno != EINTR)
  1737. error("Error waiting for child process: %m");
  1738. }
  1739. return 0;
  1740. }
  1741. /*
  1742. * add_notifier - add a new function to be called when something happens.
  1743. */
  1744. void
  1745. add_notifier(notif, func, arg)
  1746. struct notifier **notif;
  1747. notify_func func;
  1748. void *arg;
  1749. {
  1750. struct notifier *np;
  1751. np = malloc(sizeof(struct notifier));
  1752. if (np == 0)
  1753. novm("notifier struct");
  1754. np->next = *notif;
  1755. np->func = func;
  1756. np->arg = arg;
  1757. *notif = np;
  1758. }
  1759. /*
  1760. * remove_notifier - remove a function from the list of things to
  1761. * be called when something happens.
  1762. */
  1763. void
  1764. remove_notifier(notif, func, arg)
  1765. struct notifier **notif;
  1766. notify_func func;
  1767. void *arg;
  1768. {
  1769. struct notifier *np;
  1770. for (; (np = *notif) != 0; notif = &np->next) {
  1771. if (np->func == func && np->arg == arg) {
  1772. *notif = np->next;
  1773. free(np);
  1774. break;
  1775. }
  1776. }
  1777. }
  1778. /*
  1779. * notify - call a set of functions registered with add_notifier.
  1780. */
  1781. void
  1782. notify(notif, val)
  1783. struct notifier *notif;
  1784. int val;
  1785. {
  1786. struct notifier *np;
  1787. while ((np = notif) != 0) {
  1788. notif = np->next;
  1789. (*np->func)(np->arg, val);
  1790. }
  1791. }
  1792. /*
  1793. * novm - log an error message saying we ran out of memory, and die.
  1794. */
  1795. void
  1796. novm(msg)
  1797. char *msg;
  1798. {
  1799. fatal("Virtual memory exhausted allocating %s\n", msg);
  1800. }
  1801. /*
  1802. * script_setenv - set an environment variable value to be used
  1803. * for scripts that we run (e.g. ip-up, auth-up, etc.)
  1804. */
  1805. void
  1806. script_setenv(var, value, iskey)
  1807. char *var, *value;
  1808. int iskey;
  1809. {
  1810. size_t varl = strlen(var);
  1811. size_t vl = varl + strlen(value) + 2;
  1812. int i;
  1813. char *p, *newstring;
  1814. newstring = (char *) malloc(vl+1);
  1815. if (newstring == 0)
  1816. return;
  1817. *newstring++ = iskey;
  1818. slprintf(newstring, vl, "%s=%s", var, value);
  1819. /* check if this variable is already set */
  1820. if (script_env != 0) {
  1821. for (i = 0; (p = script_env[i]) != 0; ++i) {
  1822. if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
  1823. #ifdef USE_TDB
  1824. if (p[-1] && pppdb != NULL)
  1825. delete_db_key(p);
  1826. #endif
  1827. free(p-1);
  1828. script_env[i] = newstring;
  1829. #ifdef USE_TDB
  1830. if (pppdb != NULL) {
  1831. if (iskey)
  1832. add_db_key(newstring);
  1833. update_db_entry();
  1834. }
  1835. #endif
  1836. return;
  1837. }
  1838. }
  1839. } else {
  1840. /* no space allocated for script env. ptrs. yet */
  1841. i = 0;
  1842. script_env = malloc(16 * sizeof(char *));
  1843. if (script_env == 0) {
  1844. free(newstring - 1);
  1845. return;
  1846. }
  1847. s_env_nalloc = 16;
  1848. }
  1849. if (!add_script_env(i, newstring))
  1850. return;
  1851. #ifdef USE_TDB
  1852. if (pppdb != NULL) {
  1853. if (iskey)
  1854. add_db_key(newstring);
  1855. update_db_entry();
  1856. }
  1857. #endif
  1858. }
  1859. /*
  1860. * script_unsetenv - remove a variable from the environment
  1861. * for scripts.
  1862. */
  1863. void
  1864. script_unsetenv(var)
  1865. char *var;
  1866. {
  1867. int vl = strlen(var);
  1868. int i;
  1869. char *p;
  1870. if (script_env == 0)
  1871. return;
  1872. for (i = 0; (p = script_env[i]) != 0; ++i) {
  1873. if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
  1874. #ifdef USE_TDB
  1875. if (p[-1] && pppdb != NULL)
  1876. delete_db_key(p);
  1877. #endif
  1878. remove_script_env(i);
  1879. break;
  1880. }
  1881. }
  1882. #ifdef USE_TDB
  1883. if (pppdb != NULL)
  1884. update_db_entry();
  1885. #endif
  1886. }
  1887. /*
  1888. * Any arbitrary string used as a key for locking the database.
  1889. * It doesn't matter what it is as long as all pppds use the same string.
  1890. */
  1891. #define PPPD_LOCK_KEY "pppd lock"
  1892. /*
  1893. * lock_db - get an exclusive lock on the TDB database.
  1894. * Used to ensure atomicity of various lookup/modify operations.
  1895. */
  1896. void lock_db()
  1897. {
  1898. #ifdef USE_TDB
  1899. TDB_DATA key;
  1900. key.dptr = PPPD_LOCK_KEY;
  1901. key.dsize = strlen(key.dptr);
  1902. tdb_chainlock(pppdb, key);
  1903. #endif
  1904. }
  1905. /*
  1906. * unlock_db - remove the exclusive lock obtained by lock_db.
  1907. */
  1908. void unlock_db()
  1909. {
  1910. #ifdef USE_TDB
  1911. TDB_DATA key;
  1912. key.dptr = PPPD_LOCK_KEY;
  1913. key.dsize = strlen(key.dptr);
  1914. tdb_chainunlock(pppdb, key);
  1915. #endif
  1916. }
  1917. #ifdef USE_TDB
  1918. /*
  1919. * update_db_entry - update our entry in the database.
  1920. */
  1921. static void
  1922. update_db_entry()
  1923. {
  1924. TDB_DATA key, dbuf;
  1925. int vlen, i;
  1926. char *p, *q, *vbuf;
  1927. if (script_env == NULL)
  1928. return;
  1929. vlen = 0;
  1930. for (i = 0; (p = script_env[i]) != 0; ++i)
  1931. vlen += strlen(p) + 1;
  1932. vbuf = malloc(vlen + 1);
  1933. if (vbuf == 0)
  1934. novm("database entry");
  1935. q = vbuf;
  1936. for (i = 0; (p = script_env[i]) != 0; ++i)
  1937. q += slprintf(q, vbuf + vlen - q, "%s;", p);
  1938. key.dptr = db_key;
  1939. key.dsize = strlen(db_key);
  1940. dbuf.dptr = vbuf;
  1941. dbuf.dsize = vlen;
  1942. if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
  1943. error("tdb_store failed: %s", tdb_errorstr(pppdb));
  1944. if (vbuf)
  1945. free(vbuf);
  1946. }
  1947. /*
  1948. * add_db_key - add a key that we can use to look up our database entry.
  1949. */
  1950. static void
  1951. add_db_key(str)
  1952. const char *str;
  1953. {
  1954. TDB_DATA key, dbuf;
  1955. key.dptr = (char *) str;
  1956. key.dsize = strlen(str);
  1957. dbuf.dptr = db_key;
  1958. dbuf.dsize = strlen(db_key);
  1959. if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
  1960. error("tdb_store key failed: %s", tdb_errorstr(pppdb));
  1961. }
  1962. /*
  1963. * delete_db_key - delete a key for looking up our database entry.
  1964. */
  1965. static void
  1966. delete_db_key(str)
  1967. const char *str;
  1968. {
  1969. TDB_DATA key;
  1970. key.dptr = (char *) str;
  1971. key.dsize = strlen(str);
  1972. tdb_delete(pppdb, key);
  1973. }
  1974. /*
  1975. * cleanup_db - delete all the entries we put in the database.
  1976. */
  1977. static void
  1978. cleanup_db()
  1979. {
  1980. TDB_DATA key;
  1981. int i;
  1982. char *p;
  1983. key.dptr = db_key;
  1984. key.dsize = strlen(db_key);
  1985. tdb_delete(pppdb, key);
  1986. for (i = 0; (p = script_env[i]) != 0; ++i)
  1987. if (p[-1])
  1988. delete_db_key(p);
  1989. }
  1990. #endif /* USE_TDB */