summaryrefslogtreecommitdiffstats
path: root/stap-server-connect.c
blob: cbbc97d186a926dd306b4de3ee62a0894e7e097e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
/*
  SSL server program listens on a port, accepts client connection, reads
  the data into a temporary file, calls the systemtap server script and
  then transmits the resulting fileback to the client.

  Copyright (C) 2008, 2009 Red Hat Inc.

  This file is part of systemtap, and is free software.  You can
  redistribute it and/or modify it under the terms of the GNU General Public
  License as published by the Free Software Foundation; either version 2 of the
  License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <ssl.h>
#include <nspr.h>
#include <plgetopt.h>
#include <nss.h>
#include <pk11func.h>

#include "nsscommon.h"

#define READ_BUFFER_SIZE (60 * 1024)

/* Global variables */
static char             *password = NULL;
static CERTCertificate  *cert = NULL;
static SECKEYPrivateKey *privKey = NULL;
static char             *dbdir   = NULL;
static char requestFileName[] = "/tmp/stap.server.client.zip.XXXXXX";
static char responseDirName[] = "/tmp/stap.server.XXXXXX";
static char responseZipName[] = "/tmp/stap.server.XXXXXX.zip.XXXXXX";
static const char *stapOptions = "";

static void
Usage(const char *progName)
{
  fprintf(stderr, 
	  "Usage: %s -p port -d dbdir -n rsa_nickname -w passwordFile\n",
	  progName);
  exit(1);
}

static void
errWarn(char *function)
{
  fprintf(stderr, "Error in function %s: ", function);
  nssError();
}

static void
exitErr(char *function)
{
  errWarn(function);
  /* Exit gracefully. */
  /* ignoring return value of NSS_Shutdown as code exits with 1*/
  (void) NSS_Shutdown();
  PR_Cleanup();
  exit(1);
}

/* Function:  readDataFromSocket()
 *
 * Purpose:  Read data from the socket into a temporary file.
 *
 */
static SECStatus
readDataFromSocket(PRFileDesc *sslSocket)
{
  PRFileDesc *local_file_fd;
  PRFileInfo  info;
  PRInt32     numBytesRead;
  PRInt32     numBytesWritten;
  PRInt32     totalBytes;
  char        buffer[READ_BUFFER_SIZE];

  /* Open the output file.  */
  local_file_fd = PR_Open(requestFileName, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
			  PR_IRUSR | PR_IWUSR | PR_IRGRP | PR_IWGRP | PR_IROTH);
  if (local_file_fd == NULL)
    {
      fprintf (stderr, "could not open output file %s\n", requestFileName);
      return SECFailure;
    }

  /* Read the number of bytes to be received.  */
  numBytesRead = PR_Read(sslSocket, & info.size, sizeof (info.size));
  if (numBytesRead == 0) /* EOF */
    {
      fprintf (stderr, "Error reading size of request file\n");
      return SECFailure;
    }
  if (numBytesRead < 0)
    {
      errWarn("PR_Read");
      return SECFailure;
    }

  /* Read until EOF or until the expected number of bytes has been read. */
  for (totalBytes = 0; totalBytes < info.size; totalBytes += numBytesRead)
    {
      numBytesRead = PR_Read(sslSocket, buffer, READ_BUFFER_SIZE);
      if (numBytesRead == 0)
	break;	/* EOF */
      if (numBytesRead < 0)
	{
	  errWarn("PR_Read");
	  break;
	}

      /* Write to stdout */
      numBytesWritten = PR_Write(local_file_fd, buffer, numBytesRead);
      if (numBytesWritten < 0)
	fprintf (stderr, "could not write to output file %s\n", requestFileName);
      if (numBytesWritten != numBytesRead)
	fprintf (stderr, "could not write to output file %s\n", requestFileName);
#if DEBUG
      fprintf(stderr, "***** Connection read %d bytes.\n", numBytesRead);
#if 0
      buffer[numBytesRead] = '\0';
      fprintf(stderr, "************\n%s\n************\n", buffer);
#endif
#endif
    }

  if (totalBytes != info.size)
    {
      fprintf (stderr, "Expected %d bytes, got %d\n", info.size, totalBytes);
      return SECFailure;
    }

  PR_Close(local_file_fd);

  return SECSuccess;
}

