ath79: do not build TP-Link tiny images by default
[oweals/openwrt.git] / package / network / services / ppp / patches / 500-add-pptp-plugin.patch
1 --- a/configure
2 +++ b/configure
3 @@ -195,7 +195,7 @@ if [ -d "$ksrc" ]; then
4      mkmkf $ksrc/Makedefs$compiletype Makedefs.com
5      for dir in pppd pppstats chat pppdump pppd/plugins pppd/plugins/rp-pppoe \
6                pppd/plugins/radius pppd/plugins/pppoatm \
7 -              pppd/plugins/pppol2tp; do
8 +              pppd/plugins/pppol2tp pppd/plugins/pptp ; do
9         mkmkf $dir/Makefile.$makext $dir/Makefile
10      done
11      if [ -f $ksrc/Makefile.$makext$archvariant ]; then
12 --- a/pppd/plugins/Makefile.linux
13 +++ b/pppd/plugins/Makefile.linux
14 @@ -9,7 +9,7 @@ BINDIR = $(DESTDIR)/sbin
15  MANDIR = $(DESTDIR)/share/man/man8
16  LIBDIR = $(DESTDIR)/lib/pppd/$(VERSION)
17  
18 -SUBDIRS := rp-pppoe pppoatm pppol2tp
19 +SUBDIRS := rp-pppoe pppoatm pppol2tp pptp
20  # Uncomment the next line to include the radius authentication plugin
21  SUBDIRS += radius
22  PLUGINS := minconn.so passprompt.so passwordfd.so winbind.so
23 --- /dev/null
24 +++ b/pppd/plugins/pptp/Makefile.linux
25 @@ -0,0 +1,31 @@
26 +#
27 +# This program may be distributed according to the terms of the GNU
28 +# General Public License, version 2 or (at your option) any later version.
29 +#
30 +# $Id: Makefile.linux,v 1.9 2012/05/04 21:48:00 dgolle Exp $
31 +#***********************************************************************
32 +
33 +DESTDIR = $(INSTROOT)@DESTDIR@
34 +LIBDIR = $(DESTDIR)/lib/pppd/$(PPPDVERSION)
35 +
36 +PPPDVERSION = $(shell awk -F '"' '/VERSION/ { print $$2; }' ../../patchlevel.h)
37 +
38 +INSTALL        = install
39 +
40 +COPTS=-O2 -g
41 +CFLAGS  = $(COPTS) -I. -I../.. -I../../../include -fPIC -DPPPD_VERSION=\"$(PPPDVERSION)\"
42 +all: pptp.so
43 +
44 +%.o: %.c
45 +       $(CC) $(CFLAGS) -c -o $@ $<
46 +
47 +pptp.so: dirutil.o orckit_quirks.o pptp.o pptp_callmgr.o pptp_ctrl.o pptp_quirks.o util.o vector.o
48 +       $(CC) -o pptp.so -shared dirutil.o orckit_quirks.o pptp.o pptp_callmgr.o pptp_ctrl.o pptp_quirks.o util.o vector.o
49 +
50 +install: all
51 +       $(INSTALL) -d -m 755 $(LIBDIR)
52 +       $(INSTALL) -c -m 4550 pptp.so $(LIBDIR)
53 +
54 +clean:
55 +       rm -f *.o *.so
56 +
57 --- /dev/null
58 +++ b/pppd/plugins/pptp/dirutil.c
59 @@ -0,0 +1,68 @@
60 +/* dirutil.c ... directory utilities.
61 + *               C. Scott Ananian <cananian@alumni.princeton.edu>
62 + *
63 + * $Id: dirutil.c,v 1.2 2003/06/17 17:25:47 reink Exp $
64 + */
65 +
66 +#include <sys/stat.h>
67 +#include <sys/types.h>
68 +#include <unistd.h>
69 +#include <string.h>
70 +#include <stdlib.h>
71 +#include "dirutil.h"
72 +
73 +/* Returned malloc'ed string representing basename */
74 +char *basenamex(char *pathname)
75 +{
76 +    char *dup = strdup(pathname);
77 +    char *ptr = strrchr(stripslash(dup), '/');
78 +    if (ptr == NULL) return dup;
79 +    ptr = strdup(ptr+1);
80 +    free(dup);
81 +    return ptr;
82 +}
83 +
84 +/* Return malloc'ed string representing directory name (no trailing slash) */
85 +char *dirnamex(char *pathname)
86 +{
87 +    char *dup = strdup(pathname);
88 +    char *ptr = strrchr(stripslash(dup), '/');
89 +    if (ptr == NULL) { free(dup); return strdup("."); }
90 +    if (ptr == dup && dup[0] == '/') ptr++;
91 +    *ptr = '\0';
92 +    return dup;
93 +}
94 +
95 +/* In-place modify a string to remove trailing slashes.  Returns arg.
96 + * stripslash("/") returns "/";
97 + */
98 +char *stripslash(char *pathname) {
99 +    int len = strlen(pathname);
100 +    while (len > 1 && pathname[len - 1] == '/')
101 +        pathname[--len] = '\0';
102 +    return pathname;
103 +}
104 +
105 +/* ensure dirname exists, creating it if necessary. */
106 +int make_valid_path(char *dir, mode_t mode)
107 +{
108 +    struct stat st;
109 +    char *tmp = NULL, *path = stripslash(strdup(dir));
110 +    int retval;
111 +    if (stat(path, &st) == 0) { /* file exists */
112 +        if (S_ISDIR(st.st_mode)) { retval = 1; goto end; }
113 +        else { retval = 0; goto end; } /* not a directory.  Oops. */
114 +    }
115 +    /* Directory doesn't exist.  Let's make it. */
116 +    /*   Make parent first. */
117 +    if (!make_valid_path(tmp = dirnamex(path), mode)) { retval = 0; goto end; }
118 +    /*   Now make this 'un. */
119 +    if (mkdir(path, mode) < 0) { retval = 0; goto end; }
120 +    /* Success. */
121 +    retval = 1;
122 +
123 +end:
124 +    if (tmp != NULL) free(tmp);
125 +    if (path != NULL) free(path);
126 +    return retval;
127 +}
128 --- /dev/null
129 +++ b/pppd/plugins/pptp/dirutil.h
130 @@ -0,0 +1,14 @@
131 +/* dirutil.h ... directory utilities.
132 + *               C. Scott Ananian <cananian@alumni.princeton.edu>
133 + *
134 + * $Id: dirutil.h,v 1.1.1.1 2000/12/23 08:19:51 scott Exp $
135 + */
136 +
137 +/* Returned malloc'ed string representing basename */
138 +char *basenamex(char *pathname);
139 +/* Return malloc'ed string representing directory name (no trailing slash) */
140 +char *dirnamex(char *pathname);
141 +/* In-place modify a string to remove trailing slashes.  Returns arg. */
142 +char *stripslash(char *pathname);
143 +/* ensure dirname exists, creating it if necessary. */
144 +int make_valid_path(char *dirname, mode_t mode);
145 --- /dev/null
146 +++ b/pppd/plugins/pptp/orckit_quirks.c
147 @@ -0,0 +1,86 @@
148 +/* orckit_quirks.c ...... fix quirks in orckit adsl modems
149 + *                        mulix <mulix@actcom.co.il>
150 + *
151 + * $Id: orckit_quirks.c,v 1.3 2002/03/01 01:23:36 quozl Exp $
152 + */
153 +
154 +#include <string.h>
155 +#include <sys/types.h>
156 +#include <netinet/in.h>
157 +#include "pptp_msg.h"
158 +#include "pptp_options.h"
159 +#include "pptp_ctrl.h"
160 +#include "util.h"
161 +
162 +
163 +
164 +/* return 0 on success, non zero otherwise */
165 +int
166 +orckit_atur3_build_hook(struct pptp_out_call_rqst* packet)
167 +{
168 +    unsigned int name_length = 10;
169 +
170 +    struct pptp_out_call_rqst fixed_packet = {
171 +       PPTP_HEADER_CTRL(PPTP_OUT_CALL_RQST),
172 +       0, /* hton16(call->callid) */
173 +       0, /* hton16(call->sernum) */
174 +       hton32(PPTP_BPS_MIN), hton32(PPTP_BPS_MAX),
175 +       hton32(PPTP_BEARER_DIGITAL), hton32(PPTP_FRAME_ANY),
176 +       hton16(PPTP_WINDOW), 0, hton16(name_length), 0,
177 +       {'R','E','L','A','Y','_','P','P','P','1',0}, {0}
178 +    };
179 +
180 +    if (!packet)
181 +       return -1;
182 +
183 +    memcpy(packet, &fixed_packet, sizeof(*packet));
184 +
185 +    return 0;
186 +}
187 +
188 +/* return 0 on success, non zero otherwise */
189 +int
190 +orckit_atur3_set_link_hook(struct pptp_set_link_info* packet,
191 +                          int peer_call_id)
192 +{
193 +    struct pptp_set_link_info fixed_packet = {
194 +       PPTP_HEADER_CTRL(PPTP_SET_LINK_INFO),
195 +       hton16(peer_call_id),
196 +       0,
197 +       0xffffffff,
198 +       0xffffffff};
199 +
200 +    if (!packet)
201 +       return -1;
202 +
203 +    memcpy(packet, &fixed_packet, sizeof(*packet));
204 +    return 0;
205 +}
206 +
207 +/* return 0 on success, non 0 otherwise */
208 +int
209 +orckit_atur3_start_ctrl_conn_hook(struct pptp_start_ctrl_conn* packet)
210 +{
211 +    struct pptp_start_ctrl_conn fixed_packet = {
212 +       {0}, /* we'll set the header later */
213 +       hton16(PPTP_VERSION), 0, 0,
214 +       hton32(PPTP_FRAME_ASYNC), hton32(PPTP_BEARER_ANALOG),
215 +       hton16(0) /* max channels */,
216 +       hton16(0x6021),
217 +       {'R','E','L','A','Y','_','P','P','P','1',0}, /* hostname */
218 +       {'M','S',' ','W','i','n',' ','N','T',0} /* vendor */
219 +    };
220 +
221 +    if (!packet)
222 +       return -1;
223 +
224 +    /* grab the header from the original packet, since we dont
225 +       know if this is a request or a reply */
226 +    memcpy(&fixed_packet.header, &packet->header, sizeof(struct pptp_header));
227 +
228 +    /* and now overwrite the full packet, effectively preserving the header */
229 +    memcpy(packet, &fixed_packet, sizeof(*packet));
230 +    return 0;
231 +}
232 +
233 +
234 --- /dev/null
235 +++ b/pppd/plugins/pptp/orckit_quirks.h
236 @@ -0,0 +1,27 @@
237 +/* orckit_quirks.h ...... fix quirks in orckit adsl modems
238 + *                        mulix <mulix@actcom.co.il>
239 + *
240 + * $Id: orckit_quirks.h,v 1.2 2001/11/23 03:42:51 quozl Exp $
241 + */
242 +
243 +#ifndef INC_ORCKIT_QUIRKS_H_
244 +#define INC_ORCKIT_QUIRKS_H_
245 +
246 +#include "pptp_options.h"
247 +#include "pptp_ctrl.h"
248 +#include "pptp_msg.h"
249 +
250 +/* return 0 on success, non zero otherwise */
251 +int
252 +orckit_atur3_build_hook(struct pptp_out_call_rqst* packt);
253 +
254 +/* return 0 on success, non zero otherwise */
255 +int
256 +orckit_atur3_set_link_hook(struct pptp_set_link_info* packet,
257 +                          int peer_call_id);
258 +
259 +/* return 0 on success, non zero otherwise */
260 +int
261 +orckit_atur3_start_ctrl_conn_hook(struct pptp_start_ctrl_conn* packet);
262 +
263 +#endif /* INC_ORCKIT_QUIRKS_H_ */
264 --- /dev/null
265 +++ b/pppd/plugins/pptp/pppd-pptp.8
266 @@ -0,0 +1,68 @@
267 +.\" manual page [] for PPTP plugin for pppd 2.4
268 +.\" $Id: pppd-pptp.8,v 1.0 2007/10/17 13:27:17 kad Exp $
269 +.\" SH section heading
270 +.\" SS subsection heading
271 +.\" LP paragraph
272 +.\" IP indented paragraph
273 +.\" TP hanging label
274 +.TH PPPD-PPTP 8
275 +.SH NAME
276 +pptp.so \- PPTP VPN plugin for
277 +.BR pppd (8)
278 +.SH SYNOPSIS
279 +.B pppd
280 +[
281 +.I options
282 +]
283 +plugin pptp.so
284 +.SH DESCRIPTION
285 +.LP
286 +The PPTP plugin for pppd performs interaction with pptp kernel module
287 +and has built-in call manager (client part of PPTP).
288 +It pasees necessary paremeters from \fIoptions\fR into kernel module 
289 +to configure ppp-pptp channel. If it runs in client mode, then additionally 
290 +call manager starts up. PPTPD daemon automaticaly invokes this plugin
291 +in server mode and passes necessary options, so additional configuration
292 +is not needed.
293 +
294 +.SH OPTIONS for client mode
295 +The PPTP plugin introduces one additional pppd option:
296 +.TP
297 +.BI "pptp_server " server " (required)"
298 +Specifies ip address or hostname of pptp server.
299 +.TP
300 +.BI "pptp_window " packets " (optional)"
301 +The amount of sliding window size. 
302 +Set to 0 to turn off sliding window.
303 +    to 3-10 for low speed connections.
304 +    to >10 for hi speed connections.
305 +Default is 50
306 +.TP
307 +.BI "pptp_phone " phone " (optional)"
308 +The phone string that sended to pptp server.
309 +.SH USAGE
310 +Sample configuration file:
311 +.nf
312 +plugin "pptp.so"
313 +pptp_server 192.168.0.1
314 +pptp_window 100
315 +name myname
316 +remotename pptp
317 +noauth
318 +refuse-eap
319 +refuse-chap
320 +refuse-mschap
321 +nobsdcomp
322 +nodeflate
323 +novj
324 +novjccomp
325 +require-mppe-128
326 +lcp-echo-interval 20
327 +lcp-echo-failure  3
328 +.fi
329 +
330 +.SH SEE ALSO
331 +.BR pppd (8) "  " pptpd (8) "  " pptpd.conf (5)
332 +
333 +.SH AUTHOR
334 +xeb xeb@mail.ru
335 --- /dev/null
336 +++ b/pppd/plugins/pptp/pptp.c
337 @@ -0,0 +1,323 @@
338 +/***************************************************************************
339 + *   Copyright (C) 2006 by Kozlov D. <xeb@mail.ru>                         *
340 + *   some cleanup done (C) 2012 by Daniel Golle <dgolle@allnet.de>         *
341 + *                                                                         *
342 + *   This program is free software; you can redistribute it and/or modify  *
343 + *   it under the terms of the GNU General Public License as published by  *
344 + *   the Free Software Foundation; either version 2 of the License, or     *
345 + *   (at your option) any later version.                                   *
346 + *                                                                         *
347 + *   This program is distributed in the hope that it will be useful,       *
348 + *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
349 + *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
350 + *   GNU General Public License for more details.                          *
351 + *                                                                         *
352 + *   You should have received a copy of the GNU General Public License     *
353 + *   along with this program; if not, write to the                         *
354 + *   Free Software Foundation, Inc.,                                       *
355 + *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
356 + ***************************************************************************/
357 +
358 +#define PPTP_VERSION "1.00"
359 +
360 +#ifdef HAVE_CONFIG_H
361 +#include <config.h>
362 +#endif
363 +
364 +#include <netinet/in.h>
365 +#include <arpa/inet.h>
366 +#include <sys/un.h>
367 +#include <netdb.h>
368 +#include <stdio.h>
369 +#include <string.h>
370 +#include <stdlib.h>
371 +#include <syslog.h>
372 +#include <unistd.h>
373 +#include <signal.h>
374 +#include <errno.h>
375 +#include <fcntl.h>
376 +#include <sys/wait.h>
377 +#include <sys/ioctl.h>
378 +
379 +#include "pppd.h"
380 +#include "fsm.h"
381 +#include "lcp.h"
382 +#include "ipcp.h"
383 +#include "ccp.h"
384 +#include "pathnames.h"
385 +
386 +#include "pptp_callmgr.h"
387 +#include <net/if.h>
388 +#include <net/ethernet.h>
389 +#include <linux/if_pppox.h>
390 +
391 +#include <stdio.h>
392 +#include <stdlib.h>
393 +
394 +
395 +
396 +extern char** environ;
397 +
398 +char pppd_version[] = PPPD_VERSION;
399 +extern int new_style_driver;
400 +
401 +
402 +char *pptp_server = NULL;
403 +char *pptp_client = NULL;
404 +char *pptp_phone = NULL;
405 +int pptp_window=50;
406 +int pptp_sock=-1;
407 +struct in_addr localbind = { INADDR_NONE };
408 +
409 +static int callmgr_sock;
410 +static int pptp_fd;
411 +int call_ID;
412 +
413 +static int open_callmgr(int call_id,struct in_addr inetaddr, char *phonenr,int window);
414 +static void launch_callmgr(int call_is,struct in_addr inetaddr, char *phonenr,int window);
415 +static int get_call_id(int sock, pid_t gre, pid_t pppd, u_int16_t *peer_call_id);
416 +
417 +static option_t Options[] =
418 +{
419 +    { "pptp_server", o_string, &pptp_server,
420 +      "PPTP Server" },
421 +    { "pptp_client", o_string, &pptp_client,
422 +      "PPTP Client" },
423 +    { "pptp_sock",o_int, &pptp_sock,
424 +      "PPTP socket" },
425 +    { "pptp_phone", o_string, &pptp_phone,
426 +      "PPTP Phone number" },
427 +    { "pptp_window",o_int, &pptp_window,
428 +      "PPTP window" },
429 +    { NULL }
430 +};
431 +
432 +static int pptp_connect(void);
433 +static void pptp_disconnect(void);
434 +
435 +struct channel pptp_channel = {
436 +    options: Options,
437 +    check_options: NULL,
438 +    connect: &pptp_connect,
439 +    disconnect: &pptp_disconnect,
440 +    establish_ppp: &generic_establish_ppp,
441 +    disestablish_ppp: &generic_disestablish_ppp,
442 +    close: NULL,
443 +    cleanup: NULL
444 +};
445 +
446 +static int pptp_start_server(void)
447 +{
448 +       pptp_fd=pptp_sock;
449 +       sprintf(ppp_devnam,"pptp (%s)",pptp_client);
450 +
451 +       return pptp_fd;
452 +}
453 +static int pptp_start_client(void)
454 +{
455 +       socklen_t len;
456 +       struct sockaddr_pppox src_addr,dst_addr;
457 +       struct hostent *hostinfo;
458 +
459 +       hostinfo=gethostbyname(pptp_server);
460 +  if (!hostinfo)
461 +       {
462 +               error("PPTP: Unknown host %s\n", pptp_server);
463 +               return -1;
464 +       }
465 +       dst_addr.sa_addr.pptp.sin_addr=*(struct in_addr*)hostinfo->h_addr;
466 +       {
467 +               int sock;
468 +               struct sockaddr_in addr;
469 +               len=sizeof(addr);
470 +               addr.sin_addr=dst_addr.sa_addr.pptp.sin_addr;
471 +               addr.sin_family=AF_INET;
472 +               addr.sin_port=htons(1700);
473 +               sock=socket(AF_INET,SOCK_DGRAM,0);
474 +               if (connect(sock,(struct sockaddr*)&addr,sizeof(addr)))
475 +               {
476 +                       close(sock);
477 +                       error("PPTP: connect failed (%s)\n",strerror(errno));
478 +                       return -1;
479 +               }
480 +               getsockname(sock,(struct sockaddr*)&addr,&len);
481 +               src_addr.sa_addr.pptp.sin_addr=addr.sin_addr;
482 +               close(sock);
483 +       }
484 +
485 +       src_addr.sa_family=AF_PPPOX;
486 +       src_addr.sa_protocol=PX_PROTO_PPTP;
487 +       src_addr.sa_addr.pptp.call_id=0;
488 +
489 +       dst_addr.sa_family=AF_PPPOX;
490 +       dst_addr.sa_protocol=PX_PROTO_PPTP;
491 +       dst_addr.sa_addr.pptp.call_id=0;
492 +
493 +       pptp_fd=socket(AF_PPPOX,SOCK_STREAM,PX_PROTO_PPTP);
494 +       if (pptp_fd<0)
495 +       {
496 +               error("PPTP: failed to create PPTP socket (%s)\n",strerror(errno));
497 +               return -1;
498 +       }
499 +       if (bind(pptp_fd,(struct sockaddr*)&src_addr,sizeof(src_addr)))
500 +       {
501 +               close(pptp_fd);
502 +               error("PPTP: failed to bind PPTP socket (%s)\n",strerror(errno));
503 +               return -1;
504 +       }
505 +       len=sizeof(src_addr);
506 +       getsockname(pptp_fd,(struct sockaddr*)&src_addr,&len);
507 +       call_ID=src_addr.sa_addr.pptp.call_id;
508 +
509 +  do {
510 +        /*
511 +         * Open connection to call manager (Launch call manager if necessary.)
512 +         */
513 +        callmgr_sock = open_callmgr(src_addr.sa_addr.pptp.call_id,dst_addr.sa_addr.pptp.sin_addr, pptp_phone, pptp_window);
514 +       if (callmgr_sock<0)
515 +       {
516 +               close(pptp_fd);
517 +               return -1;
518 +        }
519 +        /* Exchange PIDs, get call ID */
520 +    } while (get_call_id(callmgr_sock, getpid(), getpid(), &dst_addr.sa_addr.pptp.call_id) < 0);
521 +
522 +       if (connect(pptp_fd,(struct sockaddr*)&dst_addr,sizeof(dst_addr)))
523 +       {
524 +               close(callmgr_sock);
525 +               close(pptp_fd);
526 +               error("PPTP: failed to connect PPTP socket (%s)\n",strerror(errno));
527 +               return -1;
528 +       }
529 +
530 +       sprintf(ppp_devnam,"pptp (%s)",pptp_server);
531 +
532 +       return pptp_fd;
533 +}
534 +static int pptp_connect(void)
535 +{
536 +       if ((!pptp_server && !pptp_client) || (pptp_server && pptp_client))
537 +       {
538 +               fatal("PPTP: unknown mode (you must specify pptp_server or pptp_client option)");
539 +               return -1;
540 +       }
541 +
542 +       if (pptp_server) return pptp_start_client();
543 +       return pptp_start_server();
544 +}
545 +
546 +static void pptp_disconnect(void)
547 +{
548 +       if (pptp_server) close(callmgr_sock);
549 +       close(pptp_fd);
550 +}
551 +
552 +static int open_callmgr(int call_id,struct in_addr inetaddr, char *phonenr,int window)
553 +{
554 +    /* Try to open unix domain socket to call manager. */
555 +    struct sockaddr_un where;
556 +    const int NUM_TRIES = 3;
557 +    int i, fd;
558 +    pid_t pid;
559 +    int status;
560 +    /* Open socket */
561 +    if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
562 +    {
563 +        fatal("Could not create unix domain socket: %s", strerror(errno));
564 +    }
565 +    /* Make address */
566 +    callmgr_name_unixsock(&where, inetaddr, localbind);
567 +    for (i = 0; i < NUM_TRIES; i++)
568 +    {
569 +        if (connect(fd, (struct sockaddr *) &where, sizeof(where)) < 0)
570 +        {
571 +            /* couldn't connect.  We'll have to launch this guy. */
572 +
573 +            unlink (where.sun_path);
574 +
575 +            /* fork and launch call manager process */
576 +            switch (pid = fork())
577 +            {
578 +                case -1: /* failure */
579 +                    fatal("fork() to launch call manager failed.");
580 +                case 0: /* child */
581 +                {
582 +                    /* close the pty and gre in the call manager */
583 +                    close(fd);
584 +                    close(pptp_fd);
585 +                    launch_callmgr(call_id,inetaddr,phonenr,window);
586 +                }
587 +                default: /* parent */
588 +                    waitpid(pid, &status, 0);
589 +                    if (status!= 0)
590 +                   {
591 +                       close(fd);
592 +                       error("Call manager exited with error %d", status);
593 +                       return -1;
594 +                   }
595 +                    break;
596 +            }
597 +            sleep(1);
598 +        }
599 +        else return fd;
600 +    }
601 +    close(fd);
602 +    error("Could not launch call manager after %d tries.", i);
603 +    return -1;   /* make gcc happy */
604 +}
605 +
606 +/*** call the call manager main ***********************************************/
607 +static void launch_callmgr(int call_id,struct in_addr inetaddr, char *phonenr,int window)
608 +{
609 +    dbglog("pptp: call manager for %s\n", inet_ntoa(inetaddr));
610 +    dbglog("window size:\t%d\n",window);
611 +    if (phonenr) dbglog("phone number:\t'%s'\n",phonenr);
612 +    dbglog("call id:\t%d\n",call_id);
613 +    exit(callmgr_main(inetaddr, phonenr, window, call_id));
614 +}
615 +
616 +/*** exchange data with the call manager  *************************************/
617 +/* XXX need better error checking XXX */
618 +static int get_call_id(int sock, pid_t gre, pid_t pppd,
619 +               u_int16_t *peer_call_id)
620 +{
621 +    u_int16_t m_call_id, m_peer_call_id;
622 +    /* write pid's to socket */
623 +    /* don't bother with network byte order, because pid's are meaningless
624 +     * outside the local host.
625 +     */
626 +    int rc;
627 +    rc = write(sock, &gre, sizeof(gre));
628 +    if (rc != sizeof(gre))
629 +        return -1;
630 +    rc = write(sock, &pppd, sizeof(pppd));
631 +    if (rc != sizeof(pppd))
632 +        return -1;
633 +    rc = read(sock,  &m_call_id, sizeof(m_call_id));
634 +    if (rc != sizeof(m_call_id))
635 +        return -1;
636 +    rc = read(sock,  &m_peer_call_id, sizeof(m_peer_call_id));
637 +    if (rc != sizeof(m_peer_call_id))
638 +        return -1;
639 +    /*
640 +     * XXX FIXME ... DO ERROR CHECKING & TIME-OUTS XXX
641 +     * (Rhialto: I am assuming for now that timeouts are not relevant
642 +     * here, because the read and write calls would return -1 (fail) when
643 +     * the peer goes away during the process. We know it is (or was)
644 +     * running because the connect() call succeeded.)
645 +     * (James: on the other hand, if the route to the peer goes away, we
646 +     * wouldn't get told by read() or write() for quite some time.)
647 +     */
648 +    *peer_call_id = m_peer_call_id;
649 +    return 0;
650 +}
651 +
652 +void plugin_init(void)
653 +{
654 +    add_options(Options);
655 +
656 +    info("PPTP plugin version %s", PPTP_VERSION);
657 +
658 +    the_channel = &pptp_channel;
659 +    modem = 0;
660 +}
661 --- /dev/null
662 +++ b/pppd/plugins/pptp/pptp_callmgr.c
663 @@ -0,0 +1,381 @@
664 +/* pptp_callmgr.c ... Call manager for PPTP connections.
665 + *                    Handles TCP port 1723 protocol.
666 + *                    C. Scott Ananian <cananian@alumni.princeton.edu>
667 + *
668 + * $Id: pptp_callmgr.c,v 1.20 2005/03/31 07:42:39 quozl Exp $
669 + */
670 +#include <signal.h>
671 +#include <sys/time.h>
672 +#include <sys/types.h>
673 +#include <sys/stat.h>
674 +#include <sys/socket.h>
675 +#include <netinet/in.h>
676 +#include <arpa/inet.h>
677 +#include <sys/un.h>
678 +#include <unistd.h>
679 +#include <stdlib.h>
680 +#include <string.h>
681 +#include <assert.h>
682 +#include <setjmp.h>
683 +#include <stdio.h>
684 +#include <errno.h>
685 +#include "pptp_callmgr.h"
686 +#include "pptp_ctrl.h"
687 +#include "pptp_msg.h"
688 +#include "dirutil.h"
689 +#include "vector.h"
690 +#include "util.h"
691 +#include "pppd.h"
692 +
693 +extern struct in_addr localbind; /* from pptp.c */
694 +extern int call_ID;
695 +
696 +int open_inetsock(struct in_addr inetaddr);
697 +int open_unixsock(struct in_addr inetaddr);
698 +void close_inetsock(int fd, struct in_addr inetaddr);
699 +void close_unixsock(int fd, struct in_addr inetaddr);
700 +
701 +sigjmp_buf callmgr_env;
702 +
703 +void callmgr_sighandler(int sig) {
704 +    /* TODO: according to signal(2), siglongjmp() is unsafe used here */
705 +    siglongjmp (callmgr_env, 1);
706 +}
707 +
708 +void callmgr_do_nothing(int sig) {
709 +    /* do nothing signal handler */
710 +}
711 +
712 +struct local_callinfo {
713 +    int unix_sock;
714 +    pid_t pid[2];
715 +};
716 +
717 +struct local_conninfo {
718 +    VECTOR * call_list;
719 +    fd_set * call_set;
720 +};
721 +
722 +/* Call callback */
723 +void call_callback(PPTP_CONN *conn, PPTP_CALL *call, enum call_state state)
724 +{
725 +    struct local_callinfo *lci;
726 +    struct local_conninfo *conninfo;
727 +    u_int16_t call_id[2];
728 +    switch(state) {
729 +        case CALL_OPEN_DONE:
730 +            /* okey dokey.  This means that the call_id and peer_call_id are
731 +             * now valid, so lets send them on to our friends who requested
732 +             * this call.  */
733 +            lci = pptp_call_closure_get(conn, call); assert(lci != NULL);
734 +            pptp_call_get_ids(conn, call, &call_id[0], &call_id[1]);
735 +            write(lci->unix_sock, &call_id, sizeof(call_id));
736 +            /* Our duty to the fatherland is now complete. */
737 +            break;
738 +        case CALL_OPEN_FAIL:
739 +        case CALL_CLOSE_RQST:
740 +        case CALL_CLOSE_DONE:
741 +            /* don't need to do anything here, except make sure tables
742 +             * are sync'ed */
743 +            dbglog("Closing connection (call state)");
744 +            conninfo = pptp_conn_closure_get(conn);
745 +            lci = pptp_call_closure_get(conn, call);
746 +            assert(lci != NULL && conninfo != NULL);
747 +            if (vector_contains(conninfo->call_list, lci->unix_sock)) {
748 +                vector_remove(conninfo->call_list, lci->unix_sock);
749 +                close(lci->unix_sock);
750 +                FD_CLR(lci->unix_sock, conninfo->call_set);
751 +            }
752 +            break;
753 +        default:
754 +            dbglog("Unhandled call callback state [%d].", (int) state);
755 +            break;
756 +    }
757 +}
758 +
759 +/******************************************************************************
760 + * NOTE ABOUT 'VOLATILE':
761 + * several variables here get a volatile qualifier to silence warnings
762 + * from older (before 3.0) gccs. if the longjmp stuff is removed,
763 + * the volatile qualifiers should be removed as well.
764 + *****************************************************************************/
765 +
766 +/*** Call Manager *************************************************************/
767 +int callmgr_main(struct in_addr inetaddr, char phonenr[], int window, int pcallid)
768 +{
769 +    int inet_sock, unix_sock;
770 +    fd_set call_set;
771 +    PPTP_CONN * conn;
772 +    VECTOR * call_list;
773 +    int max_fd = 0;
774 +    volatile int first = 1;
775 +    int retval;
776 +    int i;
777 +    if (pcallid>0) call_ID=pcallid;
778 +
779 +    /* Step 1: Open sockets. */
780 +    if ((inet_sock = open_inetsock(inetaddr)) < 0)
781 +        fatal("Could not open control connection to %s", inet_ntoa(inetaddr));
782 +    dbglog("control connection");
783 +    if ((unix_sock = open_unixsock(inetaddr)) < 0)
784 +        fatal("Could not open unix socket for %s", inet_ntoa(inetaddr));
785 +    /* Step 1b: FORK and return status to calling process. */
786 +    dbglog("unix_sock");
787 +
788 +    switch (fork()) {
789 +        case 0: /* child. stick around. */
790 +            break;
791 +        case -1: /* failure.  Fatal. */
792 +            fatal("Could not fork.");
793 +        default: /* Parent. Return status to caller. */
794 +            exit(0);
795 +    }
796 +    /* re-open stderr as /dev/null to release it */
797 +    file2fd("/dev/null", "wb", STDERR_FILENO);
798 +    /* Step 1c: Clean up unix socket on TERM */
799 +    if (sigsetjmp(callmgr_env, 1) != 0)
800 +        goto cleanup;
801 +    signal(SIGINT, callmgr_sighandler);
802 +    signal(SIGTERM, callmgr_sighandler);
803 +    signal(SIGPIPE, callmgr_do_nothing);
804 +    signal(SIGUSR1, callmgr_do_nothing); /* signal state change
805 +                                            wake up accept */
806 +    /* Step 2: Open control connection and register callback */
807 +    if ((conn = pptp_conn_open(inet_sock, 1, NULL/* callback */)) == NULL) {
808 +        close(unix_sock); close(inet_sock); fatal("Could not open connection.");
809 +    }
810 +    FD_ZERO(&call_set);
811 +    call_list = vector_create();
812 +    {
813 +        struct local_conninfo *conninfo = malloc(sizeof(*conninfo));
814 +        if (conninfo == NULL) {
815 +            close(unix_sock); close(inet_sock); fatal("No memory.");
816 +        }
817 +        conninfo->call_list = call_list;
818 +        conninfo->call_set  = &call_set;
819 +        pptp_conn_closure_put(conn, conninfo);
820 +    }
821 +    if (sigsetjmp(callmgr_env, 1) != 0) goto shutdown;
822 +    /* Step 3: Get FD_SETs */
823 +    max_fd = unix_sock;
824 +    do {
825 +        int rc;
826 +        fd_set read_set = call_set, write_set;
827 +        FD_ZERO (&write_set);
828 +        if (pptp_conn_established(conn)) {
829 +         FD_SET (unix_sock, &read_set);
830 +         if (unix_sock > max_fd) max_fd = unix_sock;
831 +       }
832 +        pptp_fd_set(conn, &read_set, &write_set, &max_fd);
833 +        for (; max_fd > 0 ; max_fd--) {
834 +            if (FD_ISSET (max_fd, &read_set) ||
835 +                    FD_ISSET (max_fd, &write_set))
836 +                break;
837 +        }
838 +        /* Step 4: Wait on INET or UNIX event */
839 +        if ((rc = select(max_fd + 1, &read_set, &write_set, NULL, NULL)) <0) {
840 +         if (errno == EBADF) break;
841 +         /* a signal or somesuch. */
842 +         continue;
843 +       }
844 +        /* Step 5a: Handle INET events */
845 +        rc = pptp_dispatch(conn, &read_set, &write_set);
846 +       if (rc < 0)
847 +           break;
848 +        /* Step 5b: Handle new connection to UNIX socket */
849 +        if (FD_ISSET(unix_sock, &read_set)) {
850 +            /* New call! */
851 +            struct sockaddr_un from;
852 +            int len = sizeof(from);
853 +            PPTP_CALL * call;
854 +            struct local_callinfo *lci;
855 +            int s;
856 +            /* Accept the socket */
857 +            FD_CLR (unix_sock, &read_set);
858 +            if ((s = accept(unix_sock, (struct sockaddr *) &from, &len)) < 0) {
859 +                warn("Socket not accepted: %s", strerror(errno));
860 +                goto skip_accept;
861 +            }
862 +            /* Allocate memory for local call information structure. */
863 +            if ((lci = malloc(sizeof(*lci))) == NULL) {
864 +                warn("Out of memory."); close(s); goto skip_accept;
865 +            }
866 +            lci->unix_sock = s;
867 +            /* Give the initiator time to write the PIDs while we open
868 +             * the call */
869 +            call = pptp_call_open(conn, call_ID,call_callback, phonenr,window);
870 +            /* Read and store the associated pids */
871 +            read(s, &lci->pid[0], sizeof(lci->pid[0]));
872 +            read(s, &lci->pid[1], sizeof(lci->pid[1]));
873 +            /* associate the local information with the call */
874 +            pptp_call_closure_put(conn, call, (void *) lci);
875 +            /* The rest is done on callback. */
876 +            /* Keep alive; wait for close */
877 +            retval = vector_insert(call_list, s, call); assert(retval);
878 +            if (s > max_fd) max_fd = s;
879 +            FD_SET(s, &call_set);
880 +            first = 0;
881 +        }
882 +skip_accept: /* Step 5c: Handle socket close */
883 +        for (i = 0; i < max_fd + 1; i++)
884 +            if (FD_ISSET(i, &read_set)) {
885 +                /* close it */
886 +                PPTP_CALL * call;
887 +                retval = vector_search(call_list, i, &call);
888 +                if (retval) {
889 +                    struct local_callinfo *lci =
890 +                        pptp_call_closure_get(conn, call);
891 +                    dbglog("Closing connection (unhandled)");
892 +                    free(lci);
893 +                    /* soft shutdown.  Callback will do hard shutdown later */
894 +                    pptp_call_close(conn, call);
895 +                    vector_remove(call_list, i);
896 +                }
897 +                FD_CLR(i, &call_set);
898 +                close(i);
899 +            }
900 +    } while (vector_size(call_list) > 0 || first);
901 +shutdown:
902 +    {
903 +        int rc;
904 +        fd_set read_set, write_set;
905 +        struct timeval tv;
906 +       signal(SIGINT, callmgr_do_nothing);
907 +       signal(SIGTERM, callmgr_do_nothing);
908 +        /* warn("Shutdown"); */
909 +        /* kill all open calls */
910 +        for (i = 0; i < vector_size(call_list); i++) {
911 +            PPTP_CALL *call = vector_get_Nth(call_list, i);
912 +            dbglog("Closing connection (shutdown)");
913 +            pptp_call_close(conn, call);
914 +        }
915 +        /* attempt to dispatch these messages */
916 +        FD_ZERO(&read_set);
917 +        FD_ZERO(&write_set);
918 +        pptp_fd_set(conn, &read_set, &write_set, &max_fd);
919 +       tv.tv_sec = 0;
920 +       tv.tv_usec = 0;
921 +       select(max_fd + 1, &read_set, &write_set, NULL, &tv);
922 +        rc = pptp_dispatch(conn, &read_set, &write_set);
923 +       if (rc > 0) {
924 +         /* wait for a respond, a timeout because there might not be one */
925 +         FD_ZERO(&read_set);
926 +         FD_ZERO(&write_set);
927 +         pptp_fd_set(conn, &read_set, &write_set, &max_fd);
928 +         tv.tv_sec = 2;
929 +         tv.tv_usec = 0;
930 +         select(max_fd + 1, &read_set, &write_set, NULL, &tv);
931 +         rc = pptp_dispatch(conn, &read_set, &write_set);
932 +         if (rc > 0) {
933 +           if (i > 0) sleep(2);
934 +           /* no more open calls.  Close the connection. */
935 +           pptp_conn_close(conn, PPTP_STOP_LOCAL_SHUTDOWN);
936 +           /* wait for a respond, a timeout because there might not be one */
937 +           FD_ZERO(&read_set);
938 +           FD_ZERO(&write_set);
939 +           pptp_fd_set(conn, &read_set, &write_set, &max_fd);
940 +           tv.tv_sec = 2;
941 +           tv.tv_usec = 0;
942 +           select(max_fd + 1, &read_set, &write_set, NULL, &tv);
943 +           pptp_dispatch(conn, &read_set, &write_set);
944 +           if (rc > 0) sleep(2);
945 +         }
946 +       }
947 +        /* with extreme prejudice */
948 +        pptp_conn_destroy(conn);
949 +        vector_destroy(call_list);
950 +    }
951 +cleanup:
952 +    signal(SIGINT, callmgr_do_nothing);
953 +    signal(SIGTERM, callmgr_do_nothing);
954 +    close_inetsock(inet_sock, inetaddr);
955 +    close_unixsock(unix_sock, inetaddr);
956 +    return 0;
957 +}
958 +
959 +/*** open_inetsock ************************************************************/
960 +int open_inetsock(struct in_addr inetaddr)
961 +{
962 +    struct sockaddr_in dest, src;
963 +    int s;
964 +    dest.sin_family = AF_INET;
965 +    dest.sin_port   = htons(PPTP_PORT);
966 +    dest.sin_addr   = inetaddr;
967 +    if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
968 +        warn("socket: %s", strerror(errno));
969 +        return s;
970 +    }
971 +    if (localbind.s_addr != INADDR_NONE) {
972 +        bzero(&src, sizeof(src));
973 +        src.sin_family = AF_INET;
974 +        src.sin_addr   = localbind;
975 +        if (bind(s, (struct sockaddr *) &src, sizeof(src)) != 0) {
976 +            warn("bind: %s", strerror(errno));
977 +            close(s); return -1;
978 +        }
979 +    }
980 +    if (connect(s, (struct sockaddr *) &dest, sizeof(dest)) < 0) {
981 +        warn("connect: %s", strerror(errno));
982 +        close(s); return -1;
983 +    }
984 +    return s;
985 +}
986 +
987 +/*** open_unixsock ************************************************************/
988 +int open_unixsock(struct in_addr inetaddr)
989 +{
990 +    struct sockaddr_un where;
991 +    struct stat st;
992 +    char *dir;
993 +    int s;
994 +    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
995 +        warn("socket: %s", strerror(errno));
996 +        return s;
997 +    }
998 +    callmgr_name_unixsock( &where, inetaddr, localbind);
999 +    if (stat(where.sun_path, &st) >= 0)
1000 +    {
1001 +        warn("Call manager for %s is already running.", inet_ntoa(inetaddr));
1002 +        close(s); return -1;
1003 +    }
1004 +   /* Make sure path is valid. */
1005 +    dir = dirnamex(where.sun_path);
1006 +    if (!make_valid_path(dir, 0770))
1007 +        fatal("Could not make path to %s: %s", where.sun_path, strerror(errno));
1008 +    free(dir);
1009 +    if (bind(s, (struct sockaddr *) &where, sizeof(where)) < 0) {
1010 +        warn("bind: %s", strerror(errno));
1011 +        close(s); return -1;
1012 +    }
1013 +    chmod(where.sun_path, 0777);
1014 +    listen(s, 127);
1015 +    return s;
1016 +}
1017 +
1018 +/*** close_inetsock ***********************************************************/
1019 +void close_inetsock(int fd, struct in_addr inetaddr)
1020 +{
1021 +    close(fd);
1022 +}
1023 +
1024 +/*** close_unixsock ***********************************************************/
1025 +void close_unixsock(int fd, struct in_addr inetaddr)
1026 +{
1027 +    struct sockaddr_un where;
1028 +    close(fd);
1029 +    callmgr_name_unixsock(&where, inetaddr, localbind);
1030 +    unlink(where.sun_path);
1031 +}
1032 +
1033 +/*** make a unix socket address ***********************************************/
1034 +void callmgr_name_unixsock(struct sockaddr_un *where,
1035 +                          struct in_addr inetaddr,
1036 +                          struct in_addr localbind)
1037 +{
1038 +    char localaddr[16], remoteaddr[16];
1039 +    where->sun_family = AF_UNIX;
1040 +    strncpy(localaddr,  inet_ntoa(localbind), 16);
1041 +    strncpy(remoteaddr, inet_ntoa(inetaddr),  16);
1042 +    snprintf(where->sun_path, sizeof(where->sun_path),
1043 +            PPTP_SOCKET_PREFIX "%s:%i", remoteaddr,call_ID);
1044 +}
1045 --- /dev/null
1046 +++ b/pppd/plugins/pptp/pptp_callmgr.h
1047 @@ -0,0 +1,17 @@
1048 +/* pptp_callmgr.h ... Call manager for PPTP connections.
1049 + *                    Handles TCP port 1723 protocol.
1050 + *                    C. Scott Ananian <cananian@alumni.princeton.edu>
1051 + *
1052 + * $Id: pptp_callmgr.h,v 1.3 2003/02/17 00:22:17 quozl Exp $
1053 + */
1054 +
1055 +#define PPTP_SOCKET_PREFIX "/var/run/pptp/"
1056 +
1057 +int callmgr_main(struct in_addr inetaddr,
1058 +               char phonenr[],
1059 +               int window,
1060 +               int pcallid);
1061 +
1062 +void callmgr_name_unixsock(struct sockaddr_un *where,
1063 +                          struct in_addr inetaddr,
1064 +                          struct in_addr localbind);
1065 --- /dev/null
1066 +++ b/pppd/plugins/pptp/pptp_ctrl.c
1067 @@ -0,0 +1,1078 @@
1068 +/* pptp_ctrl.c ... handle PPTP control connection.
1069 + *                 C. Scott Ananian <cananian@alumni.princeton.edu>
1070 + *
1071 + * $Id: pptp_ctrl.c,v 1.31 2005/03/31 07:42:39 quozl Exp $
1072 + */
1073 +
1074 +#include <errno.h>
1075 +#include <sys/time.h>
1076 +#include <sys/types.h>
1077 +#include <sys/socket.h>
1078 +#include <netinet/in.h>
1079 +#include <unistd.h>
1080 +#include <stdlib.h>
1081 +#include <assert.h>
1082 +#include <signal.h>
1083 +#include <string.h>
1084 +#include <ctype.h>
1085 +#include <fcntl.h>
1086 +#include "pppd.h"
1087 +#include "pptp_msg.h"
1088 +#include "pptp_ctrl.h"
1089 +#include "pptp_options.h"
1090 +#include "vector.h"
1091 +#include "util.h"
1092 +#include "pptp_quirks.h"
1093 +
1094 +/* BECAUSE OF SIGNAL LIMITATIONS, EACH PROCESS CAN ONLY MANAGE ONE
1095 + * CONNECTION.  SO THIS 'PPTP_CONN' STRUCTURE IS A BIT MISLEADING.
1096 + * WE'LL KEEP CONNECTION-SPECIFIC INFORMATION IN THERE ANYWAY (AS
1097 + * OPPOSED TO USING GLOBAL VARIABLES), BUT BEWARE THAT THE ENTIRE
1098 + * UNIX SIGNAL-HANDLING SEMANTICS WOULD HAVE TO CHANGE (OR THE
1099 + * TIME-OUT CODE DRASTICALLY REWRITTEN) BEFORE YOU COULD DO A
1100 + * PPTP_CONN_OPEN MORE THAN ONCE PER PROCESS AND GET AWAY WITH IT.
1101 + */
1102 +
1103 +/* This structure contains connection-specific information that the
1104 + * signal handler needs to see.  Thus, it needs to be in a global
1105 + * variable.  If you end up using pthreads or something (why not
1106 + * just processes?), this would have to be placed in a thread-specific
1107 + * data area, using pthread_get|set_specific, etc., so I've
1108 + * conveniently encapsulated it for you.
1109 + * [linux threads will have to support thread-specific signals
1110 + *  before this would work at all, which, as of this writing
1111 + *  (linux-threads v0.6, linux kernel 2.1.72), it does not.]
1112 + */
1113 +
1114 +/* Globals */
1115 +
1116 +/* control the number of times echo packets will be logged */
1117 +static int nlogecho = 10;
1118 +
1119 +static struct thread_specific {
1120 +    struct sigaction old_sigaction; /* evil signals */
1121 +    PPTP_CONN * conn;
1122 +} global;
1123 +
1124 +#define INITIAL_BUFSIZE 512 /* initial i/o buffer size. */
1125 +
1126 +struct PPTP_CONN {
1127 +    int inet_sock;
1128 +    /* Connection States */
1129 +    enum {
1130 +        CONN_IDLE, CONN_WAIT_CTL_REPLY, CONN_WAIT_STOP_REPLY, CONN_ESTABLISHED
1131 +    } conn_state; /* on startup: CONN_IDLE */
1132 +    /* Keep-alive states */
1133 +    enum {
1134 +        KA_NONE, KA_OUTSTANDING
1135 +    } ka_state;  /* on startup: KA_NONE */
1136 +    /* Keep-alive ID; monotonically increasing (watch wrap-around!) */
1137 +    u_int32_t ka_id; /* on startup: 1 */
1138 +    /* Other properties. */
1139 +    u_int16_t version;
1140 +    u_int16_t firmware_rev;
1141 +    u_int8_t  hostname[64], vendor[64];
1142 +    /* XXX these are only PNS properties, currently XXX */
1143 +    /* Call assignment information. */
1144 +    u_int16_t call_serial_number;
1145 +    VECTOR *call;
1146 +    void * closure;
1147 +    pptp_conn_cb callback;
1148 +    /******* IO buffers ******/
1149 +    char * read_buffer, *write_buffer;
1150 +    size_t read_alloc,   write_alloc;
1151 +    size_t read_size,    write_size;
1152 +};
1153 +
1154 +struct PPTP_CALL {
1155 +    /* Call properties */
1156 +    enum {
1157 +        PPTP_CALL_PAC, PPTP_CALL_PNS
1158 +    } call_type;
1159 +    union {
1160 +        enum pptp_pac_state {
1161 +            PAC_IDLE, PAC_WAIT_REPLY, PAC_ESTABLISHED, PAC_WAIT_CS_ANS
1162 +        } pac;
1163 +        enum pptp_pns_state {
1164 +            PNS_IDLE, PNS_WAIT_REPLY, PNS_ESTABLISHED, PNS_WAIT_DISCONNECT
1165 +        } pns;
1166 +    } state;
1167 +    u_int16_t call_id, peer_call_id;
1168 +    u_int16_t sernum;
1169 +    u_int32_t speed;
1170 +    /* For user data: */
1171 +    pptp_call_cb callback;
1172 +    void * closure;
1173 +};
1174 +
1175 +
1176 +/* PPTP error codes: ----------------------------------------------*/
1177 +
1178 +/* (General Error Codes) */
1179 +static const struct {
1180 +    const char *name, *desc;
1181 +} pptp_general_errors[] = {
1182 +#define PPTP_GENERAL_ERROR_NONE                 0
1183 +    { "(None)", "No general error" },
1184 +#define PPTP_GENERAL_ERROR_NOT_CONNECTED        1
1185 +    { "(Not-Connected)", "No control connection exists yet for this "
1186 +        "PAC-PNS pair" },
1187 +#define PPTP_GENERAL_ERROR_BAD_FORMAT           2
1188 +    { "(Bad-Format)", "Length is wrong or Magic Cookie value is incorrect" },
1189 +#define PPTP_GENERAL_ERROR_BAD_VALUE            3
1190 +    { "(Bad-Value)", "One of the field values was out of range or "
1191 +            "reserved field was non-zero" },
1192 +#define PPTP_GENERAL_ERROR_NO_RESOURCE          4
1193 +    { "(No-Resource)", "Insufficient resources to handle this command now" },
1194 +#define PPTP_GENERAL_ERROR_BAD_CALLID           5
1195 +    { "(Bad-Call ID)", "The Call ID is invalid in this context" },
1196 +#define PPTP_GENERAL_ERROR_PAC_ERROR            6
1197 +    { "(PAC-Error)", "A generic vendor-specific error occured in the PAC" }
1198 +};
1199 +
1200 +#define  MAX_GENERAL_ERROR ( sizeof(pptp_general_errors) / \
1201 +        sizeof(pptp_general_errors[0]) - 1)
1202 +
1203 +/* Outgoing Call Reply Result Codes */
1204 +static const char *pptp_out_call_reply_result[] = {
1205 +/* 0 */        "Unknown Result Code",
1206 +/* 1 */        "Connected",
1207 +/* 2 */        "General Error",
1208 +/* 3 */        "No Carrier Detected",
1209 +/* 4 */        "Busy Signal",
1210 +/* 5 */        "No Dial Tone",
1211 +/* 6 */        "Time Out",
1212 +/* 7 */        "Not Accepted, Call is administratively prohibited" };
1213 +
1214 +#define MAX_OUT_CALL_REPLY_RESULT 7
1215 +
1216 +/* Call Disconnect Notify  Result Codes */
1217 +static const char *pptp_call_disc_ntfy[] = {
1218 +/* 0 */        "Unknown Result Code",
1219 +/* 1 */        "Lost Carrier",
1220 +/* 2 */        "General Error",
1221 +/* 3 */        "Administrative Shutdown",
1222 +/* 4 */        "(your) Request" };
1223 +
1224 +#define MAX_CALL_DISC_NTFY 4
1225 +
1226 +/* Call Disconnect Notify  Result Codes */
1227 +static const char *pptp_start_ctrl_conn_rply[] = {
1228 +/* 0 */        "Unknown Result Code",
1229 +/* 1 */        "Successful Channel Establishment",
1230 +/* 2 */        "General Error",
1231 +/* 3 */        "Command Channel Already Exists",
1232 +/* 4 */        "Requester is not Authorized" };
1233 +
1234 +#define MAX_START_CTRL_CONN_REPLY 4
1235 +
1236 +/* timing options */
1237 +int idle_wait = PPTP_TIMEOUT;
1238 +int max_echo_wait = PPTP_TIMEOUT;
1239 +
1240 +/* Local prototypes */
1241 +static void pptp_reset_timer(void);
1242 +static void pptp_handle_timer();
1243 +/* Write/read as much as we can without blocking. */
1244 +int pptp_write_some(PPTP_CONN * conn);
1245 +int pptp_read_some(PPTP_CONN * conn);
1246 +/* Make valid packets from read_buffer */
1247 +int pptp_make_packet(PPTP_CONN * conn, void **buf, size_t *size);
1248 +/* Add packet to write_buffer */
1249 +int pptp_send_ctrl_packet(PPTP_CONN * conn, void * buffer, size_t size);
1250 +/* Dispatch packets (general) */
1251 +int pptp_dispatch_packet(PPTP_CONN * conn, void * buffer, size_t size);
1252 +/* Dispatch packets (control messages) */
1253 +int ctrlp_disp(PPTP_CONN * conn, void * buffer, size_t size);
1254 +/* Set link info, for pptp servers that need it.
1255 +   this is a noop, unless the user specified a quirk and
1256 +   there's a set_link hook defined in the quirks table
1257 +   for that quirk */
1258 +void pptp_set_link(PPTP_CONN * conn, int peer_call_id);
1259 +
1260 +/*** log error information in control packets *********************************/
1261 +static void ctrlp_error( int result, int error, int cause,
1262 +        const char *result_text[], int max_result)
1263 +{
1264 +    if( cause >= 0)
1265 +        warn("Result code is %d '%s'. Error code is %d, Cause code is %d",
1266 +                result, result_text[result <= max_result ?  result : 0], error,
1267 +                cause );
1268 +    else
1269 +        warn("Reply result code is %d '%s'. Error code is %d",
1270 +                result, result_text[result <= max_result ?  result : 0], error);
1271 +    if ((error > 0) && (error <= MAX_GENERAL_ERROR)){
1272 +        if( result != PPTP_RESULT_GENERAL_ERROR )
1273 +            warn("Result code is something else then \"general error\", "
1274 +                    "so the following error is probably bogus.");
1275 +        warn("Error is '%s', Error message: '%s'",
1276 +                pptp_general_errors[error].name,
1277 +                pptp_general_errors[error].desc);
1278 +    }
1279 +}
1280 +
1281 +static const char *ctrl_msg_types[] = {
1282 +         "invalid control message type",
1283 +/*         (Control Connection Management) */
1284 +         "Start-Control-Connection-Request",            /* 1 */
1285 +         "Start-Control-Connection-Reply",              /* 2 */
1286 +         "Stop-Control-Connection-Request",             /* 3 */
1287 +         "Stop-Control-Connection-Reply",               /* 4 */
1288 +         "Echo-Request",                                /* 5 */
1289 +         "Echo-Reply",                                  /* 6 */
1290 +/*         (Call Management) */
1291 +         "Outgoing-Call-Request",                       /* 7 */
1292 +         "Outgoing-Call-Reply",                         /* 8 */
1293 +         "Incoming-Call-Request",                       /* 9 */
1294 +         "Incoming-Call-Reply",                        /* 10 */
1295 +         "Incoming-Call-Connected",                    /* 11 */
1296 +         "Call-Clear-Request",                         /* 12 */
1297 +         "Call-Disconnect-Notify",                     /* 13 */
1298 +/*         (Error Reporting) */
1299 +         "WAN-Error-Notify",                           /* 14 */
1300 +/*         (PPP Session Control) */
1301 +         "Set-Link-Info"                              /* 15 */
1302 +};
1303 +#define MAX_CTRLMSG_TYPE 15
1304 +
1305 +/*** report a sent packet ****************************************************/
1306 +static void ctrlp_rep( void * buffer, int size, int isbuff)
1307 +{
1308 +    struct pptp_header *packet = buffer;
1309 +    unsigned int type;
1310 +    if(size < sizeof(struct pptp_header)) return;
1311 +    type = ntoh16(packet->ctrl_type);
1312 +    /* FIXME: do not report sending echo requests as long as they are
1313 +     * sent in a signal handler. This may dead lock as the syslog call
1314 +     * is not reentrant */
1315 +    if( type ==  PPTP_ECHO_RQST ) return;
1316 +    /* don't keep reporting sending of echo's */
1317 +    if( (type == PPTP_ECHO_RQST || type == PPTP_ECHO_RPLY) && nlogecho <= 0 ) return;
1318 +    dbglog("%s control packet type is %d '%s'\n",isbuff ? "Buffered" : "Sent",
1319 +            type, ctrl_msg_types[type <= MAX_CTRLMSG_TYPE ? type : 0]);
1320 +
1321 +}
1322 +
1323 +
1324 +
1325 +/* Open new pptp_connection.  Returns NULL on failure. */
1326 +PPTP_CONN * pptp_conn_open(int inet_sock, int isclient, pptp_conn_cb callback)
1327 +{
1328 +    PPTP_CONN *conn;
1329 +    /* Allocate structure */
1330 +    if ((conn = malloc(sizeof(*conn))) == NULL) return NULL;
1331 +    if ((conn->call = vector_create()) == NULL) { free(conn); return NULL; }
1332 +    /* Initialize */
1333 +    conn->inet_sock = inet_sock;
1334 +    conn->conn_state = CONN_IDLE;
1335 +    conn->ka_state  = KA_NONE;
1336 +    conn->ka_id     = 1;
1337 +    conn->call_serial_number = 0;
1338 +    conn->callback  = callback;
1339 +    /* Create I/O buffers */
1340 +    conn->read_size = conn->write_size = 0;
1341 +    conn->read_alloc = conn->write_alloc = INITIAL_BUFSIZE;
1342 +    conn->read_buffer =
1343 +        malloc(sizeof(*(conn->read_buffer)) * conn->read_alloc);
1344 +    conn->write_buffer =
1345 +        malloc(sizeof(*(conn->write_buffer)) * conn->write_alloc);
1346 +    if (conn->read_buffer == NULL || conn->write_buffer == NULL) {
1347 +        if (conn->read_buffer  != NULL) free(conn->read_buffer);
1348 +        if (conn->write_buffer != NULL) free(conn->write_buffer);
1349 +        vector_destroy(conn->call); free(conn); return NULL;
1350 +    }
1351 +    /* Make this socket non-blocking. */
1352 +    fcntl(conn->inet_sock, F_SETFL, O_NONBLOCK);
1353 +    /* Request connection from server, if this is a client */
1354 +    if (isclient) {
1355 +        struct pptp_start_ctrl_conn packet = {
1356 +            PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RQST),
1357 +            hton16(PPTP_VERSION), 0, 0,
1358 +            hton32(PPTP_FRAME_CAP), hton32(PPTP_BEARER_CAP),
1359 +            hton16(PPTP_MAX_CHANNELS), hton16(PPTP_FIRMWARE_VERSION),
1360 +            PPTP_HOSTNAME, PPTP_VENDOR
1361 +        };
1362 +        /* fix this packet, if necessary */
1363 +        int idx, rc;
1364 +        idx = get_quirk_index();
1365 +        if (idx != -1 && pptp_fixups[idx].start_ctrl_conn) {
1366 +            if ((rc = pptp_fixups[idx].start_ctrl_conn(&packet)))
1367 +                warn("calling the start_ctrl_conn hook failed (%d)", rc);
1368 +        }
1369 +        if (pptp_send_ctrl_packet(conn, &packet, sizeof(packet)))
1370 +            conn->conn_state = CONN_WAIT_CTL_REPLY;
1371 +        else
1372 +            return NULL; /* could not send initial start request. */
1373 +    }
1374 +    /* Set up interval/keep-alive timer */
1375 +    /*   First, register handler for SIGALRM */
1376 +    sigpipe_create();
1377 +    sigpipe_assign(SIGALRM);
1378 +    global.conn = conn;
1379 +    /* Reset event timer */
1380 +    pptp_reset_timer();
1381 +    /* all done. */
1382 +    return conn;
1383 +}
1384 +
1385 +int pptp_conn_established(PPTP_CONN *conn) {
1386 +  return (conn->conn_state == CONN_ESTABLISHED);
1387 +}
1388 +
1389 +/* This currently *only* works for client call requests.
1390 + * We need to do something else to allocate calls for incoming requests.
1391 + */
1392 +PPTP_CALL * pptp_call_open(PPTP_CONN * conn, int call_id,pptp_call_cb callback,
1393 +        char *phonenr,int window)
1394 +{
1395 +    PPTP_CALL * call;
1396 +    int idx, rc;
1397 +    /* Send off the call request */
1398 +    struct pptp_out_call_rqst packet = {
1399 +        PPTP_HEADER_CTRL(PPTP_OUT_CALL_RQST),
1400 +        0,0, /*call_id, sernum */
1401 +        hton32(PPTP_BPS_MIN), hton32(PPTP_BPS_MAX),
1402 +        hton32(PPTP_BEARER_CAP), hton32(PPTP_FRAME_CAP),
1403 +        hton16(window), 0, 0, 0, {0}, {0}
1404 +    };
1405 +    assert(conn && conn->call);
1406 +    assert(conn->conn_state == CONN_ESTABLISHED);
1407 +    /* Assign call id */
1408 +    if (!call_id && !vector_scan(conn->call, 0, PPTP_MAX_CHANNELS - 1, &call_id))
1409 +        /* no more calls available! */
1410 +        return NULL;
1411 +    /* allocate structure. */
1412 +    if ((call = malloc(sizeof(*call))) == NULL) return NULL;
1413 +    /* Initialize call structure */
1414 +    call->call_type = PPTP_CALL_PNS;
1415 +    call->state.pns = PNS_IDLE;
1416 +    call->call_id   = (u_int16_t) call_id;
1417 +    call->sernum    = conn->call_serial_number++;
1418 +    call->callback  = callback;
1419 +    call->closure   = NULL;
1420 +    packet.call_id = htons(call->call_id);
1421 +    packet.call_sernum = htons(call->sernum);
1422 +    /* if we have a quirk, build a new packet to fit it */
1423 +    idx = get_quirk_index();
1424 +    if (idx != -1 && pptp_fixups[idx].out_call_rqst_hook) {
1425 +        if ((rc = pptp_fixups[idx].out_call_rqst_hook(&packet)))
1426 +            warn("calling the out_call_rqst hook failed (%d)", rc);
1427 +    }
1428 +    /* fill in the phone number if it was specified */
1429 +    if (phonenr) {
1430 +        strncpy(packet.phone_num, phonenr, sizeof(packet.phone_num));
1431 +        packet.phone_len = strlen(phonenr);
1432 +        if( packet.phone_len > sizeof(packet.phone_num))
1433 +            packet.phone_len = sizeof(packet.phone_num);
1434 +        packet.phone_len = hton16 (packet.phone_len);
1435 +    }
1436 +    if (pptp_send_ctrl_packet(conn, &packet, sizeof(packet))) {
1437 +        pptp_reset_timer();
1438 +        call->state.pns = PNS_WAIT_REPLY;
1439 +        /* and add it to the call vector */
1440 +        vector_insert(conn->call, call_id, call);
1441 +        return call;
1442 +    } else { /* oops, unsuccessful. Deallocate. */
1443 +        free(call);
1444 +        return NULL;
1445 +    }
1446 +}
1447 +
1448 +/*** pptp_call_close **********************************************************/
1449 +void pptp_call_close(PPTP_CONN * conn, PPTP_CALL * call)
1450 +{
1451 +    struct pptp_call_clear_rqst rqst = {
1452 +        PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_RQST), 0, 0
1453 +    };
1454 +    assert(conn && conn->call); assert(call);
1455 +    assert(vector_contains(conn->call, call->call_id));
1456 +    /* haven't thought about PAC yet */
1457 +    assert(call->call_type == PPTP_CALL_PNS);
1458 +    assert(call->state.pns != PNS_IDLE);
1459 +    rqst.call_id = hton16(call->call_id);
1460 +    /* don't check state against WAIT_DISCONNECT... allow multiple disconnect
1461 +     * requests to be made.
1462 +     */
1463 +    pptp_send_ctrl_packet(conn, &rqst, sizeof(rqst));
1464 +    pptp_reset_timer();
1465 +    call->state.pns = PNS_WAIT_DISCONNECT;
1466 +    /* call structure will be freed when we have confirmation of disconnect. */
1467 +}
1468 +
1469 +/*** hard close ***************************************************************/
1470 +void pptp_call_destroy(PPTP_CONN *conn, PPTP_CALL *call)
1471 +{
1472 +    assert(conn && conn->call); assert(call);
1473 +    assert(vector_contains(conn->call, call->call_id));
1474 +    /* notify */
1475 +    if (call->callback != NULL) call->callback(conn, call, CALL_CLOSE_DONE);
1476 +    /* deallocate */
1477 +    vector_remove(conn->call, call->call_id);
1478 +    free(call);
1479 +}
1480 +
1481 +/*** this is a soft close *****************************************************/
1482 +void pptp_conn_close(PPTP_CONN * conn, u_int8_t close_reason)
1483 +{
1484 +    struct pptp_stop_ctrl_conn rqst = {
1485 +        PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RQST),
1486 +        hton8(close_reason), 0, 0
1487 +    };
1488 +    int i;
1489 +    assert(conn && conn->call);
1490 +    /* avoid repeated close attempts */
1491 +    if (conn->conn_state == CONN_IDLE || conn->conn_state == CONN_WAIT_STOP_REPLY)
1492 +        return;
1493 +    /* close open calls, if any */
1494 +    for (i = 0; i < vector_size(conn->call); i++)
1495 +        pptp_call_close(conn, vector_get_Nth(conn->call, i));
1496 +    /* now close connection */
1497 +    info("Closing PPTP connection");
1498 +    pptp_send_ctrl_packet(conn, &rqst, sizeof(rqst));
1499 +    pptp_reset_timer(); /* wait 60 seconds for reply */
1500 +    conn->conn_state = CONN_WAIT_STOP_REPLY;
1501 +    return;
1502 +}
1503 +
1504 +/*** this is a hard close *****************************************************/
1505 +void pptp_conn_destroy(PPTP_CONN * conn)
1506 +{
1507 +    int i;
1508 +    assert(conn != NULL); assert(conn->call != NULL);
1509 +    /* destroy all open calls */
1510 +    for (i = 0; i < vector_size(conn->call); i++)
1511 +        pptp_call_destroy(conn, vector_get_Nth(conn->call, i));
1512 +    /* notify */
1513 +    if (conn->callback != NULL) conn->callback(conn, CONN_CLOSE_DONE);
1514 +    sigpipe_close();
1515 +    close(conn->inet_sock);
1516 +    /* deallocate */
1517 +    vector_destroy(conn->call);
1518 +    free(conn);
1519 +}
1520 +
1521 +/*** Deal with messages, in a non-blocking manner
1522 + * Add file descriptors used by pptp to fd_set.
1523 + */
1524 +void pptp_fd_set(PPTP_CONN * conn, fd_set * read_set, fd_set * write_set,
1525 +                 int * max_fd)
1526 +{
1527 +    assert(conn && conn->call);
1528 +    /* Add fd to write_set if there are outstanding writes. */
1529 +    if (conn->write_size > 0)
1530 +        FD_SET(conn->inet_sock, write_set);
1531 +    /* Always add fd to read_set. (always want something to read) */
1532 +    FD_SET(conn->inet_sock, read_set);
1533 +    if (*max_fd < conn->inet_sock) *max_fd = conn->inet_sock;
1534 +    /* Add signal pipe file descriptor to set */
1535 +    int sig_fd = sigpipe_fd();
1536 +    FD_SET(sig_fd, read_set);
1537 +    if (*max_fd < sig_fd) *max_fd = sig_fd;
1538 +}
1539 +
1540 +/*** handle any pptp file descriptors set in fd_set, and clear them ***********/
1541 +int pptp_dispatch(PPTP_CONN * conn, fd_set * read_set, fd_set * write_set)
1542 +{
1543 +    int r = 0;
1544 +    assert(conn && conn->call);
1545 +    /* Check for signals */
1546 +    if (FD_ISSET(sigpipe_fd(), read_set)) {
1547 +        if (sigpipe_read() == SIGALRM) pptp_handle_timer();
1548 +       FD_CLR(sigpipe_fd(), read_set);
1549 +    }
1550 +    /* Check write_set could be set. */
1551 +    if (FD_ISSET(conn->inet_sock, write_set)) {
1552 +        FD_CLR(conn->inet_sock, write_set);
1553 +        if (conn->write_size > 0)
1554 +            r = pptp_write_some(conn);/* write as much as we can without blocking */
1555 +    }
1556 +    /* Check read_set */
1557 +    if (r >= 0 && FD_ISSET(conn->inet_sock, read_set)) {
1558 +        void *buffer; size_t size;
1559 +        FD_CLR(conn->inet_sock, read_set);
1560 +        r = pptp_read_some(conn); /* read as much as we can without blocking */
1561 +       if (r < 0)
1562 +           return r;
1563 +        /* make packets of the buffer, while we can. */
1564 +        while (r >= 0 && pptp_make_packet(conn, &buffer, &size)) {
1565 +            r = pptp_dispatch_packet(conn, buffer, size);
1566 +            free(buffer);
1567 +        }
1568 +    }
1569 +    /* That's all, folks.  Simple, eh? */
1570 +    return r;
1571 +}
1572 +
1573 +/*** Non-blocking write *******************************************************/
1574 +int pptp_write_some(PPTP_CONN * conn) {
1575 +    ssize_t retval;
1576 +    assert(conn && conn->call);
1577 +    retval = write(conn->inet_sock, conn->write_buffer, conn->write_size);
1578 +    if (retval < 0) { /* error. */
1579 +        if (errno == EAGAIN || errno == EINTR) {
1580 +            return 0;
1581 +        } else { /* a real error */
1582 +            warn("write error: %s", strerror(errno));
1583 +           return -1;
1584 +        }
1585 +    }
1586 +    assert(retval <= conn->write_size);
1587 +    conn->write_size -= retval;
1588 +    memmove(conn->write_buffer, conn->write_buffer + retval, conn->write_size);
1589 +    ctrlp_rep(conn->write_buffer, retval, 0);
1590 +    return 0;
1591 +}
1592 +
1593 +/*** Non-blocking read ********************************************************/
1594 +int pptp_read_some(PPTP_CONN * conn)
1595 +{
1596 +    ssize_t retval;
1597 +    assert(conn && conn->call);
1598 +    if (conn->read_size == conn->read_alloc) { /* need to alloc more memory */
1599 +        char *new_buffer = realloc(conn->read_buffer,
1600 +                sizeof(*(conn->read_buffer)) * conn->read_alloc * 2);
1601 +        if (new_buffer == NULL) {
1602 +            warn("Out of memory"); return -1;
1603 +        }
1604 +        conn->read_alloc *= 2;
1605 +        conn->read_buffer = new_buffer;
1606 +    }
1607 +    retval = read(conn->inet_sock, conn->read_buffer + conn->read_size,
1608 +            conn->read_alloc  - conn->read_size);
1609 +    if (retval == 0) {
1610 +        warn("read returned zero, peer has closed");
1611 +        return -1;
1612 +    }
1613 +    if (retval < 0) {
1614 +        if (errno == EINTR || errno == EAGAIN)
1615 +           return 0;
1616 +        else { /* a real error */
1617 +            warn("read error: %s", strerror(errno));
1618 +            return -1;
1619 +        }
1620 +    }
1621 +    conn->read_size += retval;
1622 +    assert(conn->read_size <= conn->read_alloc);
1623 +    return 0;
1624 +}
1625 +
1626 +/*** Packet formation *********************************************************/
1627 +int pptp_make_packet(PPTP_CONN * conn, void **buf, size_t *size)
1628 +{
1629 +    struct pptp_header *header;
1630 +    size_t bad_bytes = 0;
1631 +    assert(conn && conn->call); assert(buf != NULL); assert(size != NULL);
1632 +    /* Give up unless there are at least sizeof(pptp_header) bytes */
1633 +    while ((conn->read_size-bad_bytes) >= sizeof(struct pptp_header)) {
1634 +        /* Throw out bytes until we have a valid header. */
1635 +        header = (struct pptp_header *) (conn->read_buffer + bad_bytes);
1636 +        if (ntoh32(header->magic) != PPTP_MAGIC) goto throwitout;
1637 +        if (ntoh16(header->reserved0) != 0)
1638 +            warn("reserved0 field is not zero! (0x%x) Cisco feature? \n",
1639 +                    ntoh16(header->reserved0));
1640 +        if (ntoh16(header->length) < sizeof(struct pptp_header)) goto throwitout;
1641 +        if (ntoh16(header->length) > PPTP_CTRL_SIZE_MAX) goto throwitout;
1642 +        /* well.  I guess it's good. Let's see if we've got it all. */
1643 +        if (ntoh16(header->length) > (conn->read_size-bad_bytes))
1644 +            /* nope.  Let's wait until we've got it, then. */
1645 +            goto flushbadbytes;
1646 +        /* One last check: */
1647 +        if ((ntoh16(header->pptp_type) == PPTP_MESSAGE_CONTROL) &&
1648 +                (ntoh16(header->length) !=
1649 +                         PPTP_CTRL_SIZE(ntoh16(header->ctrl_type))))
1650 +            goto throwitout;
1651 +        /* well, I guess we've got it. */
1652 +        *size = ntoh16(header->length);
1653 +        *buf = malloc(*size);
1654 +        if (*buf == NULL) { warn("Out of memory."); return 0; /* ack! */ }
1655 +        memcpy(*buf, conn->read_buffer + bad_bytes, *size);
1656 +        /* Delete this packet from the read_buffer. */
1657 +        conn->read_size -= (bad_bytes + *size);
1658 +        memmove(conn->read_buffer, conn->read_buffer + bad_bytes + *size,
1659 +                conn->read_size);
1660 +        if (bad_bytes > 0)
1661 +            warn("%lu bad bytes thrown away.", (unsigned long) bad_bytes);
1662 +        return 1;
1663 +throwitout:
1664 +        bad_bytes++;
1665 +    }
1666 +flushbadbytes:
1667 +    /* no more packets.  Let's get rid of those bad bytes */
1668 +    conn->read_size -= bad_bytes;
1669 +    memmove(conn->read_buffer, conn->read_buffer + bad_bytes, conn->read_size);
1670 +    if (bad_bytes > 0)
1671 +        warn("%lu bad bytes thrown away.", (unsigned long) bad_bytes);
1672 +    return 0;
1673 +}
1674 +
1675 +/*** pptp_send_ctrl_packet ****************************************************/
1676 +int pptp_send_ctrl_packet(PPTP_CONN * conn, void * buffer, size_t size)
1677 +{
1678 +    assert(conn && conn->call); assert(buffer);
1679 +    if( conn->write_size > 0) pptp_write_some( conn);
1680 +    if( conn->write_size == 0) {
1681 +        ssize_t retval;
1682 +        retval = write(conn->inet_sock, buffer, size);
1683 +        if (retval < 0) { /* error. */
1684 +            if (errno == EAGAIN || errno == EINTR) {
1685 +                /* ignore */;
1686 +                retval = 0;
1687 +            } else { /* a real error */
1688 +                warn("write error: %s", strerror(errno));
1689 +                pptp_conn_destroy(conn); /* shut down fast. */
1690 +                return 0;
1691 +            }
1692 +        }
1693 +        ctrlp_rep( buffer, retval, 0);
1694 +        size -= retval;
1695 +        if( size <= 0) return 1;
1696 +    }
1697 +    /* Shove anything not written into the write buffer */
1698 +    if (conn->write_size + size > conn->write_alloc) { /* need more memory */
1699 +        char *new_buffer = realloc(conn->write_buffer,
1700 +                sizeof(*(conn->write_buffer)) * conn->write_alloc * 2);
1701 +        if (new_buffer == NULL) {
1702 +            warn("Out of memory"); return 0;
1703 +        }
1704 +        conn->write_alloc *= 2;
1705 +        conn->write_buffer = new_buffer;
1706 +    }
1707 +    memcpy(conn->write_buffer + conn->write_size, buffer, size);
1708 +    conn->write_size += size;
1709 +    ctrlp_rep( buffer,size,1);
1710 +    return 1;
1711 +}
1712 +
1713 +/*** Packet Dispatch **********************************************************/
1714 +int pptp_dispatch_packet(PPTP_CONN * conn, void * buffer, size_t size)
1715 +{
1716 +    int r = 0;
1717 +    struct pptp_header *header = (struct pptp_header *)buffer;
1718 +    assert(conn && conn->call); assert(buffer);
1719 +    assert(ntoh32(header->magic) == PPTP_MAGIC);
1720 +    assert(ntoh16(header->length) == size);
1721 +    switch (ntoh16(header->pptp_type)) {
1722 +        case PPTP_MESSAGE_CONTROL:
1723 +            r = ctrlp_disp(conn, buffer, size);
1724 +            break;
1725 +        case PPTP_MESSAGE_MANAGE:
1726 +            /* MANAGEMENT messages aren't even part of the spec right now. */
1727 +            dbglog("PPTP management message received, but not understood.");
1728 +            break;
1729 +        default:
1730 +            dbglog("Unknown PPTP control message type received: %u",
1731 +                    (unsigned int) ntoh16(header->pptp_type));
1732 +            break;
1733 +    }
1734 +    return r;
1735 +}
1736 +
1737 +/*** log echo request/replies *************************************************/
1738 +static void logecho( int type)
1739 +{
1740 +    /* hack to stop flooding the log files (the most interesting part is right
1741 +     * after the connection built-up) */
1742 +    if( nlogecho > 0) {
1743 +        dbglog("Echo Re%s received.", type == PPTP_ECHO_RQST ? "quest" :"ply");
1744 +        if( --nlogecho == 0)
1745 +            dbglog("no more Echo Reply/Request packets will be reported.");
1746 +    }
1747 +}
1748 +
1749 +/*** pptp_dispatch_ctrl_packet ************************************************/
1750 +int ctrlp_disp(PPTP_CONN * conn, void * buffer, size_t size)
1751 +{
1752 +    struct pptp_header *header = (struct pptp_header *)buffer;
1753 +    u_int8_t close_reason = PPTP_STOP_NONE;
1754 +    assert(conn && conn->call); assert(buffer);
1755 +    assert(ntoh32(header->magic) == PPTP_MAGIC);
1756 +    assert(ntoh16(header->length) == size);
1757 +    assert(ntoh16(header->pptp_type) == PPTP_MESSAGE_CONTROL);
1758 +    if (size < PPTP_CTRL_SIZE(ntoh16(header->ctrl_type))) {
1759 +        warn("Invalid packet received [type: %d; length: %d].",
1760 +                (int) ntoh16(header->ctrl_type), (int) size);
1761 +        return 0;
1762 +    }
1763 +    switch (ntoh16(header->ctrl_type)) {
1764 +        /* ----------- STANDARD Start-Session MESSAGES ------------ */
1765 +        case PPTP_START_CTRL_CONN_RQST:
1766 +        {
1767 +            struct pptp_start_ctrl_conn *packet =
1768 +                (struct pptp_start_ctrl_conn *) buffer;
1769 +            struct pptp_start_ctrl_conn reply = {
1770 +                PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RPLY),
1771 +                hton16(PPTP_VERSION), 0, 0,
1772 +                hton32(PPTP_FRAME_CAP), hton32(PPTP_BEARER_CAP),
1773 +                hton16(PPTP_MAX_CHANNELS), hton16(PPTP_FIRMWARE_VERSION),
1774 +                PPTP_HOSTNAME, PPTP_VENDOR };
1775 +            int idx, rc;
1776 +            dbglog("Received Start Control Connection Request");
1777 +            /* fix this packet, if necessary */
1778 +            idx = get_quirk_index();
1779 +            if (idx != -1 && pptp_fixups[idx].start_ctrl_conn) {
1780 +                if ((rc = pptp_fixups[idx].start_ctrl_conn(&reply)))
1781 +                    warn("calling the start_ctrl_conn hook failed (%d)", rc);
1782 +            }
1783 +            if (conn->conn_state == CONN_IDLE) {
1784 +                if (ntoh16(packet->version) < PPTP_VERSION) {
1785 +                    /* Can't support this (earlier) PPTP_VERSION */
1786 +                    reply.version = packet->version;
1787 +                    /* protocol version not supported */
1788 +                    reply.result_code = hton8(5);
1789 +                    pptp_send_ctrl_packet(conn, &reply, sizeof(reply));
1790 +                    pptp_reset_timer(); /* give sender a chance for a retry */
1791 +                } else { /* same or greater version */
1792 +                    if (pptp_send_ctrl_packet(conn, &reply, sizeof(reply))) {
1793 +                        conn->conn_state = CONN_ESTABLISHED;
1794 +                        dbglog("server connection ESTABLISHED.");
1795 +                        pptp_reset_timer();
1796 +                    }
1797 +                }
1798 +            }
1799 +            break;
1800 +        }
1801 +        case PPTP_START_CTRL_CONN_RPLY:
1802 +        {
1803 +            struct pptp_start_ctrl_conn *packet =
1804 +                (struct pptp_start_ctrl_conn *) buffer;
1805 +            dbglog("Received Start Control Connection Reply");
1806 +            if (conn->conn_state == CONN_WAIT_CTL_REPLY) {
1807 +                /* XXX handle collision XXX [see rfc] */
1808 +                if (ntoh16(packet->version) != PPTP_VERSION) {
1809 +                    if (conn->callback != NULL)
1810 +                        conn->callback(conn, CONN_OPEN_FAIL);
1811 +                    close_reason = PPTP_STOP_PROTOCOL;
1812 +                    goto pptp_conn_close;
1813 +                }
1814 +                if (ntoh8(packet->result_code) != 1 &&
1815 +                    /* J'ai change le if () afin que la connection ne se ferme
1816 +                     * pas pour un "rien" :p adel@cybercable.fr -
1817 +                     *
1818 +                     * Don't close the connection if the result code is zero
1819 +                     * (feature found in certain ADSL modems)
1820 +                     */
1821 +                        ntoh8(packet->result_code) != 0) {
1822 +                    dbglog("Negative reply received to our Start Control "
1823 +                            "Connection Request");
1824 +                    ctrlp_error(packet->result_code, packet->error_code,
1825 +                            -1, pptp_start_ctrl_conn_rply,
1826 +                            MAX_START_CTRL_CONN_REPLY);
1827 +                    if (conn->callback != NULL)
1828 +                        conn->callback(conn, CONN_OPEN_FAIL);
1829 +                    close_reason = PPTP_STOP_PROTOCOL;
1830 +                    goto pptp_conn_close;
1831 +                }
1832 +                conn->conn_state = CONN_ESTABLISHED;
1833 +                /* log session properties */
1834 +                conn->version      = ntoh16(packet->version);
1835 +                conn->firmware_rev = ntoh16(packet->firmware_rev);
1836 +                memcpy(conn->hostname, packet->hostname, sizeof(conn->hostname));
1837 +                memcpy(conn->vendor, packet->vendor, sizeof(conn->vendor));
1838 +                pptp_reset_timer(); /* 60 seconds until keep-alive */
1839 +                dbglog("Client connection established.");
1840 +                if (conn->callback != NULL)
1841 +                    conn->callback(conn, CONN_OPEN_DONE);
1842 +            } /* else goto pptp_conn_close; */
1843 +            break;
1844 +        }
1845 +            /* ----------- STANDARD Stop-Session MESSAGES ------------ */
1846 +        case PPTP_STOP_CTRL_CONN_RQST:
1847 +        {
1848 +            /* conn_state should be CONN_ESTABLISHED, but it could be
1849 +             * something else */
1850 +            struct pptp_stop_ctrl_conn reply = {
1851 +                PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RPLY),
1852 +                hton8(1), hton8(PPTP_GENERAL_ERROR_NONE), 0
1853 +            };
1854 +            dbglog("Received Stop Control Connection Request.");
1855 +            if (conn->conn_state == CONN_IDLE) break;
1856 +            if (pptp_send_ctrl_packet(conn, &reply, sizeof(reply))) {
1857 +                if (conn->callback != NULL)
1858 +                    conn->callback(conn, CONN_CLOSE_RQST);
1859 +                conn->conn_state = CONN_IDLE;
1860 +               return -1;
1861 +            }
1862 +            break;
1863 +        }
1864 +        case PPTP_STOP_CTRL_CONN_RPLY:
1865 +        {
1866 +            dbglog("Received Stop Control Connection Reply.");
1867 +            /* conn_state should be CONN_WAIT_STOP_REPLY, but it
1868 +             * could be something else */
1869 +            if (conn->conn_state == CONN_IDLE) break;
1870 +            conn->conn_state = CONN_IDLE;
1871 +           return -1;
1872 +        }
1873 +            /* ----------- STANDARD Echo/Keepalive MESSAGES ------------ */
1874 +        case PPTP_ECHO_RPLY:
1875 +        {
1876 +            struct pptp_echo_rply *packet =
1877 +                (struct pptp_echo_rply *) buffer;
1878 +            logecho( PPTP_ECHO_RPLY);
1879 +            if ((conn->ka_state == KA_OUTSTANDING) &&
1880 +                    (ntoh32(packet->identifier) == conn->ka_id)) {
1881 +                conn->ka_id++;
1882 +                conn->ka_state = KA_NONE;
1883 +                pptp_reset_timer();
1884 +            }
1885 +            break;
1886 +        }
1887 +        case PPTP_ECHO_RQST:
1888 +        {
1889 +            struct pptp_echo_rqst *packet =
1890 +                (struct pptp_echo_rqst *) buffer;
1891 +            struct pptp_echo_rply reply = {
1892 +                PPTP_HEADER_CTRL(PPTP_ECHO_RPLY),
1893 +                packet->identifier, /* skip hton32(ntoh32(id)) */
1894 +                hton8(1), hton8(PPTP_GENERAL_ERROR_NONE), 0
1895 +            };
1896 +            logecho( PPTP_ECHO_RQST);
1897 +            pptp_send_ctrl_packet(conn, &reply, sizeof(reply));
1898 +            pptp_reset_timer();
1899 +            break;
1900 +        }
1901 +            /* ----------- OUTGOING CALL MESSAGES ------------ */
1902 +        case PPTP_OUT_CALL_RQST:
1903 +        {
1904 +            struct pptp_out_call_rqst *packet =
1905 +                (struct pptp_out_call_rqst *)buffer;
1906 +            struct pptp_out_call_rply reply = {
1907 +                PPTP_HEADER_CTRL(PPTP_OUT_CALL_RPLY),
1908 +                0 /* callid */, packet->call_id, 1, PPTP_GENERAL_ERROR_NONE, 0,
1909 +                hton32(PPTP_CONNECT_SPEED),
1910 +                hton16(PPTP_WINDOW), hton16(PPTP_DELAY), 0
1911 +            };
1912 +            dbglog("Received Outgoing Call Request.");
1913 +            /* XXX PAC: eventually this should make an outgoing call. XXX */
1914 +            reply.result_code = hton8(7); /* outgoing calls verboten */
1915 +            pptp_send_ctrl_packet(conn, &reply, sizeof(reply));
1916 +            break;
1917 +        }
1918 +        case PPTP_OUT_CALL_RPLY:
1919 +        {
1920 +            struct pptp_out_call_rply *packet =
1921 +                (struct pptp_out_call_rply *)buffer;
1922 +            PPTP_CALL * call;
1923 +            u_int16_t callid = ntoh16(packet->call_id_peer);
1924 +            dbglog("Received Outgoing Call Reply.");
1925 +            if (!vector_search(conn->call, (int) callid, &call)) {
1926 +                dbglog("PPTP_OUT_CALL_RPLY received for non-existant call: "
1927 +                        "peer call ID (us)  %d call ID (them) %d.",
1928 +                        callid, ntoh16(packet->call_id));
1929 +                break;
1930 +            }
1931 +            if (call->call_type != PPTP_CALL_PNS) {
1932 +                dbglog("Ack!  How did this call_type get here?"); /* XXX? */
1933 +                break;
1934 +            }
1935 +            if (call->state.pns != PNS_WAIT_REPLY) {
1936 +                warn("Unexpected(?) Outgoing Call Reply will be ignored.");
1937 +                break;
1938 +            }
1939 +            /* check for errors */
1940 +            if (packet->result_code != 1) {
1941 +                /* An error.  Log it verbosely. */
1942 +                dbglog("Our outgoing call request [callid %d] has not been "
1943 +                        "accepted.", (int) callid);
1944 +                ctrlp_error(packet->result_code, packet->error_code,
1945 +                        packet->cause_code, pptp_out_call_reply_result,
1946 +                        MAX_OUT_CALL_REPLY_RESULT);
1947 +                call->state.pns = PNS_IDLE;
1948 +                if (call->callback != NULL)
1949 +                    call->callback(conn, call, CALL_OPEN_FAIL);
1950 +                pptp_call_destroy(conn, call);
1951 +            } else {
1952 +                /* connection established */
1953 +                call->state.pns = PNS_ESTABLISHED;
1954 +                call->peer_call_id = ntoh16(packet->call_id);
1955 +                call->speed        = ntoh32(packet->speed);
1956 +                pptp_reset_timer();
1957 +                /* call pptp_set_link. unless the user specified a quirk
1958 +                   and this quirk has a set_link hook, this is a noop */
1959 +                pptp_set_link(conn, call->peer_call_id);
1960 +                if (call->callback != NULL)
1961 +                    call->callback(conn, call, CALL_OPEN_DONE);
1962 +                dbglog("Outgoing call established (call ID %u, peer's "
1963 +                        "call ID %u).\n", call->call_id, call->peer_call_id);
1964 +            }
1965 +            break;
1966 +        }
1967 +            /* ----------- INCOMING CALL MESSAGES ------------ */
1968 +            /* XXX write me XXX */
1969 +            /* ----------- CALL CONTROL MESSAGES ------------ */
1970 +        case PPTP_CALL_CLEAR_RQST:
1971 +        {
1972 +            struct pptp_call_clear_rqst *packet =
1973 +                (struct pptp_call_clear_rqst *)buffer;
1974 +            struct pptp_call_clear_ntfy reply = {
1975 +                PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_NTFY), packet->call_id,
1976 +                1, PPTP_GENERAL_ERROR_NONE, 0, 0, {0}
1977 +            };
1978 +            dbglog("Received Call Clear Request.");
1979 +            if (vector_contains(conn->call, ntoh16(packet->call_id))) {
1980 +                PPTP_CALL * call;
1981 +                vector_search(conn->call, ntoh16(packet->call_id), &call);
1982 +                if (call->callback != NULL)
1983 +                    call->callback(conn, call, CALL_CLOSE_RQST);
1984 +                pptp_send_ctrl_packet(conn, &reply, sizeof(reply));
1985 +                pptp_call_destroy(conn, call);
1986 +                dbglog("Call closed (RQST) (call id %d)", (int) call->call_id);
1987 +            }
1988 +            break;
1989 +        }
1990 +        case PPTP_CALL_CLEAR_NTFY:
1991 +        {
1992 +            struct pptp_call_clear_ntfy *packet =
1993 +                (struct pptp_call_clear_ntfy *)buffer;
1994 +            dbglog("Call disconnect notification received (call id %d)",
1995 +                    ntoh16(packet->call_id));
1996 +            if (vector_contains(conn->call, ntoh16(packet->call_id))) {
1997 +                PPTP_CALL * call;
1998 +                ctrlp_error(packet->result_code, packet->error_code,
1999 +                        packet->cause_code, pptp_call_disc_ntfy,
2000 +                        MAX_CALL_DISC_NTFY);
2001 +                vector_search(conn->call, ntoh16(packet->call_id), &call);
2002 +                pptp_call_destroy(conn, call);
2003 +            }
2004 +            /* XXX we could log call stats here XXX */
2005 +            /* XXX not all servers send this XXX */
2006 +            break;
2007 +        }
2008 +        case PPTP_SET_LINK_INFO:
2009 +        {
2010 +            /* I HAVE NO CLUE WHAT TO DO IF send_accm IS NOT 0! */
2011 +            /* this is really dealt with in the HDLC deencapsulation, anyway. */
2012 +            struct pptp_set_link_info *packet =
2013 +                (struct pptp_set_link_info *)buffer;
2014 +            /* log it. */
2015 +            dbglog("PPTP_SET_LINK_INFO received from peer_callid %u",
2016 +                    (unsigned int) ntoh16(packet->call_id_peer));
2017 +            dbglog("  send_accm is %08lX, recv_accm is %08lX",
2018 +                    (unsigned long) ntoh32(packet->send_accm),
2019 +                    (unsigned long) ntoh32(packet->recv_accm));
2020 +            if (!(ntoh32(packet->send_accm) == 0 &&
2021 +                    ntoh32(packet->recv_accm) == 0))
2022 +                warn("Non-zero Async Control Character Maps are not supported!");
2023 +            break;
2024 +        }
2025 +        default:
2026 +            dbglog("Unrecognized Packet %d received.",
2027 +                    (int) ntoh16(((struct pptp_header *)buffer)->ctrl_type));
2028 +            /* goto pptp_conn_close; */
2029 +            break;
2030 +    }
2031 +    return 0;
2032 +pptp_conn_close:
2033 +    warn("pptp_conn_close(%d)", (int) close_reason);
2034 +    pptp_conn_close(conn, close_reason);
2035 +    return 0;
2036 +}
2037 +
2038 +/*** pptp_set_link **************************************************************/
2039 +void pptp_set_link(PPTP_CONN* conn, int peer_call_id)
2040 +{
2041 +    int idx, rc;
2042 +    /* if we need to send a set_link packet because of buggy
2043 +       hardware or pptp server, do it now */
2044 +    if ((idx = get_quirk_index()) != -1 && pptp_fixups[idx].set_link_hook) {
2045 +        struct pptp_set_link_info packet;
2046 +        if ((rc = pptp_fixups[idx].set_link_hook(&packet, peer_call_id)))
2047 +            warn("calling the set_link hook failed (%d)", rc);
2048 +        if (pptp_send_ctrl_packet(conn, &packet, sizeof(packet))) {
2049 +            pptp_reset_timer();
2050 +        }
2051 +    }
2052 +}
2053 +
2054 +/*** Get info from call structure *********************************************/
2055 +/* NOTE: The peer_call_id is undefined until we get a server response. */
2056 +void pptp_call_get_ids(PPTP_CONN * conn, PPTP_CALL * call,
2057 +                      u_int16_t * call_id, u_int16_t * peer_call_id)
2058 +{
2059 +    assert(conn != NULL); assert(call != NULL);
2060 +    *call_id = call->call_id;
2061 +    *peer_call_id = call->peer_call_id;
2062 +}
2063 +
2064 +/*** pptp_call_closure_put ****************************************************/
2065 +void   pptp_call_closure_put(PPTP_CONN * conn, PPTP_CALL * call, void *cl)
2066 +{
2067 +    assert(conn != NULL); assert(call != NULL);
2068 +    call->closure = cl;
2069 +}
2070 +
2071 +/*** pptp_call_closure_get ****************************************************/
2072 +void * pptp_call_closure_get(PPTP_CONN * conn, PPTP_CALL * call)
2073 +{
2074 +    assert(conn != NULL); assert(call != NULL);
2075 +    return call->closure;
2076 +}
2077 +
2078 +/*** pptp_conn_closure_put ****************************************************/
2079 +void   pptp_conn_closure_put(PPTP_CONN * conn, void *cl)
2080 +{
2081 +    assert(conn != NULL);
2082 +    conn->closure = cl;
2083 +}
2084 +
2085 +/*** pptp_conn_closure_get ****************************************************/
2086 +void * pptp_conn_closure_get(PPTP_CONN * conn)
2087 +{
2088 +    assert(conn != NULL);
2089 +    return conn->closure;
2090 +}
2091 +
2092 +/*** Reset keep-alive timer ***************************************************/
2093 +static void pptp_reset_timer(void)
2094 +{
2095 +    const struct itimerval tv = { {  0, 0 },   /* stop on time-out */
2096 +        { idle_wait, 0 } };
2097 +    if (idle_wait) setitimer(ITIMER_REAL, &tv, NULL);
2098 +}
2099 +
2100 +
2101 +/*** Handle keep-alive timer **************************************************/
2102 +static void pptp_handle_timer()
2103 +{
2104 +    int i;
2105 +    /* "Keep Alives and Timers, 1": check connection state */
2106 +    if (global.conn->conn_state != CONN_ESTABLISHED) {
2107 +        if (global.conn->conn_state == CONN_WAIT_STOP_REPLY)
2108 +            /* hard close. */
2109 +            pptp_conn_destroy(global.conn);
2110 +        else /* soft close */
2111 +            pptp_conn_close(global.conn, PPTP_STOP_NONE);
2112 +    }
2113 +    /* "Keep Alives and Timers, 2": check echo status */
2114 +    if (global.conn->ka_state == KA_OUTSTANDING) {
2115 +        /* no response to keep-alive */
2116 +        info("closing control connection due to missing echo reply");
2117 +       pptp_conn_close(global.conn, PPTP_STOP_NONE);
2118 +    } else { /* ka_state == NONE */ /* send keep-alive */
2119 +        struct pptp_echo_rqst rqst = {
2120 +            PPTP_HEADER_CTRL(PPTP_ECHO_RQST), hton32(global.conn->ka_id) };
2121 +        pptp_send_ctrl_packet(global.conn, &rqst, sizeof(rqst));
2122 +        global.conn->ka_state = KA_OUTSTANDING;
2123 +    }
2124 +    /* check incoming/outgoing call states for !IDLE && !ESTABLISHED */
2125 +    for (i = 0; i < vector_size(global.conn->call); i++) {
2126 +        PPTP_CALL * call = vector_get_Nth(global.conn->call, i);
2127 +        if (call->call_type == PPTP_CALL_PNS) {
2128 +            if (call->state.pns == PNS_WAIT_REPLY) {
2129 +                /* send close request */
2130 +                pptp_call_close(global.conn, call);
2131 +                assert(call->state.pns == PNS_WAIT_DISCONNECT);
2132 +            } else if (call->state.pns == PNS_WAIT_DISCONNECT) {
2133 +                /* hard-close the call */
2134 +                pptp_call_destroy(global.conn, call);
2135 +            }
2136 +        } else if (call->call_type == PPTP_CALL_PAC) {
2137 +            if (call->state.pac == PAC_WAIT_REPLY) {
2138 +                /* XXX FIXME -- drop the PAC connection XXX */
2139 +            } else if (call->state.pac == PAC_WAIT_CS_ANS) {
2140 +                /* XXX FIXME -- drop the PAC connection XXX */
2141 +            }
2142 +        }
2143 +    }
2144 +    pptp_reset_timer();
2145 +}
2146 --- /dev/null
2147 +++ b/pppd/plugins/pptp/pptp_ctrl.h
2148 @@ -0,0 +1,57 @@
2149 +/* pptp_ctrl.h ... handle PPTP control connection.
2150 + *                 C. Scott Ananian <cananian@alumni.princeton.edu>
2151 + *
2152 + * $Id: pptp_ctrl.h,v 1.5 2004/11/09 01:42:32 quozl Exp $
2153 + */
2154 +
2155 +#ifndef INC_PPTP_CTRL_H
2156 +#define INC_PPTP_CTRL_H
2157 +#include <sys/types.h>
2158 +
2159 +typedef struct PPTP_CONN PPTP_CONN;
2160 +typedef struct PPTP_CALL PPTP_CALL;
2161 +
2162 +enum call_state { CALL_OPEN_RQST,  CALL_OPEN_DONE, CALL_OPEN_FAIL,
2163 +                 CALL_CLOSE_RQST, CALL_CLOSE_DONE };
2164 +enum conn_state { CONN_OPEN_RQST,  CONN_OPEN_DONE, CONN_OPEN_FAIL,
2165 +                 CONN_CLOSE_RQST, CONN_CLOSE_DONE };
2166 +
2167 +typedef void (*pptp_call_cb)(PPTP_CONN*, PPTP_CALL*, enum call_state);
2168 +typedef void (*pptp_conn_cb)(PPTP_CONN*, enum conn_state);
2169 +
2170 +/* if 'isclient' is true, then will send 'conn open' packet to other host.
2171 + * not necessary if this is being opened by a server process after
2172 + * receiving a conn_open packet from client.
2173 + */
2174 +PPTP_CONN * pptp_conn_open(int inet_sock, int isclient,
2175 +                          pptp_conn_cb callback);
2176 +PPTP_CALL * pptp_call_open(PPTP_CONN * conn, int call_id,
2177 +                          pptp_call_cb callback, char *phonenr,int window);
2178 +int pptp_conn_established(PPTP_CONN * conn);
2179 +/* soft close.  Will callback on completion. */
2180 +void pptp_call_close(PPTP_CONN * conn, PPTP_CALL * call);
2181 +/* hard close. */
2182 +void pptp_call_destroy(PPTP_CONN *conn, PPTP_CALL *call);
2183 +/* soft close.  Will callback on completion. */
2184 +void pptp_conn_close(PPTP_CONN * conn, u_int8_t close_reason);
2185 +/* hard close */
2186 +void pptp_conn_destroy(PPTP_CONN * conn);
2187 +
2188 +/* Add file descriptors used by pptp to fd_set. */
2189 +void pptp_fd_set(PPTP_CONN * conn, fd_set * read_set, fd_set * write_set, int *max_fd);
2190 +/* handle any pptp file descriptors set in fd_set, and clear them */
2191 +int pptp_dispatch(PPTP_CONN * conn, fd_set * read_set, fd_set * write_set);
2192 +
2193 +/* Get info about connection, call */
2194 +void pptp_call_get_ids(PPTP_CONN * conn, PPTP_CALL * call,
2195 +                      u_int16_t * call_id, u_int16_t * peer_call_id);
2196 +/* Arbitrary user data about this call/connection.
2197 + * It is the caller's responsibility to free this data before calling
2198 + * pptp_call|conn_close()
2199 + */
2200 +void * pptp_conn_closure_get(PPTP_CONN * conn);
2201 +void   pptp_conn_closure_put(PPTP_CONN * conn, void *cl);
2202 +void * pptp_call_closure_get(PPTP_CONN * conn, PPTP_CALL * call);
2203 +void   pptp_call_closure_put(PPTP_CONN * conn, PPTP_CALL * call, void *cl);
2204 +
2205 +#endif /* INC_PPTP_CTRL_H */
2206 --- /dev/null
2207 +++ b/pppd/plugins/pptp/pptp_msg.h
2208 @@ -0,0 +1,303 @@
2209 +/*  pptp.h:  packet structures and magic constants for the PPTP protocol 
2210 + *           C. Scott Ananian <cananian@alumni.princeton.edu>            
2211 + *
2212 + * $Id: pptp_msg.h,v 1.3 2003/02/15 10:37:21 quozl Exp $
2213 + */
2214 +
2215 +#ifndef INC_PPTP_H
2216 +#define INC_PPTP_H
2217 +
2218 +/* Grab definitions of int16, int32, etc. */
2219 +#include <sys/types.h>
2220 +/* define "portable" htons, etc. */
2221 +#define hton8(x)  (x)
2222 +#define ntoh8(x)  (x)
2223 +#define hton16(x) htons(x)
2224 +#define ntoh16(x) ntohs(x)
2225 +#define hton32(x) htonl(x)
2226 +#define ntoh32(x) ntohl(x)
2227 +
2228 +/* PPTP magic numbers: ----------------------------------------- */
2229 +
2230 +#define PPTP_MAGIC 0x1A2B3C4D /* Magic cookie for PPTP datagrams */
2231 +#define PPTP_PORT  1723       /* PPTP TCP port number            */
2232 +#define PPTP_PROTO 47         /* PPTP IP protocol number         */
2233 +
2234 +/* Control Connection Message Types: --------------------------- */
2235 +
2236 +#define PPTP_MESSAGE_CONTROL           1
2237 +#define PPTP_MESSAGE_MANAGE            2
2238 +
2239 +/* Control Message Types: -------------------------------------- */
2240 +
2241 +/* (Control Connection Management) */
2242 +#define PPTP_START_CTRL_CONN_RQST      1
2243 +#define PPTP_START_CTRL_CONN_RPLY      2
2244 +#define PPTP_STOP_CTRL_CONN_RQST       3
2245 +#define PPTP_STOP_CTRL_CONN_RPLY       4
2246 +#define PPTP_ECHO_RQST                 5
2247 +#define PPTP_ECHO_RPLY                 6
2248 +
2249 +/* (Call Management) */
2250 +#define PPTP_OUT_CALL_RQST             7
2251 +#define PPTP_OUT_CALL_RPLY             8
2252 +#define PPTP_IN_CALL_RQST              9
2253 +#define PPTP_IN_CALL_RPLY              10
2254 +#define PPTP_IN_CALL_CONNECT           11
2255 +#define PPTP_CALL_CLEAR_RQST           12
2256 +#define PPTP_CALL_CLEAR_NTFY           13
2257 +
2258 +/* (Error Reporting) */
2259 +#define PPTP_WAN_ERR_NTFY              14
2260 +
2261 +/* (PPP Session Control) */
2262 +#define PPTP_SET_LINK_INFO             15
2263 +
2264 +/* PPTP version information: --------------------------------------*/
2265 +#define PPTP_VERSION_STRING    "1.00"
2266 +#define PPTP_VERSION           0x100
2267 +#define PPTP_FIRMWARE_STRING   "0.01"
2268 +#define PPTP_FIRMWARE_VERSION  0x001
2269 +
2270 +/* PPTP capabilities: ---------------------------------------------*/
2271 +
2272 +/* (Framing capabilities for msg sender) */
2273 +#define PPTP_FRAME_ASYNC       1
2274 +#define PPTP_FRAME_SYNC                2
2275 +#define PPTP_FRAME_ANY          3
2276 +
2277 +/* (Bearer capabilities for msg sender) */
2278 +#define PPTP_BEARER_ANALOG     1
2279 +#define PPTP_BEARER_DIGITAL    2
2280 +#define PPTP_BEARER_ANY                3
2281 +
2282 +#define PPTP_RESULT_GENERAL_ERROR 2
2283 +
2284 +/* (Reasons to close a connection) */
2285 +#define PPTP_STOP_NONE           1 /* no good reason                        */
2286 +#define PPTP_STOP_PROTOCOL       2 /* can't support peer's protocol version */
2287 +#define PPTP_STOP_LOCAL_SHUTDOWN  3 /* requester is being shut down          */
2288 +
2289 +/* PPTP datagram structures (all data in network byte order): ----------*/
2290 +
2291 +struct pptp_header {
2292 +  u_int16_t length;      /* message length in octets, including header */
2293 +  u_int16_t pptp_type;   /* PPTP message type. 1 for control message.  */
2294 +  u_int32_t magic;       /* this should be PPTP_MAGIC.                 */
2295 +  u_int16_t ctrl_type;   /* Control message type (0-15)                */
2296 +  u_int16_t reserved0;   /* reserved.  MUST BE ZERO.                   */
2297 +};
2298 +
2299 +struct pptp_start_ctrl_conn { /* for control message types 1 and 2 */
2300 +  struct pptp_header header;
2301 +
2302 +  u_int16_t version;      /* PPTP protocol version.  = PPTP_VERSION     */
2303 +  u_int8_t  result_code;  /* these two fields should be zero on rqst msg*/
2304 +  u_int8_t  error_code;   /* 0 unless result_code==2 (General Error)    */
2305 +  u_int32_t framing_cap;  /* Framing capabilities                       */
2306 +  u_int32_t bearer_cap;   /* Bearer Capabilities                        */
2307 +  u_int16_t max_channels; /* Maximum Channels (=0 for PNS, PAC ignores) */
2308 +  u_int16_t firmware_rev; /* Firmware or Software Revision              */
2309 +  u_int8_t  hostname[64]; /* Host Name (64 octets, zero terminated)     */
2310 +  u_int8_t  vendor[64];   /* Vendor string (64 octets, zero term.)      */
2311 +  /* MS says that end of hostname/vendor fields should be filled with   */
2312 +  /* octets of value 0, but Win95 PPTP driver doesn't do this.          */
2313 +};
2314 +
2315 +struct pptp_stop_ctrl_conn { /* for control message types 3 and 4 */
2316 +  struct pptp_header header;
2317 +
2318 +  u_int8_t reason_result; /* reason for rqst, result for rply          */
2319 +  u_int8_t error_code;   /* MUST be 0, unless rply result==2 (general err)*/
2320 +  u_int16_t reserved1;    /* MUST be 0                                */
2321 +};
2322 +
2323 +struct pptp_echo_rqst { /* for control message type 5 */
2324 +  struct pptp_header header;
2325 +  u_int32_t identifier;   /* arbitrary value set by sender which is used */
2326 +                          /* to match up reply and request               */
2327 +};
2328 +
2329 +struct pptp_echo_rply { /* for control message type 6 */
2330 +  struct pptp_header header;
2331 +  u_int32_t identifier;          /* should correspond to id of rqst             */
2332 +  u_int8_t result_code;
2333 +  u_int8_t error_code;    /* =0, unless result_code==2 (general error)   */
2334 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2335 +};
2336 +
2337 +struct pptp_out_call_rqst { /* for control message type 7 */
2338 +  struct pptp_header header;
2339 +  u_int16_t call_id;     /* Call ID (unique id used to multiplex data)  */
2340 +  u_int16_t call_sernum;  /* Call Serial Number (used for logging)       */
2341 +  u_int32_t bps_min;      /* Minimum BPS (lowest acceptable line speed)  */
2342 +  u_int32_t bps_max;     /* Maximum BPS (highest acceptable line speed) */
2343 +  u_int32_t bearer;      /* Bearer type                                 */
2344 +  u_int32_t framing;      /* Framing type                                */
2345 +  u_int16_t recv_size;   /* Recv. Window Size (no. of buffered packets) */
2346 +  u_int16_t delay;       /* Packet Processing Delay (in 1/10 sec)       */
2347 +  u_int16_t phone_len;   /* Phone Number Length (num. of valid digits)  */
2348 +  u_int16_t reserved1;    /* MUST BE ZERO                               */
2349 +  u_int8_t  phone_num[64]; /* Phone Number (64 octets, null term.)       */
2350 +  u_int8_t subaddress[64]; /* Subaddress (64 octets, null term.)         */
2351 +};
2352 +
2353 +struct pptp_out_call_rply { /* for control message type 8 */
2354 +  struct pptp_header header;
2355 +  u_int16_t call_id;      /* Call ID (used to multiplex data over tunnel)*/
2356 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/
2357 +  u_int8_t  result_code;  /* Result Code (1 is no errors)                */
2358 +  u_int8_t  error_code;   /* Error Code (=0 unless result_code==2)       */
2359 +  u_int16_t cause_code;   /* Cause Code (addt'l failure information)     */
2360 +  u_int32_t speed;        /* Connect Speed (in BPS)                      */
2361 +  u_int16_t recv_size;    /* Recv. Window Size (no. of buffered packets) */
2362 +  u_int16_t delay;       /* Packet Processing Delay (in 1/10 sec)       */
2363 +  u_int32_t channel;      /* Physical Channel ID (for logging)           */
2364 +};
2365 +
2366 +struct pptp_in_call_rqst { /* for control message type 9 */
2367 +  struct pptp_header header;
2368 +  u_int16_t call_id;     /* Call ID (unique id used to multiplex data)  */
2369 +  u_int16_t call_sernum;  /* Call Serial Number (used for logging)       */
2370 +  u_int32_t bearer;      /* Bearer type                                 */
2371 +  u_int32_t channel;      /* Physical Channel ID (for logging)           */
2372 +  u_int16_t dialed_len;   /* Dialed Number Length (# of valid digits)    */
2373 +  u_int16_t dialing_len;  /* Dialing Number Length (# of valid digits)   */
2374 +  u_int8_t dialed_num[64]; /* Dialed Number (64 octets, zero term.)      */
2375 +  u_int8_t dialing_num[64]; /* Dialing Number (64 octets, zero term.)    */
2376 +  u_int8_t subaddress[64];  /* Subaddress (64 octets, zero term.)        */
2377 +};
2378 +
2379 +struct pptp_in_call_rply { /* for control message type 10 */
2380 +  struct pptp_header header;
2381 +  u_int16_t call_id;      /* Call ID (used to multiplex data over tunnel)*/
2382 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/
2383 +  u_int8_t  result_code;  /* Result Code (1 is no errors)                */
2384 +  u_int8_t  error_code;   /* Error Code (=0 unless result_code==2)       */
2385 +  u_int16_t recv_size;    /* Recv. Window Size (no. of buffered packets) */
2386 +  u_int16_t delay;       /* Packet Processing Delay (in 1/10 sec)       */
2387 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2388 +};
2389 +
2390 +struct pptp_in_call_connect { /* for control message type 11 */
2391 +  struct pptp_header header;
2392 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/
2393 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2394 +  u_int32_t speed;        /* Connect Speed (in BPS)                      */
2395 +  u_int16_t recv_size;    /* Recv. Window Size (no. of buffered packets) */
2396 +  u_int16_t delay;       /* Packet Processing Delay (in 1/10 sec)       */
2397 +  u_int32_t framing;      /* Framing type                                */
2398 +};
2399 +
2400 +struct pptp_call_clear_rqst { /* for control message type 12 */
2401 +  struct pptp_header header;
2402 +  u_int16_t call_id;      /* Call ID (used to multiplex data over tunnel)*/
2403 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2404 +};
2405 +
2406 +struct pptp_call_clear_ntfy { /* for control message type 13 */
2407 +  struct pptp_header header;
2408 +  u_int16_t call_id;      /* Call ID (used to multiplex data over tunnel)*/
2409 +  u_int8_t  result_code;  /* Result Code                                 */
2410 +  u_int8_t  error_code;   /* Error Code (=0 unless result_code==2)       */
2411 +  u_int16_t cause_code;   /* Cause Code (for ISDN, is Q.931 cause code)  */
2412 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2413 +  u_int8_t call_stats[128]; /* Call Statistics: 128 octets, ascii, 0-term */
2414 +};
2415 +
2416 +struct pptp_wan_err_ntfy {    /* for control message type 14 */
2417 +  struct pptp_header header;
2418 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/
2419 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2420 +  u_int32_t crc_errors;   /* CRC errors                                 */
2421 +  u_int32_t frame_errors; /* Framing errors                             */
2422 +  u_int32_t hard_errors;  /* Hardware overruns                                  */
2423 +  u_int32_t buff_errors;  /* Buffer overruns                            */
2424 +  u_int32_t time_errors;  /* Time-out errors                            */
2425 +  u_int32_t align_errors; /* Alignment errors                           */
2426 +};
2427 +
2428 +struct pptp_set_link_info {   /* for control message type 15 */
2429 +  struct pptp_header header;
2430 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst) */
2431 +  u_int16_t reserved1;    /* MUST BE ZERO                                   */
2432 +  u_int32_t send_accm;    /* Send ACCM (for PPP packets; default 0xFFFFFFFF)*/
2433 +  u_int32_t recv_accm;    /* Receive ACCM (for PPP pack.;default 0xFFFFFFFF)*/
2434 +};
2435 +
2436 +/* helpful #defines: -------------------------------------------- */
2437 +#define pptp_isvalid_ctrl(header, type, length) \
2438 + (!( ( ntoh16(((struct pptp_header *)header)->length)    < (length)  ) ||   \
2439 +     ( ntoh16(((struct pptp_header *)header)->pptp_type) !=(type)    ) ||   \
2440 +     ( ntoh32(((struct pptp_header *)header)->magic)     !=PPTP_MAGIC) ||   \
2441 +     ( ntoh16(((struct pptp_header *)header)->ctrl_type) > PPTP_SET_LINK_INFO) || \
2442 +     ( ntoh16(((struct pptp_header *)header)->reserved0) !=0         ) ))
2443 +
2444 +#define PPTP_HEADER_CTRL(type)  \
2445 +{ hton16(PPTP_CTRL_SIZE(type)), \
2446 +  hton16(PPTP_MESSAGE_CONTROL), \
2447 +  hton32(PPTP_MAGIC),           \
2448 +  hton16(type), 0 }             
2449 +
2450 +#define PPTP_CTRL_SIZE(type) ( \
2451 +(type==PPTP_START_CTRL_CONN_RQST)?sizeof(struct pptp_start_ctrl_conn): \
2452 +(type==PPTP_START_CTRL_CONN_RPLY)?sizeof(struct pptp_start_ctrl_conn): \
2453 +(type==PPTP_STOP_CTRL_CONN_RQST )?sizeof(struct pptp_stop_ctrl_conn):  \
2454 +(type==PPTP_STOP_CTRL_CONN_RPLY )?sizeof(struct pptp_stop_ctrl_conn):  \
2455 +(type==PPTP_ECHO_RQST           )?sizeof(struct pptp_echo_rqst):       \
2456 +(type==PPTP_ECHO_RPLY           )?sizeof(struct pptp_echo_rply):       \
2457 +(type==PPTP_OUT_CALL_RQST       )?sizeof(struct pptp_out_call_rqst):   \
2458 +(type==PPTP_OUT_CALL_RPLY       )?sizeof(struct pptp_out_call_rply):   \
2459 +(type==PPTP_IN_CALL_RQST        )?sizeof(struct pptp_in_call_rqst):    \
2460 +(type==PPTP_IN_CALL_RPLY        )?sizeof(struct pptp_in_call_rply):    \
2461 +(type==PPTP_IN_CALL_CONNECT     )?sizeof(struct pptp_in_call_connect): \
2462 +(type==PPTP_CALL_CLEAR_RQST     )?sizeof(struct pptp_call_clear_rqst): \
2463 +(type==PPTP_CALL_CLEAR_NTFY     )?sizeof(struct pptp_call_clear_ntfy): \
2464 +(type==PPTP_WAN_ERR_NTFY        )?sizeof(struct pptp_wan_err_ntfy):    \
2465 +(type==PPTP_SET_LINK_INFO       )?sizeof(struct pptp_set_link_info):   \
2466 +0)
2467 +#define max(a,b) (((a)>(b))?(a):(b))
2468 +#define PPTP_CTRL_SIZE_MAX (                   \
2469 +max(sizeof(struct pptp_start_ctrl_conn),       \
2470 +max(sizeof(struct pptp_echo_rqst),             \
2471 +max(sizeof(struct pptp_echo_rply),             \
2472 +max(sizeof(struct pptp_out_call_rqst),         \
2473 +max(sizeof(struct pptp_out_call_rply),         \
2474 +max(sizeof(struct pptp_in_call_rqst),          \
2475 +max(sizeof(struct pptp_in_call_rply),          \
2476 +max(sizeof(struct pptp_in_call_connect),       \
2477 +max(sizeof(struct pptp_call_clear_rqst),       \
2478 +max(sizeof(struct pptp_call_clear_ntfy),       \
2479 +max(sizeof(struct pptp_wan_err_ntfy),          \
2480 +max(sizeof(struct pptp_set_link_info), 0)))))))))))))
2481 +
2482 +
2483 +/* gre header structure: -------------------------------------------- */
2484 +
2485 +#define PPTP_GRE_PROTO  0x880B
2486 +#define PPTP_GRE_VER    0x1
2487 +
2488 +#define PPTP_GRE_FLAG_C        0x80
2489 +#define PPTP_GRE_FLAG_R        0x40
2490 +#define PPTP_GRE_FLAG_K        0x20
2491 +#define PPTP_GRE_FLAG_S        0x10
2492 +#define PPTP_GRE_FLAG_A        0x80
2493 +
2494 +#define PPTP_GRE_IS_C(f) ((f)&PPTP_GRE_FLAG_C)
2495 +#define PPTP_GRE_IS_R(f) ((f)&PPTP_GRE_FLAG_R)
2496 +#define PPTP_GRE_IS_K(f) ((f)&PPTP_GRE_FLAG_K)
2497 +#define PPTP_GRE_IS_S(f) ((f)&PPTP_GRE_FLAG_S)
2498 +#define PPTP_GRE_IS_A(f) ((f)&PPTP_GRE_FLAG_A)
2499 +
2500 +struct pptp_gre_header {
2501 +  u_int8_t flags;              /* bitfield */
2502 +  u_int8_t ver;                        /* should be PPTP_GRE_VER (enhanced GRE) */
2503 +  u_int16_t protocol;          /* should be PPTP_GRE_PROTO (ppp-encaps) */
2504 +  u_int16_t payload_len;       /* size of ppp payload, not inc. gre header */
2505 +  u_int16_t call_id;           /* peer's call_id for this session */
2506 +  u_int32_t seq;               /* sequence number.  Present if S==1 */
2507 +  u_int32_t ack;               /* seq number of highest packet recieved by */
2508 +                               /*  sender in this session */
2509 +};
2510 +
2511 +#endif /* INC_PPTP_H */
2512 --- /dev/null
2513 +++ b/pppd/plugins/pptp/pptp_options.h
2514 @@ -0,0 +1,41 @@
2515 +/* pptp_options.h ...... various constants used in the PPTP protocol.
2516 + *                       #define STANDARD to emulate NT 4.0 exactly.
2517 + *                       C. Scott Ananian <cananian@alumni.princeton.edu>
2518 + *
2519 + * $Id: pptp_options.h,v 1.3 2004/11/09 01:42:32 quozl Exp $
2520 + */
2521 +
2522 +#ifndef INC_PPTP_OPTIONS_H
2523 +#define INC_PPTP_OPTIONS_H
2524 +
2525 +#undef  PPTP_FIRMWARE_STRING
2526 +#undef  PPTP_FIRMWARE_VERSION
2527 +#define PPTP_BUF_MAX 65536
2528 +#define PPTP_TIMEOUT 60 /* seconds */
2529 +extern int idle_wait;
2530 +extern int max_echo_wait;
2531 +#define PPTP_CONNECT_SPEED 1000000000
2532 +#define PPTP_WINDOW 3
2533 +#define PPTP_DELAY  0
2534 +#define PPTP_BPS_MIN 2400
2535 +#define PPTP_BPS_MAX 1000000000
2536 +
2537 +#ifndef STANDARD
2538 +#define PPTP_MAX_CHANNELS 65535
2539 +#define PPTP_FIRMWARE_STRING "0.01"
2540 +#define PPTP_FIRMWARE_VERSION 0x001
2541 +#define PPTP_HOSTNAME {'l','o','c','a','l',0}
2542 +#define PPTP_VENDOR   {'c','a','n','a','n','i','a','n',0}
2543 +#define PPTP_FRAME_CAP  PPTP_FRAME_ANY
2544 +#define PPTP_BEARER_CAP PPTP_BEARER_ANY
2545 +#else
2546 +#define PPTP_MAX_CHANNELS 5
2547 +#define PPTP_FIRMWARE_STRING "0.01"
2548 +#define PPTP_FIRMWARE_VERSION 0
2549 +#define PPTP_HOSTNAME {'l','o','c','a','l',0}
2550 +#define PPTP_VENDOR   {'N','T',0}
2551 +#define PPTP_FRAME_CAP  2
2552 +#define PPTP_BEARER_CAP 1
2553 +#endif
2554 +
2555 +#endif /* INC_PPTP_OPTIONS_H */
2556 --- /dev/null
2557 +++ b/pppd/plugins/pptp/pptp_quirks.c
2558 @@ -0,0 +1,54 @@
2559 +/* pptp_quirks.c ...... various options to fix quirks found in buggy adsl modems
2560 + *                      mulix <mulix@actcom.co.il>
2561 + *
2562 + * $Id: pptp_quirks.c,v 1.2 2001/11/23 03:42:51 quozl Exp $
2563 + */
2564 +
2565 +#include <string.h>
2566 +#include "orckit_quirks.h"
2567 +#include "pptp_quirks.h"
2568 +
2569 +static int quirk_index = -1;
2570 +
2571 +struct pptp_fixup pptp_fixups[] = {
2572 +    {BEZEQ_ISRAEL, ORCKIT, ORCKIT_ATUR3,
2573 +     orckit_atur3_build_hook,
2574 +     orckit_atur3_start_ctrl_conn_hook,
2575 +     orckit_atur3_set_link_hook}
2576 +};
2577 +
2578 +static int fixups_sz = sizeof(pptp_fixups)/sizeof(pptp_fixups[0]);
2579 +
2580 +/* return 0 on success, non 0 otherwise */
2581 +int set_quirk_index(int index)
2582 +{
2583 +    if (index >= 0 && index < fixups_sz) {
2584 +       quirk_index = index;
2585 +       return 0;
2586 +    }
2587 +
2588 +    return -1;
2589 +}
2590 +
2591 +int get_quirk_index()
2592 +{
2593 +    return quirk_index;
2594 +}
2595 +
2596 +/* return the index for this isp in the quirks table, -1 if not found */
2597 +int find_quirk(const char* isp_name)
2598 +{
2599 +    int i = 0;
2600 +    if (isp_name) {
2601 +       while (i < fixups_sz && pptp_fixups[i].isp) {
2602 +           if (!strcmp(pptp_fixups[i].isp, isp_name)) {
2603 +               return i;
2604 +           }
2605 +           ++i;
2606 +       }
2607 +    }
2608 +
2609 +    return -1;
2610 +}
2611 +
2612 +
2613 --- /dev/null
2614 +++ b/pppd/plugins/pptp/pptp_quirks.h
2615 @@ -0,0 +1,59 @@
2616 +/* pptp_quirks.h ...... various options to fix quirks found in buggy adsl modems
2617 + *                      mulix <mulix@actcom.co.il>
2618 + *
2619 + * $Id: pptp_quirks.h,v 1.1 2001/11/20 06:30:10 quozl Exp $
2620 + */
2621 +
2622 +#ifndef INC_PPTP_QUIRKS_H
2623 +#define INC_PPTP_QUIRKS_H
2624 +
2625 +/* isp defs - correspond to slots in the fixups table */
2626 +#define BEZEQ_ISRAEL "BEZEQ_ISRAEL"
2627 +
2628 +/* vendor defs */
2629 +
2630 +#define ORCKIT 1
2631 +#define ALCATEL 2
2632 +
2633 +/* device defs */
2634 +
2635 +#define ORCKIT_ATUR2 1
2636 +#define ORCKIT_ATUR3 2
2637 +
2638 +#include "pptp_msg.h"
2639 +#include "pptp_ctrl.h"
2640 +
2641 +struct pptp_fixup {
2642 +    const char* isp;    /* which isp? e.g. Bezeq in Israel */
2643 +    int vendor; /* which vendor? e.g. Orckit */
2644 +    int device; /* which device? e.g. Orckit Atur3 */
2645 +
2646 +    /* use this hook to build your own out call request packet */
2647 +    int (*out_call_rqst_hook)(struct pptp_out_call_rqst* packet);
2648 +
2649 +    /* use this hook to build your own start control connection packet */
2650 +    /* note that this hook is called from two different places, depending
2651 +       on whether this is a request or reply */
2652 +    int (*start_ctrl_conn)(struct pptp_start_ctrl_conn* packet);
2653 +
2654 +    /* use this hook if you need to send a 'set_link' packet once
2655 +       the connection is established */
2656 +    int (*set_link_hook)(struct pptp_set_link_info* packet,
2657 +                        int peer_call_id);
2658 +};
2659 +
2660 +extern struct pptp_fixup pptp_fixups[];
2661 +
2662 +/* find the index for this isp in the quirks table */
2663 +/* return the index on success, -1 if not found */
2664 +int find_quirk(const char* isp_name);
2665 +
2666 +/* set the global quirk index. return 0 on success, non 0 otherwise */
2667 +int set_quirk_index(int index);
2668 +
2669 +/* get the global quirk index. return the index on success,
2670 +   -1 if no quirk is defined */
2671 +int get_quirk_index();
2672 +
2673 +
2674 +#endif /* INC_PPTP_QUIRKS_H */
2675 --- /dev/null
2676 +++ b/pppd/plugins/pptp/util.c
2677 @@ -0,0 +1,109 @@
2678 +/* util.c ....... error message utilities.
2679 + *                C. Scott Ananian <cananian@alumni.princeton.edu>
2680 + *
2681 + * $Id: util.c,v 1.11 2005/08/22 00:49:48 quozl Exp $
2682 + */
2683 +
2684 +#include <stdio.h>
2685 +#include <stdarg.h>
2686 +#include <syslog.h>
2687 +#include <unistd.h>
2688 +#include <stdlib.h>
2689 +#include "util.h"
2690 +
2691 +#define MAKE_STRING(label)                             \
2692 +va_list ap;                                            \
2693 +char buf[256], string[256];                            \
2694 +va_start(ap, format);                                  \
2695 +vsnprintf(buf, sizeof(buf), format, ap);               \
2696 +snprintf(string, sizeof(string), "%s %s[%s:%s:%d]: %s",        \
2697 +        log_string, label, func, file, line, buf);     \
2698 +va_end(ap)
2699 +
2700 +/*** connect a file to a file descriptor **************************************/
2701 +int file2fd(const char *path, const char *mode, int fd)
2702 +{
2703 +    int ok = 0;
2704 +    FILE *file = NULL;
2705 +    file = fopen(path, mode);
2706 +    if (file != NULL && dup2(fileno(file), fd) != -1)
2707 +        ok = 1;
2708 +    if (file) fclose(file);
2709 +    return ok;
2710 +}
2711 +
2712 +/* signal to pipe delivery implementation */
2713 +#include <unistd.h>
2714 +#include <fcntl.h>
2715 +#include <signal.h>
2716 +#include <string.h>
2717 +
2718 +/* pipe private to process */
2719 +static int sigpipe[2];
2720 +
2721 +/* create a signal pipe, returns 0 for success, -1 with errno for failure */
2722 +int sigpipe_create()
2723 +{
2724 +  int rc;
2725 +  
2726 +  rc = pipe(sigpipe);
2727 +  if (rc < 0) return rc;
2728 +  
2729 +  fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC);
2730 +  fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC);
2731 +  
2732 +#ifdef O_NONBLOCK
2733 +#define FLAG_TO_SET O_NONBLOCK
2734 +#else
2735 +#ifdef SYSV
2736 +#define FLAG_TO_SET O_NDELAY
2737 +#else /* BSD */
2738 +#define FLAG_TO_SET FNDELAY
2739 +#endif
2740 +#endif
2741 +  
2742 +  rc = fcntl(sigpipe[1], F_GETFL);
2743 +  if (rc != -1)
2744 +    rc = fcntl(sigpipe[1], F_SETFL, rc | FLAG_TO_SET);
2745 +  if (rc < 0) return rc;
2746 +  return 0;
2747 +#undef FLAG_TO_SET
2748 +}
2749 +
2750 +/* generic handler for signals, writes signal number to pipe */
2751 +void sigpipe_handler(int signum)
2752 +{
2753 +  write(sigpipe[1], &signum, sizeof(signum));
2754 +  signal(signum, sigpipe_handler);
2755 +}
2756 +
2757 +/* assign a signal number to the pipe */
2758 +void sigpipe_assign(int signum)
2759 +{
2760 +  struct sigaction sa;
2761 +
2762 +  memset(&sa, 0, sizeof(sa));
2763 +  sa.sa_handler = sigpipe_handler;
2764 +  sigaction(signum, &sa, NULL);
2765 +}
2766 +
2767 +/* return the signal pipe read file descriptor for select(2) */
2768 +int sigpipe_fd()
2769 +{
2770 +  return sigpipe[0];
2771 +}
2772 +
2773 +/* read and return the pending signal from the pipe */
2774 +int sigpipe_read()
2775 +{
2776 +  int signum;
2777 +  read(sigpipe[0], &signum, sizeof(signum));
2778 +  return signum;
2779 +}
2780 +
2781 +void sigpipe_close()
2782 +{
2783 +  close(sigpipe[0]);
2784 +  close(sigpipe[1]);
2785 +}
2786 +
2787 --- /dev/null
2788 +++ b/pppd/plugins/pptp/util.h
2789 @@ -0,0 +1,31 @@
2790 +/* util.h ....... error message utilities.
2791 + *                C. Scott Ananian <cananian@alumni.princeton.edu>
2792 + *
2793 + * $Id: util.h,v 1.6 2005/03/10 01:18:20 quozl Exp $
2794 + */
2795 +
2796 +#ifndef INC_UTIL_H
2797 +#define INC_UTIL_H
2798 +
2799 +int file2fd(const char *path, const char *mode, int fd);
2800 +
2801 +/* signal to pipe delivery implementation */
2802 +
2803 +/* create a signal pipe, returns 0 for success, -1 with errno for failure */
2804 +int sigpipe_create();
2805 +
2806 +/* generic handler for signals, writes signal number to pipe */
2807 +void sigpipe_handler(int signum);
2808 +
2809 +/* assign a signal number to the pipe */
2810 +void sigpipe_assign(int signum);
2811 +
2812 +/* return the signal pipe read file descriptor for select(2) */
2813 +int sigpipe_fd();
2814 +
2815 +/* read and return the pending signal from the pipe */
2816 +int sigpipe_read();
2817 +
2818 +void sigpipe_close();
2819 +
2820 +#endif /* INC_UTIL_H */
2821 --- /dev/null
2822 +++ b/pppd/plugins/pptp/vector.c
2823 @@ -0,0 +1,209 @@
2824 +/* vector.c ..... store a vector of PPTP_CALL information and search it
2825 + *                efficiently.
2826 + *                C. Scott Ananian <cananian@alumni.princeton.edu>
2827 + *
2828 + * $Id: vector.c,v 1.3 2003/06/17 10:12:55 reink Exp $
2829 + */
2830 +
2831 +#include <stdlib.h>
2832 +#include <string.h>
2833 +#include <assert.h>
2834 +#include "pptp_ctrl.h"
2835 +#include "vector.h"
2836 +/* #define VECTOR_DEBUG */
2837 +#ifndef TRUE
2838 +#define TRUE 1
2839 +#endif
2840 +#ifndef FALSE
2841 +#define FALSE 0
2842 +#endif
2843 +
2844 +struct vector_item {
2845 +    int key;
2846 +    PPTP_CALL *call;
2847 +};
2848 +
2849 +struct vector_struct {
2850 +    struct vector_item *item;
2851 +    int size;
2852 +    int alloc;
2853 +#ifdef VECTOR_DEBUG
2854 +    int key_max;
2855 +#endif
2856 +};
2857 +
2858 +static struct vector_item *binary_search(VECTOR *v, int key);
2859 +
2860 +/*** vector_create ************************************************************/
2861 +VECTOR *vector_create()
2862 +{
2863 +    const int INITIAL_SIZE = 4;
2864 +
2865 +    VECTOR *v = malloc(sizeof(*v));
2866 +    if (v == NULL) return v;
2867 +
2868 +    v->size = 0;
2869 +    v->alloc = INITIAL_SIZE;
2870 +    v->item = malloc(sizeof(*(v->item)) * (v->alloc));
2871 +#ifdef VECTOR_DEBUG
2872 +    v->key_max = -1;
2873 +#endif
2874 +    if (v->item == NULL) { free(v); return NULL; }
2875 +    else return v;
2876 +}
2877 +
2878 +/*** vector_destroy ***********************************************************/
2879 +void vector_destroy(VECTOR *v)
2880 +{
2881 +    free(v->item);
2882 +#ifdef VECTOR_DEBUG
2883 +    v->item = NULL;
2884 +#endif
2885 +    free(v);
2886 +}
2887 +
2888 +/*** vector_size **************************************************************/
2889 +int vector_size(VECTOR *v)
2890 +{
2891 +    assert(v != NULL);
2892 +    return v->size;
2893 +}
2894 +
2895 +/*** vector_insert*************************************************************
2896 + * nice thing about file descriptors is that we are assured by POSIX 
2897 + * that they are monotonically increasing.
2898 + */
2899 +int vector_insert(VECTOR *v, int key, PPTP_CALL * call)
2900 +{
2901 +    int i;
2902 +    assert(v != NULL && call != NULL);
2903 +    assert(!vector_contains(v, key));
2904 +#ifdef VECTOR_DEBUG
2905 +    assert(v->key_max < key);
2906 +#endif
2907 +    if (!(v->size < v->alloc)) {
2908 +        void *tmp = realloc(v->item, sizeof(*(v->item)) * 2 * v->alloc);
2909 +        if (tmp != NULL) {
2910 +            v->alloc *= 2;
2911 +            v->item = tmp;
2912 +        } else return FALSE; /* failed to alloc memory. */
2913 +    }
2914 +    assert(v->size < v->alloc);
2915 +    /* for safety, we make this work in the general case;
2916 +     * but this is optimized for adding call to the end of the vector.
2917 +     */
2918 +    for(i = v->size - 1; i >= 0; i--)
2919 +        if (v->item[i].key < key)
2920 +            break;
2921 +    /* insert after item i */
2922 +    memmove(&v->item[i + 2], &v->item[i + 1],
2923 +            (v->size - i - 1) * sizeof(*(v->item)));
2924 +    v->item[i + 1].key  = key;
2925 +    v->item[i + 1].call = call;
2926 +    v->size++;
2927 +#ifdef VECTOR_DEBUG
2928 +    if (v->key_max < key) /* ie, always. */
2929 +        v->key_max = key;
2930 +#endif
2931 +    return TRUE;
2932 +}
2933 +
2934 +/*** vector_remove ************************************************************/
2935 +int  vector_remove(VECTOR *v, int key)
2936 +{
2937 +    struct vector_item *tmp;
2938 +    assert(v != NULL);
2939 +    if ((tmp =binary_search(v,key)) == NULL) return FALSE;
2940 +    assert(tmp >= v->item && tmp < v->item + v->size);
2941 +    memmove(tmp, tmp + 1, (v->size - (v->item - tmp) - 1) * sizeof(*(v->item)));
2942 +    v->size--;
2943 +    return TRUE;
2944 +}
2945 +
2946 +/*** vector_search ************************************************************/
2947 +int  vector_search(VECTOR *v, int key, PPTP_CALL **call)
2948 +{
2949 +    struct vector_item *tmp;
2950 +    assert(v != NULL);
2951 +    tmp = binary_search(v, key);
2952 +    if (tmp ==NULL) return FALSE;
2953 +    *call = tmp->call;
2954 +    return TRUE;
2955 +}
2956 +
2957 +/*** vector_contains **********************************************************/
2958 +int  vector_contains(VECTOR *v, int key)
2959 +{
2960 +    assert(v != NULL);
2961 +    return (binary_search(v, key) != NULL);
2962 +}
2963 +
2964 +/*** vector_item **************************************************************/
2965 +static struct vector_item *binary_search(VECTOR *v, int key)
2966 +{
2967 +    int l,r,x;
2968 +    l = 0;
2969 +    r = v->size - 1;
2970 +    while (r >= l) {
2971 +        x = (l + r)/2;
2972 +        if (key <  v->item[x].key) r = x - 1; else l = x + 1;
2973 +        if (key == v->item[x].key) return &(v->item[x]);
2974 +    }
2975 +    return NULL;
2976 +}
2977 +
2978 +/*** vector_scan ***************************************************************
2979 + * Hmm.  Let's be fancy and use a binary search for the first
2980 + * unused key, taking advantage of the list is stored sorted; ie
2981 + * we can look at pointers and keys at two different locations, 
2982 + * and if (ptr1 - ptr2) = (key1 - key2) then all the slots
2983 + * between ptr1 and ptr2 are filled.  Note that ptr1-ptr2 should
2984 + * never be greater than key1-key2 (no duplicate keys!)... we
2985 + * check for this.
2986 + */
2987 +int vector_scan(VECTOR *v, int lo, int hi, int *key)
2988 +{
2989 +    int l,r,x;
2990 +    assert(v != NULL);
2991 +    assert(key != NULL);
2992 +    if ((v->size<1) || (lo < v->item[0].key)) { *key = lo; return TRUE; }
2993 +    /* our array bounds */
2994 +    l = 0;  r = v->size - 1;
2995 +    while (r > l) {
2996 +        /* check for a free spot right after l */
2997 +        if (v->item[l].key + 1 < v->item[l + 1].key) { /* found it! */
2998 +            *key = v->item[l].key + 1;
2999 +            return TRUE;
3000 +        }
3001 +        /* no dice. Let's see if the free spot is before or after the midpoint */
3002 +        x = (l + r)/2;
3003 +        /* Okay, we have right (r), left (l) and the probe (x). */
3004 +        assert(x - l <= v->item[x].key - v->item[l].key);
3005 +        assert(r - x <= v->item[r].key - v->item[x].key);
3006 +        if (x - l < v->item[x].key - v->item[l].key)
3007 +            /* room between l and x */
3008 +            r = x;
3009 +        else /* no room between l and x */
3010 +            if (r - x < v->item[r].key - v->item[x].key)
3011 +                /* room between x and r */
3012 +                l = x;
3013 +            else /* no room between x and r, either */
3014 +                break; /* game over, man. */
3015 +    }
3016 +    /* no room found in already allocated space.  Check to see if
3017 +     * there's free space above allocated entries. */
3018 +    if (v->item[v->size - 1].key < hi) {
3019 +        *key = v->item[v->size - 1].key + 1;
3020 +        return TRUE;
3021 +    }
3022 +    /* outta luck */
3023 +    return FALSE;
3024 +}
3025 +
3026 +/*** vector_get_Nth ***********************************************************/
3027 +PPTP_CALL * vector_get_Nth(VECTOR *v, int n)
3028 +{
3029 +    assert(v != NULL);
3030 +    assert(0 <= n && n < vector_size(v));
3031 +    return v->item[n].call;
3032 +}
3033 --- /dev/null
3034 +++ b/pppd/plugins/pptp/vector.h
3035 @@ -0,0 +1,31 @@
3036 +/* vector.h ..... store a vector of PPTP_CALL information and search it
3037 + *                efficiently.
3038 + *                C. Scott Ananian <cananian@alumni.princeton.edu>
3039 + *
3040 + * $Id: vector.h,v 1.1.1.1 2000/12/23 08:19:51 scott Exp $
3041 + */
3042 +
3043 +#ifndef INC_VECTOR_H
3044 +#define INC_VECTOR_H
3045 +
3046 +#include "pptp_ctrl.h" /* for definition of PPTP_CALL */
3047 +
3048 +typedef struct vector_struct VECTOR;
3049 +
3050 +VECTOR *vector_create();
3051 +void vector_destroy(VECTOR *v);
3052 +
3053 +int vector_size(VECTOR *v);
3054 +
3055 +/* vector_insert and vector_search return TRUE on success, FALSE on failure. */
3056 +int  vector_insert(VECTOR *v, int key, PPTP_CALL * call);
3057 +int  vector_remove(VECTOR *v, int key);
3058 +int  vector_search(VECTOR *v, int key, PPTP_CALL ** call);
3059 +/* vector_contains returns FALSE if not found, TRUE if found. */
3060 +int  vector_contains(VECTOR *v, int key);
3061 +/* find first unused key. Returns TRUE on success, FALSE if no. */
3062 +int  vector_scan(VECTOR *v, int lo, int hi, int *key);
3063 +/* get a specific PPTP_CALL ... useful only when iterating. */
3064 +PPTP_CALL * vector_get_Nth(VECTOR *v, int n);
3065 +
3066 +#endif /* INC_VECTOR_H */