kernel: fq_codel: dont reinit flow state
[openwrt.git] / package / 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,1077 @@
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 "pptp_msg.h"
1087 +#include "pptp_ctrl.h"
1088 +#include "pptp_options.h"
1089 +#include "vector.h"
1090 +#include "util.h"
1091 +#include "pptp_quirks.h"
1092 +
1093 +/* BECAUSE OF SIGNAL LIMITATIONS, EACH PROCESS CAN ONLY MANAGE ONE
1094 + * CONNECTION.  SO THIS 'PPTP_CONN' STRUCTURE IS A BIT MISLEADING.
1095 + * WE'LL KEEP CONNECTION-SPECIFIC INFORMATION IN THERE ANYWAY (AS
1096 + * OPPOSED TO USING GLOBAL VARIABLES), BUT BEWARE THAT THE ENTIRE
1097 + * UNIX SIGNAL-HANDLING SEMANTICS WOULD HAVE TO CHANGE (OR THE
1098 + * TIME-OUT CODE DRASTICALLY REWRITTEN) BEFORE YOU COULD DO A
1099 + * PPTP_CONN_OPEN MORE THAN ONCE PER PROCESS AND GET AWAY WITH IT.
1100 + */
1101 +
1102 +/* This structure contains connection-specific information that the
1103 + * signal handler needs to see.  Thus, it needs to be in a global
1104 + * variable.  If you end up using pthreads or something (why not
1105 + * just processes?), this would have to be placed in a thread-specific
1106 + * data area, using pthread_get|set_specific, etc., so I've
1107 + * conveniently encapsulated it for you.
1108 + * [linux threads will have to support thread-specific signals
1109 + *  before this would work at all, which, as of this writing
1110 + *  (linux-threads v0.6, linux kernel 2.1.72), it does not.]
1111 + */
1112 +
1113 +/* Globals */
1114 +
1115 +/* control the number of times echo packets will be logged */
1116 +static int nlogecho = 10;
1117 +
1118 +static struct thread_specific {
1119 +    struct sigaction old_sigaction; /* evil signals */
1120 +    PPTP_CONN * conn;
1121 +} global;
1122 +
1123 +#define INITIAL_BUFSIZE 512 /* initial i/o buffer size. */
1124 +
1125 +struct PPTP_CONN {
1126 +    int inet_sock;
1127 +    /* Connection States */
1128 +    enum {
1129 +        CONN_IDLE, CONN_WAIT_CTL_REPLY, CONN_WAIT_STOP_REPLY, CONN_ESTABLISHED
1130 +    } conn_state; /* on startup: CONN_IDLE */
1131 +    /* Keep-alive states */
1132 +    enum {
1133 +        KA_NONE, KA_OUTSTANDING
1134 +    } ka_state;  /* on startup: KA_NONE */
1135 +    /* Keep-alive ID; monotonically increasing (watch wrap-around!) */
1136 +    u_int32_t ka_id; /* on startup: 1 */
1137 +    /* Other properties. */
1138 +    u_int16_t version;
1139 +    u_int16_t firmware_rev;
1140 +    u_int8_t  hostname[64], vendor[64];
1141 +    /* XXX these are only PNS properties, currently XXX */
1142 +    /* Call assignment information. */
1143 +    u_int16_t call_serial_number;
1144 +    VECTOR *call;
1145 +    void * closure;
1146 +    pptp_conn_cb callback;
1147 +    /******* IO buffers ******/
1148 +    char * read_buffer, *write_buffer;
1149 +    size_t read_alloc,   write_alloc;
1150 +    size_t read_size,    write_size;
1151 +};
1152 +
1153 +struct PPTP_CALL {
1154 +    /* Call properties */
1155 +    enum {
1156 +        PPTP_CALL_PAC, PPTP_CALL_PNS
1157 +    } call_type;
1158 +    union {
1159 +        enum pptp_pac_state {
1160 +            PAC_IDLE, PAC_WAIT_REPLY, PAC_ESTABLISHED, PAC_WAIT_CS_ANS
1161 +        } pac;
1162 +        enum pptp_pns_state {
1163 +            PNS_IDLE, PNS_WAIT_REPLY, PNS_ESTABLISHED, PNS_WAIT_DISCONNECT
1164 +        } pns;
1165 +    } state;
1166 +    u_int16_t call_id, peer_call_id;
1167 +    u_int16_t sernum;
1168 +    u_int32_t speed;
1169 +    /* For user data: */
1170 +    pptp_call_cb callback;
1171 +    void * closure;
1172 +};
1173 +
1174 +
1175 +/* PPTP error codes: ----------------------------------------------*/
1176 +
1177 +/* (General Error Codes) */
1178 +static const struct {
1179 +    const char *name, *desc;
1180 +} pptp_general_errors[] = {
1181 +#define PPTP_GENERAL_ERROR_NONE                 0
1182 +    { "(None)", "No general error" },
1183 +#define PPTP_GENERAL_ERROR_NOT_CONNECTED        1
1184 +    { "(Not-Connected)", "No control connection exists yet for this "
1185 +        "PAC-PNS pair" },
1186 +#define PPTP_GENERAL_ERROR_BAD_FORMAT           2
1187 +    { "(Bad-Format)", "Length is wrong or Magic Cookie value is incorrect" },
1188 +#define PPTP_GENERAL_ERROR_BAD_VALUE            3
1189 +    { "(Bad-Value)", "One of the field values was out of range or "
1190 +            "reserved field was non-zero" },
1191 +#define PPTP_GENERAL_ERROR_NO_RESOURCE          4
1192 +    { "(No-Resource)", "Insufficient resources to handle this command now" },
1193 +#define PPTP_GENERAL_ERROR_BAD_CALLID           5
1194 +    { "(Bad-Call ID)", "The Call ID is invalid in this context" },
1195 +#define PPTP_GENERAL_ERROR_PAC_ERROR            6
1196 +    { "(PAC-Error)", "A generic vendor-specific error occured in the PAC" }
1197 +};
1198 +
1199 +#define  MAX_GENERAL_ERROR ( sizeof(pptp_general_errors) / \
1200 +        sizeof(pptp_general_errors[0]) - 1)
1201 +
1202 +/* Outgoing Call Reply Result Codes */
1203 +static const char *pptp_out_call_reply_result[] = {
1204 +/* 0 */        "Unknown Result Code",
1205 +/* 1 */        "Connected",
1206 +/* 2 */        "General Error",
1207 +/* 3 */        "No Carrier Detected",
1208 +/* 4 */        "Busy Signal",
1209 +/* 5 */        "No Dial Tone",
1210 +/* 6 */        "Time Out",
1211 +/* 7 */        "Not Accepted, Call is administratively prohibited" };
1212 +
1213 +#define MAX_OUT_CALL_REPLY_RESULT 7
1214 +
1215 +/* Call Disconnect Notify  Result Codes */
1216 +static const char *pptp_call_disc_ntfy[] = {
1217 +/* 0 */        "Unknown Result Code",
1218 +/* 1 */        "Lost Carrier",
1219 +/* 2 */        "General Error",
1220 +/* 3 */        "Administrative Shutdown",
1221 +/* 4 */        "(your) Request" };
1222 +
1223 +#define MAX_CALL_DISC_NTFY 4
1224 +
1225 +/* Call Disconnect Notify  Result Codes */
1226 +static const char *pptp_start_ctrl_conn_rply[] = {
1227 +/* 0 */        "Unknown Result Code",
1228 +/* 1 */        "Successful Channel Establishment",
1229 +/* 2 */        "General Error",
1230 +/* 3 */        "Command Channel Already Exists",
1231 +/* 4 */        "Requester is not Authorized" };
1232 +
1233 +#define MAX_START_CTRL_CONN_REPLY 4
1234 +
1235 +/* timing options */
1236 +int idle_wait = PPTP_TIMEOUT;
1237 +int max_echo_wait = PPTP_TIMEOUT;
1238 +
1239 +/* Local prototypes */
1240 +static void pptp_reset_timer(void);
1241 +static void pptp_handle_timer();
1242 +/* Write/read as much as we can without blocking. */
1243 +int pptp_write_some(PPTP_CONN * conn);
1244 +int pptp_read_some(PPTP_CONN * conn);
1245 +/* Make valid packets from read_buffer */
1246 +int pptp_make_packet(PPTP_CONN * conn, void **buf, size_t *size);
1247 +/* Add packet to write_buffer */
1248 +int pptp_send_ctrl_packet(PPTP_CONN * conn, void * buffer, size_t size);
1249 +/* Dispatch packets (general) */
1250 +int pptp_dispatch_packet(PPTP_CONN * conn, void * buffer, size_t size);
1251 +/* Dispatch packets (control messages) */
1252 +int ctrlp_disp(PPTP_CONN * conn, void * buffer, size_t size);
1253 +/* Set link info, for pptp servers that need it.
1254 +   this is a noop, unless the user specified a quirk and
1255 +   there's a set_link hook defined in the quirks table
1256 +   for that quirk */
1257 +void pptp_set_link(PPTP_CONN * conn, int peer_call_id);
1258 +
1259 +/*** log error information in control packets *********************************/
1260 +static void ctrlp_error( int result, int error, int cause,
1261 +        const char *result_text[], int max_result)
1262 +{
1263 +    if( cause >= 0)
1264 +        warn("Result code is %d '%s'. Error code is %d, Cause code is %d",
1265 +                result, result_text[result <= max_result ?  result : 0], error,
1266 +                cause );
1267 +    else
1268 +        warn("Reply result code is %d '%s'. Error code is %d",
1269 +                result, result_text[result <= max_result ?  result : 0], error);
1270 +    if ((error > 0) && (error <= MAX_GENERAL_ERROR)){
1271 +        if( result != PPTP_RESULT_GENERAL_ERROR )
1272 +            warn("Result code is something else then \"general error\", "
1273 +                    "so the following error is probably bogus.");
1274 +        warn("Error is '%s', Error message: '%s'",
1275 +                pptp_general_errors[error].name,
1276 +                pptp_general_errors[error].desc);
1277 +    }
1278 +}
1279 +
1280 +static const char *ctrl_msg_types[] = {
1281 +         "invalid control message type",
1282 +/*         (Control Connection Management) */
1283 +         "Start-Control-Connection-Request",            /* 1 */
1284 +         "Start-Control-Connection-Reply",              /* 2 */
1285 +         "Stop-Control-Connection-Request",             /* 3 */
1286 +         "Stop-Control-Connection-Reply",               /* 4 */
1287 +         "Echo-Request",                                /* 5 */
1288 +         "Echo-Reply",                                  /* 6 */
1289 +/*         (Call Management) */
1290 +         "Outgoing-Call-Request",                       /* 7 */
1291 +         "Outgoing-Call-Reply",                         /* 8 */
1292 +         "Incoming-Call-Request",                       /* 9 */
1293 +         "Incoming-Call-Reply",                        /* 10 */
1294 +         "Incoming-Call-Connected",                    /* 11 */
1295 +         "Call-Clear-Request",                         /* 12 */
1296 +         "Call-Disconnect-Notify",                     /* 13 */
1297 +/*         (Error Reporting) */
1298 +         "WAN-Error-Notify",                           /* 14 */
1299 +/*         (PPP Session Control) */
1300 +         "Set-Link-Info"                              /* 15 */
1301 +};
1302 +#define MAX_CTRLMSG_TYPE 15
1303 +
1304 +/*** report a sent packet ****************************************************/
1305 +static void ctrlp_rep( void * buffer, int size, int isbuff)
1306 +{
1307 +    struct pptp_header *packet = buffer;
1308 +    unsigned int type;
1309 +    if(size < sizeof(struct pptp_header)) return;
1310 +    type = ntoh16(packet->ctrl_type);
1311 +    /* FIXME: do not report sending echo requests as long as they are
1312 +     * sent in a signal handler. This may dead lock as the syslog call
1313 +     * is not reentrant */
1314 +    if( type ==  PPTP_ECHO_RQST ) return;
1315 +    /* don't keep reporting sending of echo's */
1316 +    if( (type == PPTP_ECHO_RQST || type == PPTP_ECHO_RPLY) && nlogecho <= 0 ) return;
1317 +    dbglog("%s control packet type is %d '%s'\n",isbuff ? "Buffered" : "Sent",
1318 +            type, ctrl_msg_types[type <= MAX_CTRLMSG_TYPE ? type : 0]);
1319 +
1320 +}
1321 +
1322 +
1323 +
1324 +/* Open new pptp_connection.  Returns NULL on failure. */
1325 +PPTP_CONN * pptp_conn_open(int inet_sock, int isclient, pptp_conn_cb callback)
1326 +{
1327 +    PPTP_CONN *conn;
1328 +    /* Allocate structure */
1329 +    if ((conn = malloc(sizeof(*conn))) == NULL) return NULL;
1330 +    if ((conn->call = vector_create()) == NULL) { free(conn); return NULL; }
1331 +    /* Initialize */
1332 +    conn->inet_sock = inet_sock;
1333 +    conn->conn_state = CONN_IDLE;
1334 +    conn->ka_state  = KA_NONE;
1335 +    conn->ka_id     = 1;
1336 +    conn->call_serial_number = 0;
1337 +    conn->callback  = callback;
1338 +    /* Create I/O buffers */
1339 +    conn->read_size = conn->write_size = 0;
1340 +    conn->read_alloc = conn->write_alloc = INITIAL_BUFSIZE;
1341 +    conn->read_buffer =
1342 +        malloc(sizeof(*(conn->read_buffer)) * conn->read_alloc);
1343 +    conn->write_buffer =
1344 +        malloc(sizeof(*(conn->write_buffer)) * conn->write_alloc);
1345 +    if (conn->read_buffer == NULL || conn->write_buffer == NULL) {
1346 +        if (conn->read_buffer  != NULL) free(conn->read_buffer);
1347 +        if (conn->write_buffer != NULL) free(conn->write_buffer);
1348 +        vector_destroy(conn->call); free(conn); return NULL;
1349 +    }
1350 +    /* Make this socket non-blocking. */
1351 +    fcntl(conn->inet_sock, F_SETFL, O_NONBLOCK);
1352 +    /* Request connection from server, if this is a client */
1353 +    if (isclient) {
1354 +        struct pptp_start_ctrl_conn packet = {
1355 +            PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RQST),
1356 +            hton16(PPTP_VERSION), 0, 0,
1357 +            hton32(PPTP_FRAME_CAP), hton32(PPTP_BEARER_CAP),
1358 +            hton16(PPTP_MAX_CHANNELS), hton16(PPTP_FIRMWARE_VERSION),
1359 +            PPTP_HOSTNAME, PPTP_VENDOR
1360 +        };
1361 +        /* fix this packet, if necessary */
1362 +        int idx, rc;
1363 +        idx = get_quirk_index();
1364 +        if (idx != -1 && pptp_fixups[idx].start_ctrl_conn) {
1365 +            if ((rc = pptp_fixups[idx].start_ctrl_conn(&packet)))
1366 +                warn("calling the start_ctrl_conn hook failed (%d)", rc);
1367 +        }
1368 +        if (pptp_send_ctrl_packet(conn, &packet, sizeof(packet)))
1369 +            conn->conn_state = CONN_WAIT_CTL_REPLY;
1370 +        else
1371 +            return NULL; /* could not send initial start request. */
1372 +    }
1373 +    /* Set up interval/keep-alive timer */
1374 +    /*   First, register handler for SIGALRM */
1375 +    sigpipe_create();
1376 +    sigpipe_assign(SIGALRM);
1377 +    global.conn = conn;
1378 +    /* Reset event timer */
1379 +    pptp_reset_timer();
1380 +    /* all done. */
1381 +    return conn;
1382 +}
1383 +
1384 +int pptp_conn_established(PPTP_CONN *conn) {
1385 +  return (conn->conn_state == CONN_ESTABLISHED);
1386 +}
1387 +
1388 +/* This currently *only* works for client call requests.
1389 + * We need to do something else to allocate calls for incoming requests.
1390 + */
1391 +PPTP_CALL * pptp_call_open(PPTP_CONN * conn, int call_id,pptp_call_cb callback,
1392 +        char *phonenr,int window)
1393 +{
1394 +    PPTP_CALL * call;
1395 +    int idx, rc;
1396 +    /* Send off the call request */
1397 +    struct pptp_out_call_rqst packet = {
1398 +        PPTP_HEADER_CTRL(PPTP_OUT_CALL_RQST),
1399 +        0,0, /*call_id, sernum */
1400 +        hton32(PPTP_BPS_MIN), hton32(PPTP_BPS_MAX),
1401 +        hton32(PPTP_BEARER_CAP), hton32(PPTP_FRAME_CAP),
1402 +        hton16(window), 0, 0, 0, {0}, {0}
1403 +    };
1404 +    assert(conn && conn->call);
1405 +    assert(conn->conn_state == CONN_ESTABLISHED);
1406 +    /* Assign call id */
1407 +    if (!call_id && !vector_scan(conn->call, 0, PPTP_MAX_CHANNELS - 1, &call_id))
1408 +        /* no more calls available! */
1409 +        return NULL;
1410 +    /* allocate structure. */
1411 +    if ((call = malloc(sizeof(*call))) == NULL) return NULL;
1412 +    /* Initialize call structure */
1413 +    call->call_type = PPTP_CALL_PNS;
1414 +    call->state.pns = PNS_IDLE;
1415 +    call->call_id   = (u_int16_t) call_id;
1416 +    call->sernum    = conn->call_serial_number++;
1417 +    call->callback  = callback;
1418 +    call->closure   = NULL;
1419 +    packet.call_id = htons(call->call_id);
1420 +    packet.call_sernum = htons(call->sernum);
1421 +    /* if we have a quirk, build a new packet to fit it */
1422 +    idx = get_quirk_index();
1423 +    if (idx != -1 && pptp_fixups[idx].out_call_rqst_hook) {
1424 +        if ((rc = pptp_fixups[idx].out_call_rqst_hook(&packet)))
1425 +            warn("calling the out_call_rqst hook failed (%d)", rc);
1426 +    }
1427 +    /* fill in the phone number if it was specified */
1428 +    if (phonenr) {
1429 +        strncpy(packet.phone_num, phonenr, sizeof(packet.phone_num));
1430 +        packet.phone_len = strlen(phonenr);
1431 +        if( packet.phone_len > sizeof(packet.phone_num))
1432 +            packet.phone_len = sizeof(packet.phone_num);
1433 +        packet.phone_len = hton16 (packet.phone_len);
1434 +    }
1435 +    if (pptp_send_ctrl_packet(conn, &packet, sizeof(packet))) {
1436 +        pptp_reset_timer();
1437 +        call->state.pns = PNS_WAIT_REPLY;
1438 +        /* and add it to the call vector */
1439 +        vector_insert(conn->call, call_id, call);
1440 +        return call;
1441 +    } else { /* oops, unsuccessful. Deallocate. */
1442 +        free(call);
1443 +        return NULL;
1444 +    }
1445 +}
1446 +
1447 +/*** pptp_call_close **********************************************************/
1448 +void pptp_call_close(PPTP_CONN * conn, PPTP_CALL * call)
1449 +{
1450 +    struct pptp_call_clear_rqst rqst = {
1451 +        PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_RQST), 0, 0
1452 +    };
1453 +    assert(conn && conn->call); assert(call);
1454 +    assert(vector_contains(conn->call, call->call_id));
1455 +    /* haven't thought about PAC yet */
1456 +    assert(call->call_type == PPTP_CALL_PNS);
1457 +    assert(call->state.pns != PNS_IDLE);
1458 +    rqst.call_id = hton16(call->call_id);
1459 +    /* don't check state against WAIT_DISCONNECT... allow multiple disconnect
1460 +     * requests to be made.
1461 +     */
1462 +    pptp_send_ctrl_packet(conn, &rqst, sizeof(rqst));
1463 +    pptp_reset_timer();
1464 +    call->state.pns = PNS_WAIT_DISCONNECT;
1465 +    /* call structure will be freed when we have confirmation of disconnect. */
1466 +}
1467 +
1468 +/*** hard close ***************************************************************/
1469 +void pptp_call_destroy(PPTP_CONN *conn, PPTP_CALL *call)
1470 +{
1471 +    assert(conn && conn->call); assert(call);
1472 +    assert(vector_contains(conn->call, call->call_id));
1473 +    /* notify */
1474 +    if (call->callback != NULL) call->callback(conn, call, CALL_CLOSE_DONE);
1475 +    /* deallocate */
1476 +    vector_remove(conn->call, call->call_id);
1477 +    free(call);
1478 +}
1479 +
1480 +/*** this is a soft close *****************************************************/
1481 +void pptp_conn_close(PPTP_CONN * conn, u_int8_t close_reason)
1482 +{
1483 +    struct pptp_stop_ctrl_conn rqst = {
1484 +        PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RQST),
1485 +        hton8(close_reason), 0, 0
1486 +    };
1487 +    int i;
1488 +    assert(conn && conn->call);
1489 +    /* avoid repeated close attempts */
1490 +    if (conn->conn_state == CONN_IDLE || conn->conn_state == CONN_WAIT_STOP_REPLY)
1491 +        return;
1492 +    /* close open calls, if any */
1493 +    for (i = 0; i < vector_size(conn->call); i++)
1494 +        pptp_call_close(conn, vector_get_Nth(conn->call, i));
1495 +    /* now close connection */
1496 +    info("Closing PPTP connection");
1497 +    pptp_send_ctrl_packet(conn, &rqst, sizeof(rqst));
1498 +    pptp_reset_timer(); /* wait 60 seconds for reply */
1499 +    conn->conn_state = CONN_WAIT_STOP_REPLY;
1500 +    return;
1501 +}
1502 +
1503 +/*** this is a hard close *****************************************************/
1504 +void pptp_conn_destroy(PPTP_CONN * conn)
1505 +{
1506 +    int i;
1507 +    assert(conn != NULL); assert(conn->call != NULL);
1508 +    /* destroy all open calls */
1509 +    for (i = 0; i < vector_size(conn->call); i++)
1510 +        pptp_call_destroy(conn, vector_get_Nth(conn->call, i));
1511 +    /* notify */
1512 +    if (conn->callback != NULL) conn->callback(conn, CONN_CLOSE_DONE);
1513 +    sigpipe_close();
1514 +    close(conn->inet_sock);
1515 +    /* deallocate */
1516 +    vector_destroy(conn->call);
1517 +    free(conn);
1518 +}
1519 +
1520 +/*** Deal with messages, in a non-blocking manner
1521 + * Add file descriptors used by pptp to fd_set.
1522 + */
1523 +void pptp_fd_set(PPTP_CONN * conn, fd_set * read_set, fd_set * write_set,
1524 +                 int * max_fd)
1525 +{
1526 +    assert(conn && conn->call);
1527 +    /* Add fd to write_set if there are outstanding writes. */
1528 +    if (conn->write_size > 0)
1529 +        FD_SET(conn->inet_sock, write_set);
1530 +    /* Always add fd to read_set. (always want something to read) */
1531 +    FD_SET(conn->inet_sock, read_set);
1532 +    if (*max_fd < conn->inet_sock) *max_fd = conn->inet_sock;
1533 +    /* Add signal pipe file descriptor to set */
1534 +    int sig_fd = sigpipe_fd();
1535 +    FD_SET(sig_fd, read_set);
1536 +    if (*max_fd < sig_fd) *max_fd = sig_fd;
1537 +}
1538 +
1539 +/*** handle any pptp file descriptors set in fd_set, and clear them ***********/
1540 +int pptp_dispatch(PPTP_CONN * conn, fd_set * read_set, fd_set * write_set)
1541 +{
1542 +    int r = 0;
1543 +    assert(conn && conn->call);
1544 +    /* Check for signals */
1545 +    if (FD_ISSET(sigpipe_fd(), read_set)) {
1546 +        if (sigpipe_read() == SIGALRM) pptp_handle_timer();
1547 +       FD_CLR(sigpipe_fd(), read_set);
1548 +    }
1549 +    /* Check write_set could be set. */
1550 +    if (FD_ISSET(conn->inet_sock, write_set)) {
1551 +        FD_CLR(conn->inet_sock, write_set);
1552 +        if (conn->write_size > 0)
1553 +            r = pptp_write_some(conn);/* write as much as we can without blocking */
1554 +    }
1555 +    /* Check read_set */
1556 +    if (r >= 0 && FD_ISSET(conn->inet_sock, read_set)) {
1557 +        void *buffer; size_t size;
1558 +        FD_CLR(conn->inet_sock, read_set);
1559 +        r = pptp_read_some(conn); /* read as much as we can without blocking */
1560 +       if (r < 0)
1561 +           return r;
1562 +        /* make packets of the buffer, while we can. */
1563 +        while (r >= 0 && pptp_make_packet(conn, &buffer, &size)) {
1564 +            r = pptp_dispatch_packet(conn, buffer, size);
1565 +            free(buffer);
1566 +        }
1567 +    }
1568 +    /* That's all, folks.  Simple, eh? */
1569 +    return r;
1570 +}
1571 +
1572 +/*** Non-blocking write *******************************************************/
1573 +int pptp_write_some(PPTP_CONN * conn) {
1574 +    ssize_t retval;
1575 +    assert(conn && conn->call);
1576 +    retval = write(conn->inet_sock, conn->write_buffer, conn->write_size);
1577 +    if (retval < 0) { /* error. */
1578 +        if (errno == EAGAIN || errno == EINTR) {
1579 +            return 0;
1580 +        } else { /* a real error */
1581 +            warn("write error: %s", strerror(errno));
1582 +           return -1;
1583 +        }
1584 +    }
1585 +    assert(retval <= conn->write_size);
1586 +    conn->write_size -= retval;
1587 +    memmove(conn->write_buffer, conn->write_buffer + retval, conn->write_size);
1588 +    ctrlp_rep(conn->write_buffer, retval, 0);
1589 +    return 0;
1590 +}
1591 +
1592 +/*** Non-blocking read ********************************************************/
1593 +int pptp_read_some(PPTP_CONN * conn)
1594 +{
1595 +    ssize_t retval;
1596 +    assert(conn && conn->call);
1597 +    if (conn->read_size == conn->read_alloc) { /* need to alloc more memory */
1598 +        char *new_buffer = realloc(conn->read_buffer,
1599 +                sizeof(*(conn->read_buffer)) * conn->read_alloc * 2);
1600 +        if (new_buffer == NULL) {
1601 +            warn("Out of memory"); return -1;
1602 +        }
1603 +        conn->read_alloc *= 2;
1604 +        conn->read_buffer = new_buffer;
1605 +    }
1606 +    retval = read(conn->inet_sock, conn->read_buffer + conn->read_size,
1607 +            conn->read_alloc  - conn->read_size);
1608 +    if (retval == 0) {
1609 +        warn("read returned zero, peer has closed");
1610 +        return -1;
1611 +    }
1612 +    if (retval < 0) {
1613 +        if (errno == EINTR || errno == EAGAIN)
1614 +           return 0;
1615 +        else { /* a real error */
1616 +            warn("read error: %s", strerror(errno));
1617 +            return -1;
1618 +        }
1619 +    }
1620 +    conn->read_size += retval;
1621 +    assert(conn->read_size <= conn->read_alloc);
1622 +    return 0;
1623 +}
1624 +
1625 +/*** Packet formation *********************************************************/
1626 +int pptp_make_packet(PPTP_CONN * conn, void **buf, size_t *size)
1627 +{
1628 +    struct pptp_header *header;
1629 +    size_t bad_bytes = 0;
1630 +    assert(conn && conn->call); assert(buf != NULL); assert(size != NULL);
1631 +    /* Give up unless there are at least sizeof(pptp_header) bytes */
1632 +    while ((conn->read_size-bad_bytes) >= sizeof(struct pptp_header)) {
1633 +        /* Throw out bytes until we have a valid header. */
1634 +        header = (struct pptp_header *) (conn->read_buffer + bad_bytes);
1635 +        if (ntoh32(header->magic) != PPTP_MAGIC) goto throwitout;
1636 +        if (ntoh16(header->reserved0) != 0)
1637 +            warn("reserved0 field is not zero! (0x%x) Cisco feature? \n",
1638 +                    ntoh16(header->reserved0));
1639 +        if (ntoh16(header->length) < sizeof(struct pptp_header)) goto throwitout;
1640 +        if (ntoh16(header->length) > PPTP_CTRL_SIZE_MAX) goto throwitout;
1641 +        /* well.  I guess it's good. Let's see if we've got it all. */
1642 +        if (ntoh16(header->length) > (conn->read_size-bad_bytes))
1643 +            /* nope.  Let's wait until we've got it, then. */
1644 +            goto flushbadbytes;
1645 +        /* One last check: */
1646 +        if ((ntoh16(header->pptp_type) == PPTP_MESSAGE_CONTROL) &&
1647 +                (ntoh16(header->length) !=
1648 +                         PPTP_CTRL_SIZE(ntoh16(header->ctrl_type))))
1649 +            goto throwitout;
1650 +        /* well, I guess we've got it. */
1651 +        *size = ntoh16(header->length);
1652 +        *buf = malloc(*size);
1653 +        if (*buf == NULL) { warn("Out of memory."); return 0; /* ack! */ }
1654 +        memcpy(*buf, conn->read_buffer + bad_bytes, *size);
1655 +        /* Delete this packet from the read_buffer. */
1656 +        conn->read_size -= (bad_bytes + *size);
1657 +        memmove(conn->read_buffer, conn->read_buffer + bad_bytes + *size,
1658 +                conn->read_size);
1659 +        if (bad_bytes > 0)
1660 +            warn("%lu bad bytes thrown away.", (unsigned long) bad_bytes);
1661 +        return 1;
1662 +throwitout:
1663 +        bad_bytes++;
1664 +    }
1665 +flushbadbytes:
1666 +    /* no more packets.  Let's get rid of those bad bytes */
1667 +    conn->read_size -= bad_bytes;
1668 +    memmove(conn->read_buffer, conn->read_buffer + bad_bytes, conn->read_size);
1669 +    if (bad_bytes > 0)
1670 +        warn("%lu bad bytes thrown away.", (unsigned long) bad_bytes);
1671 +    return 0;
1672 +}
1673 +
1674 +/*** pptp_send_ctrl_packet ****************************************************/
1675 +int pptp_send_ctrl_packet(PPTP_CONN * conn, void * buffer, size_t size)
1676 +{
1677 +    assert(conn && conn->call); assert(buffer);
1678 +    if( conn->write_size > 0) pptp_write_some( conn);
1679 +    if( conn->write_size == 0) {
1680 +        ssize_t retval;
1681 +        retval = write(conn->inet_sock, buffer, size);
1682 +        if (retval < 0) { /* error. */
1683 +            if (errno == EAGAIN || errno == EINTR) {
1684 +                /* ignore */;
1685 +                retval = 0;
1686 +            } else { /* a real error */
1687 +                warn("write error: %s", strerror(errno));
1688 +                pptp_conn_destroy(conn); /* shut down fast. */
1689 +                return 0;
1690 +            }
1691 +        }
1692 +        ctrlp_rep( buffer, retval, 0);
1693 +        size -= retval;
1694 +        if( size <= 0) return 1;
1695 +    }
1696 +    /* Shove anything not written into the write buffer */
1697 +    if (conn->write_size + size > conn->write_alloc) { /* need more memory */
1698 +        char *new_buffer = realloc(conn->write_buffer,
1699 +                sizeof(*(conn->write_buffer)) * conn->write_alloc * 2);
1700 +        if (new_buffer == NULL) {
1701 +            warn("Out of memory"); return 0;
1702 +        }
1703 +        conn->write_alloc *= 2;
1704 +        conn->write_buffer = new_buffer;
1705 +    }
1706 +    memcpy(conn->write_buffer + conn->write_size, buffer, size);
1707 +    conn->write_size += size;
1708 +    ctrlp_rep( buffer,size,1);
1709 +    return 1;
1710 +}
1711 +
1712 +/*** Packet Dispatch **********************************************************/
1713 +int pptp_dispatch_packet(PPTP_CONN * conn, void * buffer, size_t size)
1714 +{
1715 +    int r = 0;
1716 +    struct pptp_header *header = (struct pptp_header *)buffer;
1717 +    assert(conn && conn->call); assert(buffer);
1718 +    assert(ntoh32(header->magic) == PPTP_MAGIC);
1719 +    assert(ntoh16(header->length) == size);
1720 +    switch (ntoh16(header->pptp_type)) {
1721 +        case PPTP_MESSAGE_CONTROL:
1722 +            r = ctrlp_disp(conn, buffer, size);
1723 +            break;
1724 +        case PPTP_MESSAGE_MANAGE:
1725 +            /* MANAGEMENT messages aren't even part of the spec right now. */
1726 +            dbglog("PPTP management message received, but not understood.");
1727 +            break;
1728 +        default:
1729 +            dbglog("Unknown PPTP control message type received: %u",
1730 +                    (unsigned int) ntoh16(header->pptp_type));
1731 +            break;
1732 +    }
1733 +    return r;
1734 +}
1735 +
1736 +/*** log echo request/replies *************************************************/
1737 +static void logecho( int type)
1738 +{
1739 +    /* hack to stop flooding the log files (the most interesting part is right
1740 +     * after the connection built-up) */
1741 +    if( nlogecho > 0) {
1742 +        dbglog("Echo Re%s received.", type == PPTP_ECHO_RQST ? "quest" :"ply");
1743 +        if( --nlogecho == 0)
1744 +            dbglog("no more Echo Reply/Request packets will be reported.");
1745 +    }
1746 +}
1747 +
1748 +/*** pptp_dispatch_ctrl_packet ************************************************/
1749 +int ctrlp_disp(PPTP_CONN * conn, void * buffer, size_t size)
1750 +{
1751 +    struct pptp_header *header = (struct pptp_header *)buffer;
1752 +    u_int8_t close_reason = PPTP_STOP_NONE;
1753 +    assert(conn && conn->call); assert(buffer);
1754 +    assert(ntoh32(header->magic) == PPTP_MAGIC);
1755 +    assert(ntoh16(header->length) == size);
1756 +    assert(ntoh16(header->pptp_type) == PPTP_MESSAGE_CONTROL);
1757 +    if (size < PPTP_CTRL_SIZE(ntoh16(header->ctrl_type))) {
1758 +        warn("Invalid packet received [type: %d; length: %d].",
1759 +                (int) ntoh16(header->ctrl_type), (int) size);
1760 +        return 0;
1761 +    }
1762 +    switch (ntoh16(header->ctrl_type)) {
1763 +        /* ----------- STANDARD Start-Session MESSAGES ------------ */
1764 +        case PPTP_START_CTRL_CONN_RQST:
1765 +        {
1766 +            struct pptp_start_ctrl_conn *packet =
1767 +                (struct pptp_start_ctrl_conn *) buffer;
1768 +            struct pptp_start_ctrl_conn reply = {
1769 +                PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RPLY),
1770 +                hton16(PPTP_VERSION), 0, 0,
1771 +                hton32(PPTP_FRAME_CAP), hton32(PPTP_BEARER_CAP),
1772 +                hton16(PPTP_MAX_CHANNELS), hton16(PPTP_FIRMWARE_VERSION),
1773 +                PPTP_HOSTNAME, PPTP_VENDOR };
1774 +            int idx, rc;
1775 +            dbglog("Received Start Control Connection Request");
1776 +            /* fix this packet, if necessary */
1777 +            idx = get_quirk_index();
1778 +            if (idx != -1 && pptp_fixups[idx].start_ctrl_conn) {
1779 +                if ((rc = pptp_fixups[idx].start_ctrl_conn(&reply)))
1780 +                    warn("calling the start_ctrl_conn hook failed (%d)", rc);
1781 +            }
1782 +            if (conn->conn_state == CONN_IDLE) {
1783 +                if (ntoh16(packet->version) < PPTP_VERSION) {
1784 +                    /* Can't support this (earlier) PPTP_VERSION */
1785 +                    reply.version = packet->version;
1786 +                    /* protocol version not supported */
1787 +                    reply.result_code = hton8(5);
1788 +                    pptp_send_ctrl_packet(conn, &reply, sizeof(reply));
1789 +                    pptp_reset_timer(); /* give sender a chance for a retry */
1790 +                } else { /* same or greater version */
1791 +                    if (pptp_send_ctrl_packet(conn, &reply, sizeof(reply))) {
1792 +                        conn->conn_state = CONN_ESTABLISHED;
1793 +                        dbglog("server connection ESTABLISHED.");
1794 +                        pptp_reset_timer();
1795 +                    }
1796 +                }
1797 +            }
1798 +            break;
1799 +        }
1800 +        case PPTP_START_CTRL_CONN_RPLY:
1801 +        {
1802 +            struct pptp_start_ctrl_conn *packet =
1803 +                (struct pptp_start_ctrl_conn *) buffer;
1804 +            dbglog("Received Start Control Connection Reply");
1805 +            if (conn->conn_state == CONN_WAIT_CTL_REPLY) {
1806 +                /* XXX handle collision XXX [see rfc] */
1807 +                if (ntoh16(packet->version) != PPTP_VERSION) {
1808 +                    if (conn->callback != NULL)
1809 +                        conn->callback(conn, CONN_OPEN_FAIL);
1810 +                    close_reason = PPTP_STOP_PROTOCOL;
1811 +                    goto pptp_conn_close;
1812 +                }
1813 +                if (ntoh8(packet->result_code) != 1 &&
1814 +                    /* J'ai change le if () afin que la connection ne se ferme
1815 +                     * pas pour un "rien" :p adel@cybercable.fr -
1816 +                     *
1817 +                     * Don't close the connection if the result code is zero
1818 +                     * (feature found in certain ADSL modems)
1819 +                     */
1820 +                        ntoh8(packet->result_code) != 0) {
1821 +                    dbglog("Negative reply received to our Start Control "
1822 +                            "Connection Request");
1823 +                    ctrlp_error(packet->result_code, packet->error_code,
1824 +                            -1, pptp_start_ctrl_conn_rply,
1825 +                            MAX_START_CTRL_CONN_REPLY);
1826 +                    if (conn->callback != NULL)
1827 +                        conn->callback(conn, CONN_OPEN_FAIL);
1828 +                    close_reason = PPTP_STOP_PROTOCOL;
1829 +                    goto pptp_conn_close;
1830 +                }
1831 +                conn->conn_state = CONN_ESTABLISHED;
1832 +                /* log session properties */
1833 +                conn->version      = ntoh16(packet->version);
1834 +                conn->firmware_rev = ntoh16(packet->firmware_rev);
1835 +                memcpy(conn->hostname, packet->hostname, sizeof(conn->hostname));
1836 +                memcpy(conn->vendor, packet->vendor, sizeof(conn->vendor));
1837 +                pptp_reset_timer(); /* 60 seconds until keep-alive */
1838 +                dbglog("Client connection established.");
1839 +                if (conn->callback != NULL)
1840 +                    conn->callback(conn, CONN_OPEN_DONE);
1841 +            } /* else goto pptp_conn_close; */
1842 +            break;
1843 +        }
1844 +            /* ----------- STANDARD Stop-Session MESSAGES ------------ */
1845 +        case PPTP_STOP_CTRL_CONN_RQST:
1846 +        {
1847 +            /* conn_state should be CONN_ESTABLISHED, but it could be
1848 +             * something else */
1849 +            struct pptp_stop_ctrl_conn reply = {
1850 +                PPTP_HEADER_CTRL(PPTP_STOP_CTRL_CONN_RPLY),
1851 +                hton8(1), hton8(PPTP_GENERAL_ERROR_NONE), 0
1852 +            };
1853 +            dbglog("Received Stop Control Connection Request.");
1854 +            if (conn->conn_state == CONN_IDLE) break;
1855 +            if (pptp_send_ctrl_packet(conn, &reply, sizeof(reply))) {
1856 +                if (conn->callback != NULL)
1857 +                    conn->callback(conn, CONN_CLOSE_RQST);
1858 +                conn->conn_state = CONN_IDLE;
1859 +               return -1;
1860 +            }
1861 +            break;
1862 +        }
1863 +        case PPTP_STOP_CTRL_CONN_RPLY:
1864 +        {
1865 +            dbglog("Received Stop Control Connection Reply.");
1866 +            /* conn_state should be CONN_WAIT_STOP_REPLY, but it
1867 +             * could be something else */
1868 +            if (conn->conn_state == CONN_IDLE) break;
1869 +            conn->conn_state = CONN_IDLE;
1870 +           return -1;
1871 +        }
1872 +            /* ----------- STANDARD Echo/Keepalive MESSAGES ------------ */
1873 +        case PPTP_ECHO_RPLY:
1874 +        {
1875 +            struct pptp_echo_rply *packet =
1876 +                (struct pptp_echo_rply *) buffer;
1877 +            logecho( PPTP_ECHO_RPLY);
1878 +            if ((conn->ka_state == KA_OUTSTANDING) &&
1879 +                    (ntoh32(packet->identifier) == conn->ka_id)) {
1880 +                conn->ka_id++;
1881 +                conn->ka_state = KA_NONE;
1882 +                pptp_reset_timer();
1883 +            }
1884 +            break;
1885 +        }
1886 +        case PPTP_ECHO_RQST:
1887 +        {
1888 +            struct pptp_echo_rqst *packet =
1889 +                (struct pptp_echo_rqst *) buffer;
1890 +            struct pptp_echo_rply reply = {
1891 +                PPTP_HEADER_CTRL(PPTP_ECHO_RPLY),
1892 +                packet->identifier, /* skip hton32(ntoh32(id)) */
1893 +                hton8(1), hton8(PPTP_GENERAL_ERROR_NONE), 0
1894 +            };
1895 +            logecho( PPTP_ECHO_RQST);
1896 +            pptp_send_ctrl_packet(conn, &reply, sizeof(reply));
1897 +            pptp_reset_timer();
1898 +            break;
1899 +        }
1900 +            /* ----------- OUTGOING CALL MESSAGES ------------ */
1901 +        case PPTP_OUT_CALL_RQST:
1902 +        {
1903 +            struct pptp_out_call_rqst *packet =
1904 +                (struct pptp_out_call_rqst *)buffer;
1905 +            struct pptp_out_call_rply reply = {
1906 +                PPTP_HEADER_CTRL(PPTP_OUT_CALL_RPLY),
1907 +                0 /* callid */, packet->call_id, 1, PPTP_GENERAL_ERROR_NONE, 0,
1908 +                hton32(PPTP_CONNECT_SPEED),
1909 +                hton16(PPTP_WINDOW), hton16(PPTP_DELAY), 0
1910 +            };
1911 +            dbglog("Received Outgoing Call Request.");
1912 +            /* XXX PAC: eventually this should make an outgoing call. XXX */
1913 +            reply.result_code = hton8(7); /* outgoing calls verboten */
1914 +            pptp_send_ctrl_packet(conn, &reply, sizeof(reply));
1915 +            break;
1916 +        }
1917 +        case PPTP_OUT_CALL_RPLY:
1918 +        {
1919 +            struct pptp_out_call_rply *packet =
1920 +                (struct pptp_out_call_rply *)buffer;
1921 +            PPTP_CALL * call;
1922 +            u_int16_t callid = ntoh16(packet->call_id_peer);
1923 +            dbglog("Received Outgoing Call Reply.");
1924 +            if (!vector_search(conn->call, (int) callid, &call)) {
1925 +                dbglog("PPTP_OUT_CALL_RPLY received for non-existant call: "
1926 +                        "peer call ID (us)  %d call ID (them) %d.",
1927 +                        callid, ntoh16(packet->call_id));
1928 +                break;
1929 +            }
1930 +            if (call->call_type != PPTP_CALL_PNS) {
1931 +                dbglog("Ack!  How did this call_type get here?"); /* XXX? */
1932 +                break;
1933 +            }
1934 +            if (call->state.pns != PNS_WAIT_REPLY) {
1935 +                warn("Unexpected(?) Outgoing Call Reply will be ignored.");
1936 +                break;
1937 +            }
1938 +            /* check for errors */
1939 +            if (packet->result_code != 1) {
1940 +                /* An error.  Log it verbosely. */
1941 +                dbglog("Our outgoing call request [callid %d] has not been "
1942 +                        "accepted.", (int) callid);
1943 +                ctrlp_error(packet->result_code, packet->error_code,
1944 +                        packet->cause_code, pptp_out_call_reply_result,
1945 +                        MAX_OUT_CALL_REPLY_RESULT);
1946 +                call->state.pns = PNS_IDLE;
1947 +                if (call->callback != NULL)
1948 +                    call->callback(conn, call, CALL_OPEN_FAIL);
1949 +                pptp_call_destroy(conn, call);
1950 +            } else {
1951 +                /* connection established */
1952 +                call->state.pns = PNS_ESTABLISHED;
1953 +                call->peer_call_id = ntoh16(packet->call_id);
1954 +                call->speed        = ntoh32(packet->speed);
1955 +                pptp_reset_timer();
1956 +                /* call pptp_set_link. unless the user specified a quirk
1957 +                   and this quirk has a set_link hook, this is a noop */
1958 +                pptp_set_link(conn, call->peer_call_id);
1959 +                if (call->callback != NULL)
1960 +                    call->callback(conn, call, CALL_OPEN_DONE);
1961 +                dbglog("Outgoing call established (call ID %u, peer's "
1962 +                        "call ID %u).\n", call->call_id, call->peer_call_id);
1963 +            }
1964 +            break;
1965 +        }
1966 +            /* ----------- INCOMING CALL MESSAGES ------------ */
1967 +            /* XXX write me XXX */
1968 +            /* ----------- CALL CONTROL MESSAGES ------------ */
1969 +        case PPTP_CALL_CLEAR_RQST:
1970 +        {
1971 +            struct pptp_call_clear_rqst *packet =
1972 +                (struct pptp_call_clear_rqst *)buffer;
1973 +            struct pptp_call_clear_ntfy reply = {
1974 +                PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_NTFY), packet->call_id,
1975 +                1, PPTP_GENERAL_ERROR_NONE, 0, 0, {0}
1976 +            };
1977 +            dbglog("Received Call Clear Request.");
1978 +            if (vector_contains(conn->call, ntoh16(packet->call_id))) {
1979 +                PPTP_CALL * call;
1980 +                vector_search(conn->call, ntoh16(packet->call_id), &call);
1981 +                if (call->callback != NULL)
1982 +                    call->callback(conn, call, CALL_CLOSE_RQST);
1983 +                pptp_send_ctrl_packet(conn, &reply, sizeof(reply));
1984 +                pptp_call_destroy(conn, call);
1985 +                dbglog("Call closed (RQST) (call id %d)", (int) call->call_id);
1986 +            }
1987 +            break;
1988 +        }
1989 +        case PPTP_CALL_CLEAR_NTFY:
1990 +        {
1991 +            struct pptp_call_clear_ntfy *packet =
1992 +                (struct pptp_call_clear_ntfy *)buffer;
1993 +            dbglog("Call disconnect notification received (call id %d)",
1994 +                    ntoh16(packet->call_id));
1995 +            if (vector_contains(conn->call, ntoh16(packet->call_id))) {
1996 +                PPTP_CALL * call;
1997 +                ctrlp_error(packet->result_code, packet->error_code,
1998 +                        packet->cause_code, pptp_call_disc_ntfy,
1999 +                        MAX_CALL_DISC_NTFY);
2000 +                vector_search(conn->call, ntoh16(packet->call_id), &call);
2001 +                pptp_call_destroy(conn, call);
2002 +            }
2003 +            /* XXX we could log call stats here XXX */
2004 +            /* XXX not all servers send this XXX */
2005 +            break;
2006 +        }
2007 +        case PPTP_SET_LINK_INFO:
2008 +        {
2009 +            /* I HAVE NO CLUE WHAT TO DO IF send_accm IS NOT 0! */
2010 +            /* this is really dealt with in the HDLC deencapsulation, anyway. */
2011 +            struct pptp_set_link_info *packet =
2012 +                (struct pptp_set_link_info *)buffer;
2013 +            /* log it. */
2014 +            dbglog("PPTP_SET_LINK_INFO received from peer_callid %u",
2015 +                    (unsigned int) ntoh16(packet->call_id_peer));
2016 +            dbglog("  send_accm is %08lX, recv_accm is %08lX",
2017 +                    (unsigned long) ntoh32(packet->send_accm),
2018 +                    (unsigned long) ntoh32(packet->recv_accm));
2019 +            if (!(ntoh32(packet->send_accm) == 0 &&
2020 +                    ntoh32(packet->recv_accm) == 0))
2021 +                warn("Non-zero Async Control Character Maps are not supported!");
2022 +            break;
2023 +        }
2024 +        default:
2025 +            dbglog("Unrecognized Packet %d received.",
2026 +                    (int) ntoh16(((struct pptp_header *)buffer)->ctrl_type));
2027 +            /* goto pptp_conn_close; */
2028 +            break;
2029 +    }
2030 +    return 0;
2031 +pptp_conn_close:
2032 +    warn("pptp_conn_close(%d)", (int) close_reason);
2033 +    pptp_conn_close(conn, close_reason);
2034 +    return 0;
2035 +}
2036 +
2037 +/*** pptp_set_link **************************************************************/
2038 +void pptp_set_link(PPTP_CONN* conn, int peer_call_id)
2039 +{
2040 +    int idx, rc;
2041 +    /* if we need to send a set_link packet because of buggy
2042 +       hardware or pptp server, do it now */
2043 +    if ((idx = get_quirk_index()) != -1 && pptp_fixups[idx].set_link_hook) {
2044 +        struct pptp_set_link_info packet;
2045 +        if ((rc = pptp_fixups[idx].set_link_hook(&packet, peer_call_id)))
2046 +            warn("calling the set_link hook failed (%d)", rc);
2047 +        if (pptp_send_ctrl_packet(conn, &packet, sizeof(packet))) {
2048 +            pptp_reset_timer();
2049 +        }
2050 +    }
2051 +}
2052 +
2053 +/*** Get info from call structure *********************************************/
2054 +/* NOTE: The peer_call_id is undefined until we get a server response. */
2055 +void pptp_call_get_ids(PPTP_CONN * conn, PPTP_CALL * call,
2056 +                      u_int16_t * call_id, u_int16_t * peer_call_id)
2057 +{
2058 +    assert(conn != NULL); assert(call != NULL);
2059 +    *call_id = call->call_id;
2060 +    *peer_call_id = call->peer_call_id;
2061 +}
2062 +
2063 +/*** pptp_call_closure_put ****************************************************/
2064 +void   pptp_call_closure_put(PPTP_CONN * conn, PPTP_CALL * call, void *cl)
2065 +{
2066 +    assert(conn != NULL); assert(call != NULL);
2067 +    call->closure = cl;
2068 +}
2069 +
2070 +/*** pptp_call_closure_get ****************************************************/
2071 +void * pptp_call_closure_get(PPTP_CONN * conn, PPTP_CALL * call)
2072 +{
2073 +    assert(conn != NULL); assert(call != NULL);
2074 +    return call->closure;
2075 +}
2076 +
2077 +/*** pptp_conn_closure_put ****************************************************/
2078 +void   pptp_conn_closure_put(PPTP_CONN * conn, void *cl)
2079 +{
2080 +    assert(conn != NULL);
2081 +    conn->closure = cl;
2082 +}
2083 +
2084 +/*** pptp_conn_closure_get ****************************************************/
2085 +void * pptp_conn_closure_get(PPTP_CONN * conn)
2086 +{
2087 +    assert(conn != NULL);
2088 +    return conn->closure;
2089 +}
2090 +
2091 +/*** Reset keep-alive timer ***************************************************/
2092 +static void pptp_reset_timer(void)
2093 +{
2094 +    const struct itimerval tv = { {  0, 0 },   /* stop on time-out */
2095 +        { idle_wait, 0 } };
2096 +    if (idle_wait) setitimer(ITIMER_REAL, &tv, NULL);
2097 +}
2098 +
2099 +
2100 +/*** Handle keep-alive timer **************************************************/
2101 +static void pptp_handle_timer()
2102 +{
2103 +    int i;
2104 +    /* "Keep Alives and Timers, 1": check connection state */
2105 +    if (global.conn->conn_state != CONN_ESTABLISHED) {
2106 +        if (global.conn->conn_state == CONN_WAIT_STOP_REPLY)
2107 +            /* hard close. */
2108 +            pptp_conn_destroy(global.conn);
2109 +        else /* soft close */
2110 +            pptp_conn_close(global.conn, PPTP_STOP_NONE);
2111 +    }
2112 +    /* "Keep Alives and Timers, 2": check echo status */
2113 +    if (global.conn->ka_state == KA_OUTSTANDING) {
2114 +        /* no response to keep-alive */
2115 +        info("closing control connection due to missing echo reply");
2116 +       pptp_conn_close(global.conn, PPTP_STOP_NONE);
2117 +    } else { /* ka_state == NONE */ /* send keep-alive */
2118 +        struct pptp_echo_rqst rqst = {
2119 +            PPTP_HEADER_CTRL(PPTP_ECHO_RQST), hton32(global.conn->ka_id) };
2120 +        pptp_send_ctrl_packet(global.conn, &rqst, sizeof(rqst));
2121 +        global.conn->ka_state = KA_OUTSTANDING;
2122 +    }
2123 +    /* check incoming/outgoing call states for !IDLE && !ESTABLISHED */
2124 +    for (i = 0; i < vector_size(global.conn->call); i++) {
2125 +        PPTP_CALL * call = vector_get_Nth(global.conn->call, i);
2126 +        if (call->call_type == PPTP_CALL_PNS) {
2127 +            if (call->state.pns == PNS_WAIT_REPLY) {
2128 +                /* send close request */
2129 +                pptp_call_close(global.conn, call);
2130 +                assert(call->state.pns == PNS_WAIT_DISCONNECT);
2131 +            } else if (call->state.pns == PNS_WAIT_DISCONNECT) {
2132 +                /* hard-close the call */
2133 +                pptp_call_destroy(global.conn, call);
2134 +            }
2135 +        } else if (call->call_type == PPTP_CALL_PAC) {
2136 +            if (call->state.pac == PAC_WAIT_REPLY) {
2137 +                /* XXX FIXME -- drop the PAC connection XXX */
2138 +            } else if (call->state.pac == PAC_WAIT_CS_ANS) {
2139 +                /* XXX FIXME -- drop the PAC connection XXX */
2140 +            }
2141 +        }
2142 +    }
2143 +    pptp_reset_timer();
2144 +}
2145 --- /dev/null
2146 +++ b/pppd/plugins/pptp/pptp_ctrl.h
2147 @@ -0,0 +1,57 @@
2148 +/* pptp_ctrl.h ... handle PPTP control connection.
2149 + *                 C. Scott Ananian <cananian@alumni.princeton.edu>
2150 + *
2151 + * $Id: pptp_ctrl.h,v 1.5 2004/11/09 01:42:32 quozl Exp $
2152 + */
2153 +
2154 +#ifndef INC_PPTP_CTRL_H
2155 +#define INC_PPTP_CTRL_H
2156 +#include <sys/types.h>
2157 +
2158 +typedef struct PPTP_CONN PPTP_CONN;
2159 +typedef struct PPTP_CALL PPTP_CALL;
2160 +
2161 +enum call_state { CALL_OPEN_RQST,  CALL_OPEN_DONE, CALL_OPEN_FAIL,
2162 +                 CALL_CLOSE_RQST, CALL_CLOSE_DONE };
2163 +enum conn_state { CONN_OPEN_RQST,  CONN_OPEN_DONE, CONN_OPEN_FAIL,
2164 +                 CONN_CLOSE_RQST, CONN_CLOSE_DONE };
2165 +
2166 +typedef void (*pptp_call_cb)(PPTP_CONN*, PPTP_CALL*, enum call_state);
2167 +typedef void (*pptp_conn_cb)(PPTP_CONN*, enum conn_state);
2168 +
2169 +/* if 'isclient' is true, then will send 'conn open' packet to other host.
2170 + * not necessary if this is being opened by a server process after
2171 + * receiving a conn_open packet from client.
2172 + */
2173 +PPTP_CONN * pptp_conn_open(int inet_sock, int isclient,
2174 +                          pptp_conn_cb callback);
2175 +PPTP_CALL * pptp_call_open(PPTP_CONN * conn, int call_id,
2176 +                          pptp_call_cb callback, char *phonenr,int window);
2177 +int pptp_conn_established(PPTP_CONN * conn);
2178 +/* soft close.  Will callback on completion. */
2179 +void pptp_call_close(PPTP_CONN * conn, PPTP_CALL * call);
2180 +/* hard close. */
2181 +void pptp_call_destroy(PPTP_CONN *conn, PPTP_CALL *call);
2182 +/* soft close.  Will callback on completion. */
2183 +void pptp_conn_close(PPTP_CONN * conn, u_int8_t close_reason);
2184 +/* hard close */
2185 +void pptp_conn_destroy(PPTP_CONN * conn);
2186 +
2187 +/* Add file descriptors used by pptp to fd_set. */
2188 +void pptp_fd_set(PPTP_CONN * conn, fd_set * read_set, fd_set * write_set, int *max_fd);
2189 +/* handle any pptp file descriptors set in fd_set, and clear them */
2190 +int pptp_dispatch(PPTP_CONN * conn, fd_set * read_set, fd_set * write_set);
2191 +
2192 +/* Get info about connection, call */
2193 +void pptp_call_get_ids(PPTP_CONN * conn, PPTP_CALL * call,
2194 +                      u_int16_t * call_id, u_int16_t * peer_call_id);
2195 +/* Arbitrary user data about this call/connection.
2196 + * It is the caller's responsibility to free this data before calling
2197 + * pptp_call|conn_close()
2198 + */
2199 +void * pptp_conn_closure_get(PPTP_CONN * conn);
2200 +void   pptp_conn_closure_put(PPTP_CONN * conn, void *cl);
2201 +void * pptp_call_closure_get(PPTP_CONN * conn, PPTP_CALL * call);
2202 +void   pptp_call_closure_put(PPTP_CONN * conn, PPTP_CALL * call, void *cl);
2203 +
2204 +#endif /* INC_PPTP_CTRL_H */
2205 --- /dev/null
2206 +++ b/pppd/plugins/pptp/pptp_msg.h
2207 @@ -0,0 +1,303 @@
2208 +/*  pptp.h:  packet structures and magic constants for the PPTP protocol 
2209 + *           C. Scott Ananian <cananian@alumni.princeton.edu>            
2210 + *
2211 + * $Id: pptp_msg.h,v 1.3 2003/02/15 10:37:21 quozl Exp $
2212 + */
2213 +
2214 +#ifndef INC_PPTP_H
2215 +#define INC_PPTP_H
2216 +
2217 +/* Grab definitions of int16, int32, etc. */
2218 +#include <sys/types.h>
2219 +/* define "portable" htons, etc. */
2220 +#define hton8(x)  (x)
2221 +#define ntoh8(x)  (x)
2222 +#define hton16(x) htons(x)
2223 +#define ntoh16(x) ntohs(x)
2224 +#define hton32(x) htonl(x)
2225 +#define ntoh32(x) ntohl(x)
2226 +
2227 +/* PPTP magic numbers: ----------------------------------------- */
2228 +
2229 +#define PPTP_MAGIC 0x1A2B3C4D /* Magic cookie for PPTP datagrams */
2230 +#define PPTP_PORT  1723       /* PPTP TCP port number            */
2231 +#define PPTP_PROTO 47         /* PPTP IP protocol number         */
2232 +
2233 +/* Control Connection Message Types: --------------------------- */
2234 +
2235 +#define PPTP_MESSAGE_CONTROL           1
2236 +#define PPTP_MESSAGE_MANAGE            2
2237 +
2238 +/* Control Message Types: -------------------------------------- */
2239 +
2240 +/* (Control Connection Management) */
2241 +#define PPTP_START_CTRL_CONN_RQST      1
2242 +#define PPTP_START_CTRL_CONN_RPLY      2
2243 +#define PPTP_STOP_CTRL_CONN_RQST       3
2244 +#define PPTP_STOP_CTRL_CONN_RPLY       4
2245 +#define PPTP_ECHO_RQST                 5
2246 +#define PPTP_ECHO_RPLY                 6
2247 +
2248 +/* (Call Management) */
2249 +#define PPTP_OUT_CALL_RQST             7
2250 +#define PPTP_OUT_CALL_RPLY             8
2251 +#define PPTP_IN_CALL_RQST              9
2252 +#define PPTP_IN_CALL_RPLY              10
2253 +#define PPTP_IN_CALL_CONNECT           11
2254 +#define PPTP_CALL_CLEAR_RQST           12
2255 +#define PPTP_CALL_CLEAR_NTFY           13
2256 +
2257 +/* (Error Reporting) */
2258 +#define PPTP_WAN_ERR_NTFY              14
2259 +
2260 +/* (PPP Session Control) */
2261 +#define PPTP_SET_LINK_INFO             15
2262 +
2263 +/* PPTP version information: --------------------------------------*/
2264 +#define PPTP_VERSION_STRING    "1.00"
2265 +#define PPTP_VERSION           0x100
2266 +#define PPTP_FIRMWARE_STRING   "0.01"
2267 +#define PPTP_FIRMWARE_VERSION  0x001
2268 +
2269 +/* PPTP capabilities: ---------------------------------------------*/
2270 +
2271 +/* (Framing capabilities for msg sender) */
2272 +#define PPTP_FRAME_ASYNC       1
2273 +#define PPTP_FRAME_SYNC                2
2274 +#define PPTP_FRAME_ANY          3
2275 +
2276 +/* (Bearer capabilities for msg sender) */
2277 +#define PPTP_BEARER_ANALOG     1
2278 +#define PPTP_BEARER_DIGITAL    2
2279 +#define PPTP_BEARER_ANY                3
2280 +
2281 +#define PPTP_RESULT_GENERAL_ERROR 2
2282 +
2283 +/* (Reasons to close a connection) */
2284 +#define PPTP_STOP_NONE           1 /* no good reason                        */
2285 +#define PPTP_STOP_PROTOCOL       2 /* can't support peer's protocol version */
2286 +#define PPTP_STOP_LOCAL_SHUTDOWN  3 /* requester is being shut down          */
2287 +
2288 +/* PPTP datagram structures (all data in network byte order): ----------*/
2289 +
2290 +struct pptp_header {
2291 +  u_int16_t length;      /* message length in octets, including header */
2292 +  u_int16_t pptp_type;   /* PPTP message type. 1 for control message.  */
2293 +  u_int32_t magic;       /* this should be PPTP_MAGIC.                 */
2294 +  u_int16_t ctrl_type;   /* Control message type (0-15)                */
2295 +  u_int16_t reserved0;   /* reserved.  MUST BE ZERO.                   */
2296 +};
2297 +
2298 +struct pptp_start_ctrl_conn { /* for control message types 1 and 2 */
2299 +  struct pptp_header header;
2300 +
2301 +  u_int16_t version;      /* PPTP protocol version.  = PPTP_VERSION     */
2302 +  u_int8_t  result_code;  /* these two fields should be zero on rqst msg*/
2303 +  u_int8_t  error_code;   /* 0 unless result_code==2 (General Error)    */
2304 +  u_int32_t framing_cap;  /* Framing capabilities                       */
2305 +  u_int32_t bearer_cap;   /* Bearer Capabilities                        */
2306 +  u_int16_t max_channels; /* Maximum Channels (=0 for PNS, PAC ignores) */
2307 +  u_int16_t firmware_rev; /* Firmware or Software Revision              */
2308 +  u_int8_t  hostname[64]; /* Host Name (64 octets, zero terminated)     */
2309 +  u_int8_t  vendor[64];   /* Vendor string (64 octets, zero term.)      */
2310 +  /* MS says that end of hostname/vendor fields should be filled with   */
2311 +  /* octets of value 0, but Win95 PPTP driver doesn't do this.          */
2312 +};
2313 +
2314 +struct pptp_stop_ctrl_conn { /* for control message types 3 and 4 */
2315 +  struct pptp_header header;
2316 +
2317 +  u_int8_t reason_result; /* reason for rqst, result for rply          */
2318 +  u_int8_t error_code;   /* MUST be 0, unless rply result==2 (general err)*/
2319 +  u_int16_t reserved1;    /* MUST be 0                                */
2320 +};
2321 +
2322 +struct pptp_echo_rqst { /* for control message type 5 */
2323 +  struct pptp_header header;
2324 +  u_int32_t identifier;   /* arbitrary value set by sender which is used */
2325 +                          /* to match up reply and request               */
2326 +};
2327 +
2328 +struct pptp_echo_rply { /* for control message type 6 */
2329 +  struct pptp_header header;
2330 +  u_int32_t identifier;          /* should correspond to id of rqst             */
2331 +  u_int8_t result_code;
2332 +  u_int8_t error_code;    /* =0, unless result_code==2 (general error)   */
2333 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2334 +};
2335 +
2336 +struct pptp_out_call_rqst { /* for control message type 7 */
2337 +  struct pptp_header header;
2338 +  u_int16_t call_id;     /* Call ID (unique id used to multiplex data)  */
2339 +  u_int16_t call_sernum;  /* Call Serial Number (used for logging)       */
2340 +  u_int32_t bps_min;      /* Minimum BPS (lowest acceptable line speed)  */
2341 +  u_int32_t bps_max;     /* Maximum BPS (highest acceptable line speed) */
2342 +  u_int32_t bearer;      /* Bearer type                                 */
2343 +  u_int32_t framing;      /* Framing type                                */
2344 +  u_int16_t recv_size;   /* Recv. Window Size (no. of buffered packets) */
2345 +  u_int16_t delay;       /* Packet Processing Delay (in 1/10 sec)       */
2346 +  u_int16_t phone_len;   /* Phone Number Length (num. of valid digits)  */
2347 +  u_int16_t reserved1;    /* MUST BE ZERO                               */
2348 +  u_int8_t  phone_num[64]; /* Phone Number (64 octets, null term.)       */
2349 +  u_int8_t subaddress[64]; /* Subaddress (64 octets, null term.)         */
2350 +};
2351 +
2352 +struct pptp_out_call_rply { /* for control message type 8 */
2353 +  struct pptp_header header;
2354 +  u_int16_t call_id;      /* Call ID (used to multiplex data over tunnel)*/
2355 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/
2356 +  u_int8_t  result_code;  /* Result Code (1 is no errors)                */
2357 +  u_int8_t  error_code;   /* Error Code (=0 unless result_code==2)       */
2358 +  u_int16_t cause_code;   /* Cause Code (addt'l failure information)     */
2359 +  u_int32_t speed;        /* Connect Speed (in BPS)                      */
2360 +  u_int16_t recv_size;    /* Recv. Window Size (no. of buffered packets) */
2361 +  u_int16_t delay;       /* Packet Processing Delay (in 1/10 sec)       */
2362 +  u_int32_t channel;      /* Physical Channel ID (for logging)           */
2363 +};
2364 +
2365 +struct pptp_in_call_rqst { /* for control message type 9 */
2366 +  struct pptp_header header;
2367 +  u_int16_t call_id;     /* Call ID (unique id used to multiplex data)  */
2368 +  u_int16_t call_sernum;  /* Call Serial Number (used for logging)       */
2369 +  u_int32_t bearer;      /* Bearer type                                 */
2370 +  u_int32_t channel;      /* Physical Channel ID (for logging)           */
2371 +  u_int16_t dialed_len;   /* Dialed Number Length (# of valid digits)    */
2372 +  u_int16_t dialing_len;  /* Dialing Number Length (# of valid digits)   */
2373 +  u_int8_t dialed_num[64]; /* Dialed Number (64 octets, zero term.)      */
2374 +  u_int8_t dialing_num[64]; /* Dialing Number (64 octets, zero term.)    */
2375 +  u_int8_t subaddress[64];  /* Subaddress (64 octets, zero term.)        */
2376 +};
2377 +
2378 +struct pptp_in_call_rply { /* for control message type 10 */
2379 +  struct pptp_header header;
2380 +  u_int16_t call_id;      /* Call ID (used to multiplex data over tunnel)*/
2381 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/
2382 +  u_int8_t  result_code;  /* Result Code (1 is no errors)                */
2383 +  u_int8_t  error_code;   /* Error Code (=0 unless result_code==2)       */
2384 +  u_int16_t recv_size;    /* Recv. Window Size (no. of buffered packets) */
2385 +  u_int16_t delay;       /* Packet Processing Delay (in 1/10 sec)       */
2386 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2387 +};
2388 +
2389 +struct pptp_in_call_connect { /* for control message type 11 */
2390 +  struct pptp_header header;
2391 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/
2392 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2393 +  u_int32_t speed;        /* Connect Speed (in BPS)                      */
2394 +  u_int16_t recv_size;    /* Recv. Window Size (no. of buffered packets) */
2395 +  u_int16_t delay;       /* Packet Processing Delay (in 1/10 sec)       */
2396 +  u_int32_t framing;      /* Framing type                                */
2397 +};
2398 +
2399 +struct pptp_call_clear_rqst { /* for control message type 12 */
2400 +  struct pptp_header header;
2401 +  u_int16_t call_id;      /* Call ID (used to multiplex data over tunnel)*/
2402 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2403 +};
2404 +
2405 +struct pptp_call_clear_ntfy { /* for control message type 13 */
2406 +  struct pptp_header header;
2407 +  u_int16_t call_id;      /* Call ID (used to multiplex data over tunnel)*/
2408 +  u_int8_t  result_code;  /* Result Code                                 */
2409 +  u_int8_t  error_code;   /* Error Code (=0 unless result_code==2)       */
2410 +  u_int16_t cause_code;   /* Cause Code (for ISDN, is Q.931 cause code)  */
2411 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2412 +  u_int8_t call_stats[128]; /* Call Statistics: 128 octets, ascii, 0-term */
2413 +};
2414 +
2415 +struct pptp_wan_err_ntfy {    /* for control message type 14 */
2416 +  struct pptp_header header;
2417 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst)*/
2418 +  u_int16_t reserved1;    /* MUST BE ZERO                                */
2419 +  u_int32_t crc_errors;   /* CRC errors                                 */
2420 +  u_int32_t frame_errors; /* Framing errors                             */
2421 +  u_int32_t hard_errors;  /* Hardware overruns                                  */
2422 +  u_int32_t buff_errors;  /* Buffer overruns                            */
2423 +  u_int32_t time_errors;  /* Time-out errors                            */
2424 +  u_int32_t align_errors; /* Alignment errors                           */
2425 +};
2426 +
2427 +struct pptp_set_link_info {   /* for control message type 15 */
2428 +  struct pptp_header header;
2429 +  u_int16_t call_id_peer; /* Peer's Call ID (call_id of pptp_out_call_rqst) */
2430 +  u_int16_t reserved1;    /* MUST BE ZERO                                   */
2431 +  u_int32_t send_accm;    /* Send ACCM (for PPP packets; default 0xFFFFFFFF)*/
2432 +  u_int32_t recv_accm;    /* Receive ACCM (for PPP pack.;default 0xFFFFFFFF)*/
2433 +};
2434 +
2435 +/* helpful #defines: -------------------------------------------- */
2436 +#define pptp_isvalid_ctrl(header, type, length) \
2437 + (!( ( ntoh16(((struct pptp_header *)header)->length)    < (length)  ) ||   \
2438 +     ( ntoh16(((struct pptp_header *)header)->pptp_type) !=(type)    ) ||   \
2439 +     ( ntoh32(((struct pptp_header *)header)->magic)     !=PPTP_MAGIC) ||   \
2440 +     ( ntoh16(((struct pptp_header *)header)->ctrl_type) > PPTP_SET_LINK_INFO) || \
2441 +     ( ntoh16(((struct pptp_header *)header)->reserved0) !=0         ) ))
2442 +
2443 +#define PPTP_HEADER_CTRL(type)  \
2444 +{ hton16(PPTP_CTRL_SIZE(type)), \
2445 +  hton16(PPTP_MESSAGE_CONTROL), \
2446 +  hton32(PPTP_MAGIC),           \
2447 +  hton16(type), 0 }             
2448 +
2449 +#define PPTP_CTRL_SIZE(type) ( \
2450 +(type==PPTP_START_CTRL_CONN_RQST)?sizeof(struct pptp_start_ctrl_conn): \
2451 +(type==PPTP_START_CTRL_CONN_RPLY)?sizeof(struct pptp_start_ctrl_conn): \
2452 +(type==PPTP_STOP_CTRL_CONN_RQST )?sizeof(struct pptp_stop_ctrl_conn):  \
2453 +(type==PPTP_STOP_CTRL_CONN_RPLY )?sizeof(struct pptp_stop_ctrl_conn):  \
2454 +(type==PPTP_ECHO_RQST           )?sizeof(struct pptp_echo_rqst):       \
2455 +(type==PPTP_ECHO_RPLY           )?sizeof(struct pptp_echo_rply):       \
2456 +(type==PPTP_OUT_CALL_RQST       )?sizeof(struct pptp_out_call_rqst):   \
2457 +(type==PPTP_OUT_CALL_RPLY       )?sizeof(struct pptp_out_call_rply):   \
2458 +(type==PPTP_IN_CALL_RQST        )?sizeof(struct pptp_in_call_rqst):    \
2459 +(type==PPTP_IN_CALL_RPLY        )?sizeof(struct pptp_in_call_rply):    \
2460 +(type==PPTP_IN_CALL_CONNECT     )?sizeof(struct pptp_in_call_connect): \
2461 +(type==PPTP_CALL_CLEAR_RQST     )?sizeof(struct pptp_call_clear_rqst): \
2462 +(type==PPTP_CALL_CLEAR_NTFY     )?sizeof(struct pptp_call_clear_ntfy): \
2463 +(type==PPTP_WAN_ERR_NTFY        )?sizeof(struct pptp_wan_err_ntfy):    \
2464 +(type==PPTP_SET_LINK_INFO       )?sizeof(struct pptp_set_link_info):   \
2465 +0)
2466 +#define max(a,b) (((a)>(b))?(a):(b))
2467 +#define PPTP_CTRL_SIZE_MAX (                   \
2468 +max(sizeof(struct pptp_start_ctrl_conn),       \
2469 +max(sizeof(struct pptp_echo_rqst),             \
2470 +max(sizeof(struct pptp_echo_rply),             \
2471 +max(sizeof(struct pptp_out_call_rqst),         \
2472 +max(sizeof(struct pptp_out_call_rply),         \
2473 +max(sizeof(struct pptp_in_call_rqst),          \
2474 +max(sizeof(struct pptp_in_call_rply),          \
2475 +max(sizeof(struct pptp_in_call_connect),       \
2476 +max(sizeof(struct pptp_call_clear_rqst),       \
2477 +max(sizeof(struct pptp_call_clear_ntfy),       \
2478 +max(sizeof(struct pptp_wan_err_ntfy),          \
2479 +max(sizeof(struct pptp_set_link_info), 0)))))))))))))
2480 +
2481 +
2482 +/* gre header structure: -------------------------------------------- */
2483 +
2484 +#define PPTP_GRE_PROTO  0x880B
2485 +#define PPTP_GRE_VER    0x1
2486 +
2487 +#define PPTP_GRE_FLAG_C        0x80
2488 +#define PPTP_GRE_FLAG_R        0x40
2489 +#define PPTP_GRE_FLAG_K        0x20
2490 +#define PPTP_GRE_FLAG_S        0x10
2491 +#define PPTP_GRE_FLAG_A        0x80
2492 +
2493 +#define PPTP_GRE_IS_C(f) ((f)&PPTP_GRE_FLAG_C)
2494 +#define PPTP_GRE_IS_R(f) ((f)&PPTP_GRE_FLAG_R)
2495 +#define PPTP_GRE_IS_K(f) ((f)&PPTP_GRE_FLAG_K)
2496 +#define PPTP_GRE_IS_S(f) ((f)&PPTP_GRE_FLAG_S)
2497 +#define PPTP_GRE_IS_A(f) ((f)&PPTP_GRE_FLAG_A)
2498 +
2499 +struct pptp_gre_header {
2500 +  u_int8_t flags;              /* bitfield */
2501 +  u_int8_t ver;                        /* should be PPTP_GRE_VER (enhanced GRE) */
2502 +  u_int16_t protocol;          /* should be PPTP_GRE_PROTO (ppp-encaps) */
2503 +  u_int16_t payload_len;       /* size of ppp payload, not inc. gre header */
2504 +  u_int16_t call_id;           /* peer's call_id for this session */
2505 +  u_int32_t seq;               /* sequence number.  Present if S==1 */
2506 +  u_int32_t ack;               /* seq number of highest packet recieved by */
2507 +                               /*  sender in this session */
2508 +};
2509 +
2510 +#endif /* INC_PPTP_H */
2511 --- /dev/null
2512 +++ b/pppd/plugins/pptp/pptp_options.h
2513 @@ -0,0 +1,41 @@
2514 +/* pptp_options.h ...... various constants used in the PPTP protocol.
2515 + *                       #define STANDARD to emulate NT 4.0 exactly.
2516 + *                       C. Scott Ananian <cananian@alumni.princeton.edu>
2517 + *
2518 + * $Id: pptp_options.h,v 1.3 2004/11/09 01:42:32 quozl Exp $
2519 + */
2520 +
2521 +#ifndef INC_PPTP_OPTIONS_H
2522 +#define INC_PPTP_OPTIONS_H
2523 +
2524 +#undef  PPTP_FIRMWARE_STRING
2525 +#undef  PPTP_FIRMWARE_VERSION
2526 +#define PPTP_BUF_MAX 65536
2527 +#define PPTP_TIMEOUT 60 /* seconds */
2528 +extern int idle_wait;
2529 +extern int max_echo_wait;
2530 +#define PPTP_CONNECT_SPEED 1000000000
2531 +#define PPTP_WINDOW 3
2532 +#define PPTP_DELAY  0
2533 +#define PPTP_BPS_MIN 2400
2534 +#define PPTP_BPS_MAX 1000000000
2535 +
2536 +#ifndef STANDARD
2537 +#define PPTP_MAX_CHANNELS 65535
2538 +#define PPTP_FIRMWARE_STRING "0.01"
2539 +#define PPTP_FIRMWARE_VERSION 0x001
2540 +#define PPTP_HOSTNAME {'l','o','c','a','l',0}
2541 +#define PPTP_VENDOR   {'c','a','n','a','n','i','a','n',0}
2542 +#define PPTP_FRAME_CAP  PPTP_FRAME_ANY
2543 +#define PPTP_BEARER_CAP PPTP_BEARER_ANY
2544 +#else
2545 +#define PPTP_MAX_CHANNELS 5
2546 +#define PPTP_FIRMWARE_STRING "0.01"
2547 +#define PPTP_FIRMWARE_VERSION 0
2548 +#define PPTP_HOSTNAME {'l','o','c','a','l',0}
2549 +#define PPTP_VENDOR   {'N','T',0}
2550 +#define PPTP_FRAME_CAP  2
2551 +#define PPTP_BEARER_CAP 1
2552 +#endif
2553 +
2554 +#endif /* INC_PPTP_OPTIONS_H */
2555 --- /dev/null
2556 +++ b/pppd/plugins/pptp/pptp_quirks.c
2557 @@ -0,0 +1,54 @@
2558 +/* pptp_quirks.c ...... various options to fix quirks found in buggy adsl modems
2559 + *                      mulix <mulix@actcom.co.il>
2560 + *
2561 + * $Id: pptp_quirks.c,v 1.2 2001/11/23 03:42:51 quozl Exp $
2562 + */
2563 +
2564 +#include <string.h>
2565 +#include "orckit_quirks.h"
2566 +#include "pptp_quirks.h"
2567 +
2568 +static int quirk_index = -1;
2569 +
2570 +struct pptp_fixup pptp_fixups[] = {
2571 +    {BEZEQ_ISRAEL, ORCKIT, ORCKIT_ATUR3,
2572 +     orckit_atur3_build_hook,
2573 +     orckit_atur3_start_ctrl_conn_hook,
2574 +     orckit_atur3_set_link_hook}
2575 +};
2576 +
2577 +static int fixups_sz = sizeof(pptp_fixups)/sizeof(pptp_fixups[0]);
2578 +
2579 +/* return 0 on success, non 0 otherwise */
2580 +int set_quirk_index(int index)
2581 +{
2582 +    if (index >= 0 && index < fixups_sz) {
2583 +       quirk_index = index;
2584 +       return 0;
2585 +    }
2586 +
2587 +    return -1;
2588 +}
2589 +
2590 +int get_quirk_index()
2591 +{
2592 +    return quirk_index;
2593 +}
2594 +
2595 +/* return the index for this isp in the quirks table, -1 if not found */
2596 +int find_quirk(const char* isp_name)
2597 +{
2598 +    int i = 0;
2599 +    if (isp_name) {
2600 +       while (i < fixups_sz && pptp_fixups[i].isp) {
2601 +           if (!strcmp(pptp_fixups[i].isp, isp_name)) {
2602 +               return i;
2603 +           }
2604 +           ++i;
2605 +       }
2606 +    }
2607 +
2608 +    return -1;
2609 +}
2610 +
2611 +
2612 --- /dev/null
2613 +++ b/pppd/plugins/pptp/pptp_quirks.h
2614 @@ -0,0 +1,59 @@
2615 +/* pptp_quirks.h ...... various options to fix quirks found in buggy adsl modems
2616 + *                      mulix <mulix@actcom.co.il>
2617 + *
2618 + * $Id: pptp_quirks.h,v 1.1 2001/11/20 06:30:10 quozl Exp $
2619 + */
2620 +
2621 +#ifndef INC_PPTP_QUIRKS_H
2622 +#define INC_PPTP_QUIRKS_H
2623 +
2624 +/* isp defs - correspond to slots in the fixups table */
2625 +#define BEZEQ_ISRAEL "BEZEQ_ISRAEL"
2626 +
2627 +/* vendor defs */
2628 +
2629 +#define ORCKIT 1
2630 +#define ALCATEL 2
2631 +
2632 +/* device defs */
2633 +
2634 +#define ORCKIT_ATUR2 1
2635 +#define ORCKIT_ATUR3 2
2636 +
2637 +#include "pptp_msg.h"
2638 +#include "pptp_ctrl.h"
2639 +
2640 +struct pptp_fixup {
2641 +    const char* isp;    /* which isp? e.g. Bezeq in Israel */
2642 +    int vendor; /* which vendor? e.g. Orckit */
2643 +    int device; /* which device? e.g. Orckit Atur3 */
2644 +
2645 +    /* use this hook to build your own out call request packet */
2646 +    int (*out_call_rqst_hook)(struct pptp_out_call_rqst* packet);
2647 +
2648 +    /* use this hook to build your own start control connection packet */
2649 +    /* note that this hook is called from two different places, depending
2650 +       on whether this is a request or reply */
2651 +    int (*start_ctrl_conn)(struct pptp_start_ctrl_conn* packet);
2652 +
2653 +    /* use this hook if you need to send a 'set_link' packet once
2654 +       the connection is established */
2655 +    int (*set_link_hook)(struct pptp_set_link_info* packet,
2656 +                        int peer_call_id);
2657 +};
2658 +
2659 +extern struct pptp_fixup pptp_fixups[];
2660 +
2661 +/* find the index for this isp in the quirks table */
2662 +/* return the index on success, -1 if not found */
2663 +int find_quirk(const char* isp_name);
2664 +
2665 +/* set the global quirk index. return 0 on success, non 0 otherwise */
2666 +int set_quirk_index(int index);
2667 +
2668 +/* get the global quirk index. return the index on success,
2669 +   -1 if no quirk is defined */
2670 +int get_quirk_index();
2671 +
2672 +
2673 +#endif /* INC_PPTP_QUIRKS_H */
2674 --- /dev/null
2675 +++ b/pppd/plugins/pptp/util.c
2676 @@ -0,0 +1,109 @@
2677 +/* util.c ....... error message utilities.
2678 + *                C. Scott Ananian <cananian@alumni.princeton.edu>
2679 + *
2680 + * $Id: util.c,v 1.11 2005/08/22 00:49:48 quozl Exp $
2681 + */
2682 +
2683 +#include <stdio.h>
2684 +#include <stdarg.h>
2685 +#include <syslog.h>
2686 +#include <unistd.h>
2687 +#include <stdlib.h>
2688 +#include "util.h"
2689 +
2690 +#define MAKE_STRING(label)                             \
2691 +va_list ap;                                            \
2692 +char buf[256], string[256];                            \
2693 +va_start(ap, format);                                  \
2694 +vsnprintf(buf, sizeof(buf), format, ap);               \
2695 +snprintf(string, sizeof(string), "%s %s[%s:%s:%d]: %s",        \
2696 +        log_string, label, func, file, line, buf);     \
2697 +va_end(ap)
2698 +
2699 +/*** connect a file to a file descriptor **************************************/
2700 +int file2fd(const char *path, const char *mode, int fd)
2701 +{
2702 +    int ok = 0;
2703 +    FILE *file = NULL;
2704 +    file = fopen(path, mode);
2705 +    if (file != NULL && dup2(fileno(file), fd) != -1)
2706 +        ok = 1;
2707 +    if (file) fclose(file);
2708 +    return ok;
2709 +}
2710 +
2711 +/* signal to pipe delivery implementation */
2712 +#include <unistd.h>
2713 +#include <fcntl.h>
2714 +#include <signal.h>
2715 +#include <string.h>
2716 +
2717 +/* pipe private to process */
2718 +static int sigpipe[2];
2719 +
2720 +/* create a signal pipe, returns 0 for success, -1 with errno for failure */
2721 +int sigpipe_create()
2722 +{
2723 +  int rc;
2724 +  
2725 +  rc = pipe(sigpipe);
2726 +  if (rc < 0) return rc;
2727 +  
2728 +  fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC);
2729 +  fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC);
2730 +  
2731 +#ifdef O_NONBLOCK
2732 +#define FLAG_TO_SET O_NONBLOCK
2733 +#else
2734 +#ifdef SYSV
2735 +#define FLAG_TO_SET O_NDELAY
2736 +#else /* BSD */
2737 +#define FLAG_TO_SET FNDELAY
2738 +#endif
2739 +#endif
2740 +  
2741 +  rc = fcntl(sigpipe[1], F_GETFL);
2742 +  if (rc != -1)
2743 +    rc = fcntl(sigpipe[1], F_SETFL, rc | FLAG_TO_SET);
2744 +  if (rc < 0) return rc;
2745 +  return 0;
2746 +#undef FLAG_TO_SET
2747 +}
2748 +
2749 +/* generic handler for signals, writes signal number to pipe */
2750 +void sigpipe_handler(int signum)
2751 +{
2752 +  write(sigpipe[1], &signum, sizeof(signum));
2753 +  signal(signum, sigpipe_handler);
2754 +}
2755 +
2756 +/* assign a signal number to the pipe */
2757 +void sigpipe_assign(int signum)
2758 +{
2759 +  struct sigaction sa;
2760 +
2761 +  memset(&sa, 0, sizeof(sa));
2762 +  sa.sa_handler = sigpipe_handler;
2763 +  sigaction(signum, &sa, NULL);
2764 +}
2765 +
2766 +/* return the signal pipe read file descriptor for select(2) */
2767 +int sigpipe_fd()
2768 +{
2769 +  return sigpipe[0];
2770 +}
2771 +
2772 +/* read and return the pending signal from the pipe */
2773 +int sigpipe_read()
2774 +{
2775 +  int signum;
2776 +  read(sigpipe[0], &signum, sizeof(signum));
2777 +  return signum;
2778 +}
2779 +
2780 +void sigpipe_close()
2781 +{
2782 +  close(sigpipe[0]);
2783 +  close(sigpipe[1]);
2784 +}
2785 +
2786 --- /dev/null
2787 +++ b/pppd/plugins/pptp/util.h
2788 @@ -0,0 +1,31 @@
2789 +/* util.h ....... error message utilities.
2790 + *                C. Scott Ananian <cananian@alumni.princeton.edu>
2791 + *
2792 + * $Id: util.h,v 1.6 2005/03/10 01:18:20 quozl Exp $
2793 + */
2794 +
2795 +#ifndef INC_UTIL_H
2796 +#define INC_UTIL_H
2797 +
2798 +int file2fd(const char *path, const char *mode, int fd);
2799 +
2800 +/* signal to pipe delivery implementation */
2801 +
2802 +/* create a signal pipe, returns 0 for success, -1 with errno for failure */
2803 +int sigpipe_create();
2804 +
2805 +/* generic handler for signals, writes signal number to pipe */
2806 +void sigpipe_handler(int signum);
2807 +
2808 +/* assign a signal number to the pipe */
2809 +void sigpipe_assign(int signum);
2810 +
2811 +/* return the signal pipe read file descriptor for select(2) */
2812 +int sigpipe_fd();
2813 +
2814 +/* read and return the pending signal from the pipe */
2815 +int sigpipe_read();
2816 +
2817 +void sigpipe_close();
2818 +
2819 +#endif /* INC_UTIL_H */
2820 --- /dev/null
2821 +++ b/pppd/plugins/pptp/vector.c
2822 @@ -0,0 +1,209 @@
2823 +/* vector.c ..... store a vector of PPTP_CALL information and search it
2824 + *                efficiently.
2825 + *                C. Scott Ananian <cananian@alumni.princeton.edu>
2826 + *
2827 + * $Id: vector.c,v 1.3 2003/06/17 10:12:55 reink Exp $
2828 + */
2829 +
2830 +#include <stdlib.h>
2831 +#include <string.h>
2832 +#include <assert.h>
2833 +#include "pptp_ctrl.h"
2834 +#include "vector.h"
2835 +/* #define VECTOR_DEBUG */
2836 +#ifndef TRUE
2837 +#define TRUE 1
2838 +#endif
2839 +#ifndef FALSE
2840 +#define FALSE 0
2841 +#endif
2842 +
2843 +struct vector_item {
2844 +    int key;
2845 +    PPTP_CALL *call;
2846 +};
2847 +
2848 +struct vector_struct {
2849 +    struct vector_item *item;
2850 +    int size;
2851 +    int alloc;
2852 +#ifdef VECTOR_DEBUG
2853 +    int key_max;
2854 +#endif
2855 +};
2856 +
2857 +static struct vector_item *binary_search(VECTOR *v, int key);
2858 +
2859 +/*** vector_create ************************************************************/
2860 +VECTOR *vector_create()
2861 +{
2862 +    const int INITIAL_SIZE = 4;
2863 +
2864 +    VECTOR *v = malloc(sizeof(*v));
2865 +    if (v == NULL) return v;
2866 +
2867 +    v->size = 0;
2868 +    v->alloc = INITIAL_SIZE;
2869 +    v->item = malloc(sizeof(*(v->item)) * (v->alloc));
2870 +#ifdef VECTOR_DEBUG
2871 +    v->key_max = -1;
2872 +#endif
2873 +    if (v->item == NULL) { free(v); return NULL; }
2874 +    else return v;
2875 +}
2876 +
2877 +/*** vector_destroy ***********************************************************/
2878 +void vector_destroy(VECTOR *v)
2879 +{
2880 +    free(v->item);
2881 +#ifdef VECTOR_DEBUG
2882 +    v->item = NULL;
2883 +#endif
2884 +    free(v);
2885 +}
2886 +
2887 +/*** vector_size **************************************************************/
2888 +int vector_size(VECTOR *v)
2889 +{
2890 +    assert(v != NULL);
2891 +    return v->size;
2892 +}
2893 +
2894 +/*** vector_insert*************************************************************
2895 + * nice thing about file descriptors is that we are assured by POSIX 
2896 + * that they are monotonically increasing.
2897 + */
2898 +int vector_insert(VECTOR *v, int key, PPTP_CALL * call)
2899 +{
2900 +    int i;
2901 +    assert(v != NULL && call != NULL);
2902 +    assert(!vector_contains(v, key));
2903 +#ifdef VECTOR_DEBUG
2904 +    assert(v->key_max < key);
2905 +#endif
2906 +    if (!(v->size < v->alloc)) {
2907 +        void *tmp = realloc(v->item, sizeof(*(v->item)) * 2 * v->alloc);
2908 +        if (tmp != NULL) {
2909 +            v->alloc *= 2;
2910 +            v->item = tmp;
2911 +        } else return FALSE; /* failed to alloc memory. */
2912 +    }
2913 +    assert(v->size < v->alloc);
2914 +    /* for safety, we make this work in the general case;
2915 +     * but this is optimized for adding call to the end of the vector.
2916 +     */
2917 +    for(i = v->size - 1; i >= 0; i--)
2918 +        if (v->item[i].key < key)
2919 +            break;
2920 +    /* insert after item i */
2921 +    memmove(&v->item[i + 2], &v->item[i + 1],
2922 +            (v->size - i - 1) * sizeof(*(v->item)));
2923 +    v->item[i + 1].key  = key;
2924 +    v->item[i + 1].call = call;
2925 +    v->size++;
2926 +#ifdef VECTOR_DEBUG
2927 +    if (v->key_max < key) /* ie, always. */
2928 +        v->key_max = key;
2929 +#endif
2930 +    return TRUE;
2931 +}
2932 +
2933 +/*** vector_remove ************************************************************/
2934 +int  vector_remove(VECTOR *v, int key)
2935 +{
2936 +    struct vector_item *tmp;
2937 +    assert(v != NULL);
2938 +    if ((tmp =binary_search(v,key)) == NULL) return FALSE;
2939 +    assert(tmp >= v->item && tmp < v->item + v->size);
2940 +    memmove(tmp, tmp + 1, (v->size - (v->item - tmp) - 1) * sizeof(*(v->item)));
2941 +    v->size--;
2942 +    return TRUE;
2943 +}
2944 +
2945 +/*** vector_search ************************************************************/
2946 +int  vector_search(VECTOR *v, int key, PPTP_CALL **call)
2947 +{
2948 +    struct vector_item *tmp;
2949 +    assert(v != NULL);
2950 +    tmp = binary_search(v, key);
2951 +    if (tmp ==NULL) return FALSE;
2952 +    *call = tmp->call;
2953 +    return TRUE;
2954 +}
2955 +
2956 +/*** vector_contains **********************************************************/
2957 +int  vector_contains(VECTOR *v, int key)
2958 +{
2959 +    assert(v != NULL);
2960 +    return (binary_search(v, key) != NULL);
2961 +}
2962 +
2963 +/*** vector_item **************************************************************/
2964 +static struct vector_item *binary_search(VECTOR *v, int key)
2965 +{
2966 +    int l,r,x;
2967 +    l = 0;
2968 +    r = v->size - 1;
2969 +    while (r >= l) {
2970 +        x = (l + r)/2;
2971 +        if (key <  v->item[x].key) r = x - 1; else l = x + 1;
2972 +        if (key == v->item[x].key) return &(v->item[x]);
2973 +    }
2974 +    return NULL;
2975 +}
2976 +
2977 +/*** vector_scan ***************************************************************
2978 + * Hmm.  Let's be fancy and use a binary search for the first
2979 + * unused key, taking advantage of the list is stored sorted; ie
2980 + * we can look at pointers and keys at two different locations, 
2981 + * and if (ptr1 - ptr2) = (key1 - key2) then all the slots
2982 + * between ptr1 and ptr2 are filled.  Note that ptr1-ptr2 should
2983 + * never be greater than key1-key2 (no duplicate keys!)... we
2984 + * check for this.
2985 + */
2986 +int vector_scan(VECTOR *v, int lo, int hi, int *key)
2987 +{
2988 +    int l,r,x;
2989 +    assert(v != NULL);
2990 +    assert(key != NULL);
2991 +    if ((v->size<1) || (lo < v->item[0].key)) { *key = lo; return TRUE; }
2992 +    /* our array bounds */
2993 +    l = 0;  r = v->size - 1;
2994 +    while (r > l) {
2995 +        /* check for a free spot right after l */
2996 +        if (v->item[l].key + 1 < v->item[l + 1].key) { /* found it! */
2997 +            *key = v->item[l].key + 1;
2998 +            return TRUE;
2999 +        }
3000 +        /* no dice. Let's see if the free spot is before or after the midpoint */
3001 +        x = (l + r)/2;
3002 +        /* Okay, we have right (r), left (l) and the probe (x). */
3003 +        assert(x - l <= v->item[x].key - v->item[l].key);
3004 +        assert(r - x <= v->item[r].key - v->item[x].key);
3005 +        if (x - l < v->item[x].key - v->item[l].key)
3006 +            /* room between l and x */
3007 +            r = x;
3008 +        else /* no room between l and x */
3009 +            if (r - x < v->item[r].key - v->item[x].key)
3010 +                /* room between x and r */
3011 +                l = x;
3012 +            else /* no room between x and r, either */
3013 +                break; /* game over, man. */
3014 +    }
3015 +    /* no room found in already allocated space.  Check to see if
3016 +     * there's free space above allocated entries. */
3017 +    if (v->item[v->size - 1].key < hi) {
3018 +        *key = v->item[v->size - 1].key + 1;
3019 +        return TRUE;
3020 +    }
3021 +    /* outta luck */
3022 +    return FALSE;
3023 +}
3024 +
3025 +/*** vector_get_Nth ***********************************************************/
3026 +PPTP_CALL * vector_get_Nth(VECTOR *v, int n)
3027 +{
3028 +    assert(v != NULL);
3029 +    assert(0 <= n && n < vector_size(v));
3030 +    return v->item[n].call;
3031 +}
3032 --- /dev/null
3033 +++ b/pppd/plugins/pptp/vector.h
3034 @@ -0,0 +1,31 @@
3035 +/* vector.h ..... store a vector of PPTP_CALL information and search it
3036 + *                efficiently.
3037 + *                C. Scott Ananian <cananian@alumni.princeton.edu>
3038 + *
3039 + * $Id: vector.h,v 1.1.1.1 2000/12/23 08:19:51 scott Exp $
3040 + */
3041 +
3042 +#ifndef INC_VECTOR_H
3043 +#define INC_VECTOR_H
3044 +
3045 +#include "pptp_ctrl.h" /* for definition of PPTP_CALL */
3046 +
3047 +typedef struct vector_struct VECTOR;
3048 +
3049 +VECTOR *vector_create();
3050 +void vector_destroy(VECTOR *v);
3051 +
3052 +int vector_size(VECTOR *v);
3053 +
3054 +/* vector_insert and vector_search return TRUE on success, FALSE on failure. */
3055 +int  vector_insert(VECTOR *v, int key, PPTP_CALL * call);
3056 +int  vector_remove(VECTOR *v, int key);
3057 +int  vector_search(VECTOR *v, int key, PPTP_CALL ** call);
3058 +/* vector_contains returns FALSE if not found, TRUE if found. */
3059 +int  vector_contains(VECTOR *v, int key);
3060 +/* find first unused key. Returns TRUE on success, FALSE if no. */
3061 +int  vector_scan(VECTOR *v, int lo, int hi, int *key);
3062 +/* get a specific PPTP_CALL ... useful only when iterating. */
3063 +PPTP_CALL * vector_get_Nth(VECTOR *v, int n);
3064 +
3065 +#endif /* INC_VECTOR_H */