/* Function:  setupSSLSocket()
 *
 * Purpose:  Configure a socket for SSL.
 *
 *
 */
static PRFileDesc * 
setupSSLSocket(PRFileDesc *tcpSocket)
{
  PRFileDesc *sslSocket;
  SSLKEAType  certKEA;
#if 0
  int         certErr = 0;
#endif
  SECStatus   secStatus;

  /* Inport the socket into SSL.  */
  sslSocket = SSL_ImportFD(NULL, tcpSocket);
  if (sslSocket == NULL)
    {
      errWarn("SSL_ImportFD");
      goto loser;
    }
   
  /* Set the appropriate flags. */
  secStatus = SSL_OptionSet(sslSocket, SSL_SECURITY, PR_TRUE);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_OptionSet SSL_SECURITY");
      goto loser;
    }

  secStatus = SSL_OptionSet(sslSocket, SSL_HANDSHAKE_AS_SERVER, PR_TRUE);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_OptionSet:SSL_HANDSHAKE_AS_SERVER");
      goto loser;
    }

  secStatus = SSL_OptionSet(sslSocket, SSL_REQUEST_CERTIFICATE, PR_FALSE);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_OptionSet:SSL_REQUEST_CERTIFICATE");
      goto loser;
    }

  secStatus = SSL_OptionSet(sslSocket, SSL_REQUIRE_CERTIFICATE, PR_FALSE);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_OptionSet:SSL_REQUIRE_CERTIFICATE");
      goto loser;
    }

  /* Set the appropriate callback routines. */
#if 0 /* use the default */
  secStatus = SSL_AuthCertificateHook(sslSocket, myAuthCertificate, 
				      CERT_GetDefaultCertDB());
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_AuthCertificateHook");
      goto loser;
    }
#endif
#if 0 /* Use the default */
  secStatus = SSL_BadCertHook(sslSocket, 
			      (SSLBadCertHandler)myBadCertHandler, &certErr);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_BadCertHook");
      goto loser;
    }
#endif
#if 0 /* no handshake callback */
  secStatus = SSL_HandshakeCallback(sslSocket,
				    myHandshakeCallback,
				    NULL);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_HandshakeCallback");
      goto loser;
    }
#endif
  secStatus = SSL_SetPKCS11PinArg(sslSocket, password);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_HandshakeCallback");
      goto loser;
    }

  certKEA = NSS_FindCertKEAType(cert);

  secStatus = SSL_ConfigSecureServer(sslSocket, cert, privKey, certKEA);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_ConfigSecureServer");
      goto loser;
    }

  return sslSocket;

loser:
  PR_Close(tcpSocket);
  return NULL;
}

#if 0 /* No client authentication and not authenticating after each transaction.  */
/* Function:  authenticateSocket()
 *
 * Purpose:  Perform client authentication on the socket.
 *
 */
static SECStatus
authenticateSocket(PRFileDesc *sslSocket, PRBool requireCert)
{
  CERTCertificate *cert;
  SECStatus secStatus;

  /* Returns NULL if client authentication is not enabled or if the
   * client had no certificate. */
  cert = SSL_PeerCertificate(sslSocket);
  if (cert)
    {
      /* Client had a certificate, so authentication is through. */
      CERT_DestroyCertificate(cert);
      return SECSuccess;
    }

  /* Request client to authenticate itself. */
  secStatus = SSL_OptionSet(sslSocket, SSL_REQUEST_CERTIFICATE, PR_TRUE);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_OptionSet:SSL_REQUEST_CERTIFICATE");
      return SECFailure;
    }

  /* If desired, require client to authenticate itself.  Note
   * SSL_REQUEST_CERTIFICATE must also be on, as above.  */
  secStatus = SSL_OptionSet(sslSocket, SSL_REQUIRE_CERTIFICATE, requireCert);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_OptionSet:SSL_REQUIRE_CERTIFICATE");
      return SECFailure;
    }

  /* Having changed socket configuration parameters, redo handshake. */
  secStatus = SSL_ReHandshake(sslSocket, PR_TRUE);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_ReHandshake");
      return SECFailure;
    }

  /* Force the handshake to complete before moving on. */
  secStatus = SSL_ForceHandshake(sslSocket);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_ForceHandshake");
      return SECFailure;
    }

  return SECSuccess;
}
#endif /* No client authentication and not authenticating after each transaction.  */

/* Function:  writeDataToSocket
 *
 * Purpose:  Write the server's response back to the socket.
 *
 */
static SECStatus
writeDataToSocket(PRFileDesc *sslSocket)
{
  int         numBytes;
  PRFileDesc *local_file_fd;
  PRFileInfo  info;
  PRStatus    prStatus;

  /* Try to open the local file named.	
   * If successful, then write it to the client.
   */
  prStatus = PR_GetFileInfo(responseZipName, &info);
  if (prStatus != PR_SUCCESS || info.type != PR_FILE_FILE || info.size < 0)
    {
      fprintf (stderr, "Input file %s not found\n", responseZipName);
      return SECFailure;
    }

  local_file_fd = PR_Open(responseZipName, PR_RDONLY, 0);
  if (local_file_fd == NULL)
    {
      fprintf (stderr, "Could not open input file %s\n", responseZipName);
      return SECFailure;
    }

  /* Transmit the local file across the socket.
   */
  numBytes = PR_TransmitFile(sslSocket, local_file_fd, 
			     NULL, 0,
			     PR_TRANSMITFILE_KEEP_OPEN,
			     PR_INTERVAL_NO_TIMEOUT);

  /* Error in transmission. */
  if (numBytes < 0)
    {
      errWarn("PR_TransmitFile");
      return SECFailure;
    }
#if DEBUG
  /* Transmitted bytes successfully. */
  fprintf(stderr, "PR_TransmitFile wrote %d bytes from %s\n",
	  numBytes, responseZipName);
#endif

  PR_Close(local_file_fd);

  return SECSuccess;
}

/* Function:  int handle_connection()
 *
 * Purpose:  Handle a connection to a socket.
 *
 */
static SECStatus
handle_connection(PRFileDesc *tcpSocket)
{
  PRFileDesc *       sslSocket = NULL;
  SECStatus          secStatus = SECFailure;
  PRStatus           prStatus;
  PRSocketOptionData socketOption;
  PRFileInfo         info;
  char              *cmdline;
  char              *stap_server_prefix;
  int                rc;
  char              *rc1;

  /* Make sure the socket is blocking. */
  socketOption.option             = PR_SockOpt_Nonblocking;
  socketOption.value.non_blocking = PR_FALSE;
  PR_SetSocketOption(tcpSocket, &socketOption);

  sslSocket = setupSSLSocket(tcpSocket);
  if (sslSocket == NULL)
    {
      errWarn("setupSSLSocket");
      goto cleanup;
    }

  secStatus = SSL_ResetHandshake(sslSocket, /* asServer */ PR_TRUE);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_ResetHandshake");
      goto cleanup;
    }

  /* Force the handshake to complete before moving on. */
  secStatus = SSL_ForceHandshake(sslSocket);
  if (secStatus != SECSuccess)
    {
      errWarn("SSL_ForceHandshake");
      goto cleanup;
    }

  /* Create a temporary files and directories.  */
  memcpy (requestFileName + sizeof (requestFileName) - 1 - 6, "XXXXXX", 6);
  rc = mkstemp(requestFileName);
  if (rc == -1)
    {
      fprintf (stderr, "Could not create temporary file %s\n", requestFileName);
      perror ("");
      secStatus = SECFailure;
      goto cleanup;
    }

  memcpy (responseDirName + sizeof (responseDirName) - 1 - 6, "XXXXXX", 6);
  rc1 = mkdtemp(responseDirName);
  if (! rc1)
    {
      fprintf (stderr, "Could not create temporary directory %s\n", responseDirName);
      perror ("");
      secStatus = SECFailure;
      goto cleanup;
    }

  memcpy (responseZipName, responseDirName, sizeof (responseDirName) - 1);
  memcpy (responseZipName + sizeof (responseZipName) - 1 - 6, "XXXXXX", 6);
  rc = mkstemp(responseZipName);
  if (rc == -1)
    {
      fprintf (stderr, "Could not create temporary file %s\n", responseZipName);
      perror ("");
      secStatus = SECFailure;

      /* Remove this so that the other temp files will get removed in cleanup.  */
      prStatus = PR_RmDir (responseDirName);
      if (prStatus != PR_SUCCESS)
	errWarn ("PR_RmDir");
      goto cleanup;
    }

  /* Read data from the socket.
   * If the user is requesting/requiring authentication, authenticate
   * the socket.  */
#if DEBUG
  fprintf(stdout, "\nReading data from socket...\n\n");
#endif
  secStatus = readDataFromSocket(sslSocket);
  if (secStatus != SECSuccess)
    goto cleanup;

#if 0 /* Don't authenticate after each transaction */
  if (REQUEST_CERT_ALL)
    {
      fprintf(stdout, "\nAuthentication requested.\n\n");
      secStatus = authenticateSocket(sslSocket);
      if (secStatus != SECSuccess)
	goto cleanup;
    }
#endif

  /* Call the stap-server script.  */
  stap_server_prefix = getenv("SYSTEMTAP_SERVER_SCRIPTS") ?: BINDIR;
  cmdline = PORT_Alloc(strlen (stap_server_prefix) + sizeof ("/stap-server") + 1 +
		       sizeof (requestFileName) + 1 +
		       sizeof (responseDirName) + 1 +
		       sizeof (responseZipName) + 1 +
		       strlen (dbdir) + 1 +
		       1 + strlen (stapOptions) + 1 +
		       1);
  if (! cmdline) {
    errWarn ("PORT_Alloc");
    secStatus = SECFailure;
    goto cleanup;
  }

  sprintf (cmdline, "%s/stap-server %s %s %s %s '%s'", stap_server_prefix,
	   requestFileName, responseDirName, responseZipName, dbdir,
	   stapOptions);
  rc = system (cmdline);

  PR_Free (cmdline);

#if DEBUG
  fprintf(stdout, "\nWriting data to socket...\n\n");
#endif
  secStatus = writeDataToSocket(sslSocket);

cleanup:
  /* Close down the socket. */
  prStatus = PR_Close(tcpSocket);
  if (prStatus != PR_SUCCESS)
    errWarn("PR_Close");

  /* Attempt to remove temporary files, unless the temporary directory was
     not deleted by the server script.  */
  prStatus = PR_GetFileInfo(responseDirName, &info);
  if (prStatus != PR_SUCCESS)
    {
      prStatus = PR_Delete (requestFileName);
      if (prStatus != PR_SUCCESS)
	errWarn ("PR_Delete");
      prStatus = PR_Delete (responseZipName);
      if (prStatus != PR_SUCCESS)
	errWarn ("PR_Delete");
    }

  return secStatus;
}

/* Function:  int accept_connection()
 *
 * Purpose:  Accept a connection to the socket.
 *
 */
static SECStatus
accept_connection(PRFileDesc *listenSocket)
{
  PRNetAddr   addr;
  PRStatus    prStatus;
  PRFileDesc *tcpSocket;
#if 0
  SECStatus   result;
#endif

  while (PR_TRUE)
    {
#if DEBUG
      fprintf(stderr, "\n\n\nAbout to call accept.\n");
#endif

      /* Accept a connection to the socket. */
      tcpSocket = PR_Accept(listenSocket, &addr, PR_INTERVAL_NO_TIMEOUT);
      if (tcpSocket == NULL)
	{
	  errWarn("PR_Accept");
	  break;
	}

      /* Accepted the connection, now handle it. */
      /*result =*/ handle_connection (tcpSocket);
#if 0 /* Not necessary */
      if (result != SECSuccess)
	{
	  prStatus = PR_Close(tcpSocket);
	  if (prStatus != PR_SUCCESS)
	    exitErr("PR_Close");
	  break;
	}
#endif
    }

#if DEBUG
  fprintf(stderr, "Closing listen socket.\n");
#endif
  prStatus = PR_Close(listenSocket);
  if (prStatus != PR_SUCCESS)
    exitErr("PR_Close");

  return SECSuccess;
}

/* Function:  void server_main()
 *
 * Purpose:  This is the server's main function.  It configures a socket
 *			 and listens to it.
 *
 */
static void
server_main(unsigned short port, SECKEYPrivateKey *privKey, CERTCertificate *cert)
{
  SECStatus           secStatus;
  PRStatus            prStatus;
  PRFileDesc *        listenSocket;
  PRNetAddr           addr;
  PRSocketOptionData  socketOption;

  /* Create a new socket. */
  listenSocket = PR_NewTCPSocket();
  if (listenSocket == NULL)
    exitErr("PR_NewTCPSocket");

  /* Set socket to be blocking -
   * on some platforms the default is nonblocking.
   */
  socketOption.option = PR_SockOpt_Nonblocking;
  socketOption.value.non_blocking = PR_FALSE;

  prStatus = PR_SetSocketOption(listenSocket, &socketOption);
  if (prStatus != PR_SUCCESS)
    exitErr("PR_SetSocketOption");

#if 0
  /* This cipher is not on by default. The Acceptance test
   * would like it to be. Turn this cipher on.
   */
  secStatus = SSL_CipherPrefSetDefault(SSL_RSA_WITH_NULL_MD5, PR_TRUE);
  if (secStatus != SECSuccess)
    exitErr("SSL_CipherPrefSetDefault:SSL_RSA_WITH_NULL_MD5");
#endif

  /* Configure the network connection. */
  addr.inet.family = PR_AF_INET;
  addr.inet.ip	 = PR_INADDR_ANY;
  addr.inet.port	 = PR_htons(port);

  /* Bind the address to the listener socket. */
  prStatus = PR_Bind(listenSocket, &addr);
  if (prStatus != PR_SUCCESS)
    exitErr("PR_Bind");

  /* Listen for connection on the socket.  The second argument is
   * the maximum size of the queue for pending connections.
   */
  prStatus = PR_Listen(listenSocket, 5);
  if (prStatus != PR_SUCCESS)
    exitErr("PR_Listen");

  /* Handle connections to the socket. */
  secStatus = accept_connection (listenSocket);
  if (secStatus != SECSuccess)
    PR_Close(listenSocket);
}

/* Function: char * myPasswd()
 * 
 * Purpose: This function is our custom password handler that is called by
 * SSL when retreiving private certs and keys from the database. Returns a
 * pointer to a string that with a password for the database. Password pointer
 * should point to dynamically allocated memory that will be freed later.
 */
static char *
myPasswd(PK11SlotInfo *info, PRBool retry, void *arg)
{
  char * passwd = NULL;

  if (! retry && arg)
    passwd = PORT_Strdup((char *)arg);

  return passwd;
}

/* Obtain the certificate and key database password from the given file.  */
static char *
getPassword(char *fileName)
{
  PRFileDesc *local_file_fd;
  PRFileInfo  fileInfo;
  PRInt32     numBytesRead;
  PRStatus    prStatus;
  char       *password;
  PRInt32     i;

  prStatus = PR_GetFileInfo(fileName, &fileInfo);
  if (prStatus != PR_SUCCESS || fileInfo.type != PR_FILE_FILE || fileInfo.size < 0)
    {
      fprintf (stderr, "Password file %s not found\n", fileName);
      return NULL;
    }

  local_file_fd = PR_Open(fileName, PR_RDONLY, 0);
  if (local_file_fd == NULL)
    {
      fprintf (stderr, "Could not open password file %s\n", fileName);
      return NULL;
    }
      
  password = PORT_Alloc(fileInfo.size + 1);
  if (! password) {
    errWarn ("PORT_Alloc");
    return NULL;
  }

  numBytesRead = PR_Read(local_file_fd, password, fileInfo.size);
  if (numBytesRead <= 0)
    {
      fprintf (stderr, "Error reading password file\n");
      exitErr ("PR_Read");
    }

  PR_Close(local_file_fd);

  /* Keep only the first line of data.  */
  for (i = 0; i < numBytesRead; ++i)
    {
      if (password[i] == '\n' || password[i] == '\r' ||
	  password[i] == '\0')
	break;
    }
  password[i] = '\0';

  return password;
}

/* Function: int main()
 *
 * Purpose:  Parses command arguments and configures SSL server.
 *
 */
int
main(int argc, char **argv)
{
  const char *    progName      = NULL;
  const char *    nickName      = NULL;
  char       *    passwordFile  = NULL;
  unsigned short  port          = 0;
  SECStatus       secStatus;
  PLOptState *    optstate;
  PLOptStatus     status;

  progName = PL_strdup(argv[0]);

  optstate = PL_CreateOptState(argc, argv, "d:p:n:w:s:");
  while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK)
    {
      switch(optstate->option)
	{
	case 'd': dbdir        = PL_strdup(optstate->value); break;
	case 'n': nickName     = PL_strdup(optstate->value); break;
	case 'p': port         = PORT_Atoi(optstate->value); break;
	case 'w': passwordFile = PL_strdup(optstate->value); break;
	case 's': stapOptions  = PL_strdup(optstate->value); break;
	default:
	case '?': Usage(progName);
	}
    }

  if (nickName == NULL || port == 0 || dbdir == NULL || passwordFile == NULL)
    Usage(progName);

  password = getPassword (passwordFile);

  /* Call the NSPR initialization routines. */
  PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);

  /* Set the cert database password callback. */
  PK11_SetPasswordFunc(myPasswd);

	/* Initialize NSS. */
  secStatus = NSS_Init(dbdir);
  if (secStatus != SECSuccess)
    exitErr("NSS_Init");

  /* Set the policy for this server (REQUIRED - no default). */
  secStatus = NSS_SetDomesticPolicy();
  if (secStatus != SECSuccess)
    exitErr("NSS_SetDomesticPolicy");

  /* Get own certificate and private key. */
  cert = PK11_FindCertFromNickname(nickName, password);
  if (cert == NULL)
    exitErr("PK11_FindCertFromNickname");

  privKey = PK11_FindKeyByAnyCert(cert, password);
  if (privKey == NULL)
    exitErr("PK11_FindKeyByAnyCert");

  /* Configure the server's cache for a multi-process application
   * using default timeout values (24 hrs) and directory location (/tmp). 
   */
  SSL_ConfigMPServerSIDCache(256, 0, 0, NULL);

  /* Launch server. */
  server_main(port, privKey, cert);

  /* Shutdown NSS and exit NSPR gracefully. */
  NSS_Shutdown();
  PR_Cleanup();

  return 0;
}

/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */