gnutls.c 15.4 KB
Newer Older
Ted Zlatanov's avatar
Ted Zlatanov committed
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
/* GnuTLS glue for GNU Emacs.
   Copyright (C) 2010  Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs 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 3 of the License, or
(at your option) any later version.

GNU Emacs 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 GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */

#include <config.h>
#include <errno.h>
#include <setjmp.h>

#include "lisp.h"
#include "process.h"

#ifdef HAVE_GNUTLS
#include <gnutls/gnutls.h>

Lisp_Object Qgnutls_code;
Lisp_Object Qgnutls_anon, Qgnutls_x509pki;
Lisp_Object Qgnutls_e_interrupted, Qgnutls_e_again,
  Qgnutls_e_invalid_session, Qgnutls_e_not_ready_for_handshake;
int global_initialized;

int
emacs_gnutls_write (int fildes, gnutls_session_t state, char *buf,
                    unsigned int nbyte)
{
  register int rtnval, bytes_written;

  bytes_written = 0;

  while (nbyte > 0)
    {
      rtnval = gnutls_write (state, buf, nbyte);

      if (rtnval == -1)
        {
          if (errno == EINTR)
            continue;
          else
            return (bytes_written ? bytes_written : -1);
        }

      buf += rtnval;
      nbyte -= rtnval;
      bytes_written += rtnval;
    }
  fsync (STDOUT_FILENO);

  return (bytes_written);
}

int
emacs_gnutls_read (int fildes, gnutls_session_t state, char *buf,
                   unsigned int nbyte)
{
  register int rtnval;

70 71 72 73 74
  rtnval = gnutls_read (state, buf, nbyte);
  if (rtnval >= 0)
    return rtnval;
  else
    return -1;
Ted Zlatanov's avatar
Ted Zlatanov committed
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
}

/* convert an integer error to a Lisp_Object; it will be either a
   known symbol like `gnutls_e_interrupted' and `gnutls_e_again' or
   simply the integer value of the error.  GNUTLS_E_SUCCESS is mapped
   to Qt.  */
Lisp_Object gnutls_make_error (int error)
{
  switch (error)
  {
  case GNUTLS_E_SUCCESS:
    return Qt;
  case GNUTLS_E_AGAIN:
    return Qgnutls_e_again;
  case GNUTLS_E_INTERRUPTED:
    return Qgnutls_e_interrupted;
  case GNUTLS_E_INVALID_SESSION:
    return Qgnutls_e_invalid_session;
  }

  return make_number (error);
}

DEFUN ("gnutls-get-initstage", Fgnutls_get_initstage, Sgnutls_get_initstage, 1, 1, 0,
       doc: /* Return the GnuTLS init stage of PROCESS.
See also `gnutls-boot'.  */)
    (Lisp_Object proc)
{
  CHECK_PROCESS (proc);

  return make_number (GNUTLS_INITSTAGE (proc));
}

DEFUN ("gnutls-errorp", Fgnutls_errorp, Sgnutls_errorp, 1, 1, 0,
       doc: /* Returns t if ERROR (as generated by gnutls_make_error)
indicates a GnuTLS problem.  */)
    (Lisp_Object error)
{
  if (EQ (error, Qt)) return Qnil;

  return Qt;
}

DEFUN ("gnutls-error-fatalp", Fgnutls_error_fatalp, Sgnutls_error_fatalp, 1, 1, 0,
       doc: /* Checks if ERROR is fatal.
ERROR is an integer or a symbol with an integer `gnutls-code' property.  */)
    (Lisp_Object err)
{
  Lisp_Object code;

  if (EQ (err, Qt)) return Qnil;

  if (SYMBOLP (err))
  {
    code = Fget (err, Qgnutls_code);
    if (NUMBERP (code))
    {
      err = code;
    }
    else
    {
      error ("Symbol has no numeric gnutls-code property");
    }
  }

  if (!NUMBERP (err))
    error ("Not an error symbol or code");

  if (0 == gnutls_error_is_fatal (XINT (err)))
    return Qnil;

  return Qt;
}

DEFUN ("gnutls-error-string", Fgnutls_error_string, Sgnutls_error_string, 1, 1, 0,
       doc: /* Returns a description of ERROR.
ERROR is an integer or a symbol with an integer `gnutls-code' property.  */)
    (Lisp_Object err)
{
  Lisp_Object code;

  if (EQ (err, Qt)) return build_string ("Not an error");

  if (SYMBOLP (err))
  {
    code = Fget (err, Qgnutls_code);
    if (NUMBERP (code))
    {
      err = code;
    }
    else
    {
      return build_string ("Symbol has no numeric gnutls-code property");
    }
  }

  if (!NUMBERP (err))
    return build_string ("Not an error symbol or code");

  return build_string (gnutls_strerror (XINT (err)));
}

DEFUN ("gnutls-deinit", Fgnutls_deinit, Sgnutls_deinit, 1, 1, 0,
       doc: /* Deallocate GNU TLS resources associated with PROCESS.
See also `gnutls-init'.  */)
    (Lisp_Object proc)
{
  gnutls_session_t state;

  CHECK_PROCESS (proc);
  state = XPROCESS (proc)->gnutls_state;

  if (GNUTLS_INITSTAGE (proc) >= GNUTLS_STAGE_INIT)
  {
      gnutls_deinit (state);
      GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_INIT - 1;
  }

  return Qt;
}

/* Initializes global GNU TLS state to defaults.
Call `gnutls-global-deinit' when GNU TLS usage is no longer needed.
Returns zero on success.  */
Lisp_Object gnutls_emacs_global_init (void)
{
  int ret = GNUTLS_E_SUCCESS;

  if (!global_initialized)
    ret = gnutls_global_init ();

  global_initialized = 1;

  return gnutls_make_error (ret);
}

/* Deinitializes global GNU TLS state.
See also `gnutls-global-init'.  */
Lisp_Object gnutls_emacs_global_deinit (void)
{
  if (global_initialized)
    gnutls_global_deinit ();

  global_initialized = 0;

  return gnutls_make_error (GNUTLS_E_SUCCESS);
}

223 224 225
static void gnutls_log_function (int level, const char* string)
{
  message("gnutls.c: [%d] %s", level, string);
226 227
}

228
DEFUN ("gnutls-boot", Fgnutls_boot, Sgnutls_boot, 3, 7, 0,
Ted Zlatanov's avatar
Ted Zlatanov committed
229 230 231 232 233 234 235 236 237
       doc: /* Initializes client-mode GnuTLS for process PROC.
Currently only client mode is supported.  Returns a success/failure
value you can check with `gnutls-errorp'.

PRIORITY_STRING is a string describing the priority.
TYPE is either `gnutls-anon' or `gnutls-x509pki'.
TRUSTFILE is a PEM encoded trust file for `gnutls-x509pki'.
KEYFILE is ... for `gnutls-x509pki' (TODO).
CALLBACK is ... for `gnutls-x509pki' (TODO).
238 239 240 241
LOGLEVEL is the debug level requested from GnuTLS, try 4.

LOGLEVEL will be set for this process AND globally for GnuTLS.  So if
you set it higher or lower at any point, it affects global debugging.
Ted Zlatanov's avatar
Ted Zlatanov committed
242 243 244 245 246 247 248 249 250 251 252 253 254

Note that the priority is set on the client.  The server does not use
the protocols's priority except for disabling protocols that were not
specified.

Processes must be initialized with this function before other GNU TLS
functions are used.  This function allocates resources which can only
be deallocated by calling `gnutls-deinit' or by calling it again.

Each authentication type may need additional information in order to
work.  For X.509 PKI (`gnutls-x509pki'), you need TRUSTFILE and
KEYFILE and optionally CALLBACK.  */)
    (Lisp_Object proc, Lisp_Object priority_string, Lisp_Object type,
255 256
     Lisp_Object trustfile, Lisp_Object keyfile, Lisp_Object callback,
     Lisp_Object loglevel)
Ted Zlatanov's avatar
Ted Zlatanov committed
257 258 259
{
  int ret = GNUTLS_E_SUCCESS;

260 261
  int max_log_level = 0;

Ted Zlatanov's avatar
Ted Zlatanov committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275
  /* TODO: GNUTLS_X509_FMT_DER is also an option.  */
  int file_format = GNUTLS_X509_FMT_PEM;

  gnutls_session_t state;
  gnutls_certificate_credentials_t x509_cred;
  gnutls_anon_client_credentials_t anon_cred;
  Lisp_Object global_init;

  CHECK_PROCESS (proc);
  CHECK_SYMBOL (type);
  CHECK_STRING (priority_string);

  state = XPROCESS (proc)->gnutls_state;

276 277 278 279 280 281 282 283
  if (NUMBERP (loglevel))
    {
      message ("setting up log level %d", XINT (loglevel));
      gnutls_global_set_log_function (gnutls_log_function);
      gnutls_global_set_log_level (XINT (loglevel));
      max_log_level = XINT (loglevel);
      XPROCESS (proc)->gnutls_log_level = max_log_level;
    }
284
  
Ted Zlatanov's avatar
Ted Zlatanov committed
285 286 287 288 289 290 291 292
  /* always initialize globals.  */
  global_init = gnutls_emacs_global_init ();
  if (! NILP (Fgnutls_errorp (global_init)))
    return global_init;

  /* deinit and free resources.  */
  if (GNUTLS_INITSTAGE (proc) >= GNUTLS_STAGE_CRED_ALLOC)
  {
293 294
      GNUTLS_LOG (1, max_log_level, "deallocating credentials");

Ted Zlatanov's avatar
Ted Zlatanov committed
295 296
      if (EQ (type, Qgnutls_x509pki))
      {
297 298
          GNUTLS_LOG (2, max_log_level, "deallocating x509 credentials");
          x509_cred = XPROCESS (proc)->gnutls_x509_cred;
Ted Zlatanov's avatar
Ted Zlatanov committed
299 300 301 302
          gnutls_certificate_free_credentials (x509_cred);
      }
      else if (EQ (type, Qgnutls_anon))
      {
303 304
          GNUTLS_LOG (2, max_log_level, "deallocating anon credentials");
          anon_cred = XPROCESS (proc)->gnutls_anon_cred;
Ted Zlatanov's avatar
Ted Zlatanov committed
305 306 307 308 309 310 311 312 313 314
          gnutls_anon_free_client_credentials (anon_cred);
      }
      else
      {
          error ("unknown credential type");
          ret = GNUTLS_EMACS_ERROR_INVALID_TYPE;
      }

      if (GNUTLS_INITSTAGE (proc) >= GNUTLS_STAGE_INIT)
      {
315
          GNUTLS_LOG (1, max_log_level, "deallocating x509 credentials");
Ted Zlatanov's avatar
Ted Zlatanov committed
316 317 318 319 320 321
          Fgnutls_deinit (proc);
      }
  }

  GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_EMPTY;

322 323
  GNUTLS_LOG (1, max_log_level, "allocating credentials");

Ted Zlatanov's avatar
Ted Zlatanov committed
324 325
  if (EQ (type, Qgnutls_x509pki))
  {
326 327
      GNUTLS_LOG (2, max_log_level, "allocating x509 credentials");
      x509_cred = XPROCESS (proc)->gnutls_x509_cred;
Ted Zlatanov's avatar
Ted Zlatanov committed
328 329 330 331 332
      if (gnutls_certificate_allocate_credentials (&x509_cred) < 0)
        memory_full ();
  }
  else if (EQ (type, Qgnutls_anon))
  {
333 334
      GNUTLS_LOG (2, max_log_level, "allocating anon credentials");
      anon_cred = XPROCESS (proc)->gnutls_anon_cred;
Ted Zlatanov's avatar
Ted Zlatanov committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
      if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
        memory_full ();
  }
  else
  {
      error ("unknown credential type");
      ret = GNUTLS_EMACS_ERROR_INVALID_TYPE;
  }

  if (ret < GNUTLS_E_SUCCESS)
      return gnutls_make_error (ret);

  GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_CRED_ALLOC;

  if (EQ (type, Qgnutls_x509pki))
  {
      if (STRINGP (trustfile))
      {
353
          GNUTLS_LOG (1, max_log_level, "setting the trustfile");
Ted Zlatanov's avatar
Ted Zlatanov committed
354 355
          ret = gnutls_certificate_set_x509_trust_file
            (x509_cred,
356
             SDATA (trustfile),
Ted Zlatanov's avatar
Ted Zlatanov committed
357 358 359 360 361 362 363 364
             file_format);

          if (ret < GNUTLS_E_SUCCESS)
            return gnutls_make_error (ret);
      }

      if (STRINGP (keyfile))
      {
365
          GNUTLS_LOG (1, max_log_level, "setting the keyfile");
Ted Zlatanov's avatar
Ted Zlatanov committed
366 367
          ret = gnutls_certificate_set_x509_crl_file
            (x509_cred,
368
             SDATA (keyfile),
Ted Zlatanov's avatar
Ted Zlatanov committed
369 370 371 372 373 374 375 376 377
             file_format);

          if (ret < GNUTLS_E_SUCCESS)
            return gnutls_make_error (ret);
      }
  }

  GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_FILES;

378 379
  GNUTLS_LOG (1, max_log_level, "gnutls_init");

Ted Zlatanov's avatar
Ted Zlatanov committed
380 381 382 383 384 385 386 387 388
  ret = gnutls_init (&state, GNUTLS_CLIENT);

  if (ret < GNUTLS_E_SUCCESS)
      return gnutls_make_error (ret);

  XPROCESS (proc)->gnutls_state = state;

  GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_INIT;

389 390
  GNUTLS_LOG (1, max_log_level, "setting the priority string");

Ted Zlatanov's avatar
Ted Zlatanov committed
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
  ret = gnutls_priority_set_direct(state,
                                   (char*) SDATA (priority_string),
                                   NULL);

  if (ret < GNUTLS_E_SUCCESS)
      return gnutls_make_error (ret);

  GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_PRIORITY;

  message ("gnutls: setting the credentials");

  if (EQ (type, Qgnutls_x509pki))
  {
      message ("gnutls: setting the x509 credentials");

      ret = gnutls_cred_set (state, GNUTLS_CRD_CERTIFICATE, x509_cred);
  }
  else if (EQ (type, Qgnutls_anon))
  {
      message ("gnutls: setting the anon credentials");

      ret = gnutls_cred_set (state, GNUTLS_CRD_ANON, anon_cred);
  }
  else
  {
      error ("unknown credential type");
      ret = GNUTLS_EMACS_ERROR_INVALID_TYPE;
  }

  if (ret < GNUTLS_E_SUCCESS)
      return gnutls_make_error (ret);

423 424
  XPROCESS (proc)->gnutls_anon_cred = anon_cred;
  XPROCESS (proc)->gnutls_x509_cred = x509_cred;
Ted Zlatanov's avatar
Ted Zlatanov committed
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
  XPROCESS (proc)->gnutls_cred_type = type;

  GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_CRED_SET;

  return gnutls_make_error (GNUTLS_E_SUCCESS);
}

DEFUN ("gnutls-bye", Fgnutls_bye,
       Sgnutls_bye, 2, 2, 0,
       doc: /* Terminate current GNU TLS connection for PROCESS.
The connection should have been initiated using `gnutls-handshake'.

If CONT is not nil the TLS connection gets terminated and further
receives and sends will be disallowed. If the return value is zero you
may continue using the connection.  If CONT is nil, GnuTLS actually
sends an alert containing a close request and waits for the peer to
reply with the same message.  In order to reuse the connection you
should wait for an EOF from the peer.

This function may also return `gnutls-e-again', or
`gnutls-e-interrupted'.  */)
    (Lisp_Object proc, Lisp_Object cont)
{
  gnutls_session_t state;
  int ret;

  CHECK_PROCESS (proc);

  state = XPROCESS (proc)->gnutls_state;

  ret = gnutls_bye (state,
                    NILP (cont) ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);

  return gnutls_make_error (ret);
}

DEFUN ("gnutls-handshake", Fgnutls_handshake,
       Sgnutls_handshake, 1, 1, 0,
       doc: /* Perform GNU TLS handshake for PROCESS.
The identity of the peer is checked automatically.  This function will
fail if any problem is encountered, and will return a negative error
code. In case of a client, if it has been asked to resume a session,
but the server didn't, then a full handshake will be performed.

If the error `gnutls-e-not-ready-for-handshake' is returned, you
didn't call `gnutls-boot' first.

This function may also return the non-fatal errors `gnutls-e-again',
or `gnutls-e-interrupted'. In that case you may resume the handshake
(by calling this function again).  */)
    (Lisp_Object proc)
{
  gnutls_session_t state;
  int ret;

  CHECK_PROCESS (proc);
  state = XPROCESS (proc)->gnutls_state;

  if (GNUTLS_INITSTAGE (proc) < GNUTLS_STAGE_HANDSHAKE_CANDO)
    return Qgnutls_e_not_ready_for_handshake;

  
  if (GNUTLS_INITSTAGE (proc) < GNUTLS_STAGE_TRANSPORT_POINTERS_SET)
  {
    /* for a network process in Emacs infd and outfd are the same
       but this shows our intent more clearly.  */
    message ("gnutls: handshake: setting the transport pointers to %d/%d",
             XPROCESS (proc)->infd, XPROCESS (proc)->outfd);

494 495
    /* FIXME: This can't be right: infd and outfd are integers (file handles)
       whereas the function expects args of type gnutls_transport_ptr_t.  */
Ted Zlatanov's avatar
Ted Zlatanov committed
496 497 498 499 500 501 502 503 504
    gnutls_transport_set_ptr2 (state, XPROCESS (proc)->infd,
                               XPROCESS (proc)->outfd);

    GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_TRANSPORT_POINTERS_SET;
  }

  ret = gnutls_handshake (state);
  GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_HANDSHAKE_TRIED;

505
  if (GNUTLS_E_SUCCESS == ret)
Ted Zlatanov's avatar
Ted Zlatanov committed
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
  {
    /* here we're finally done.  */
    GNUTLS_INITSTAGE (proc) = GNUTLS_STAGE_READY;
  }

  return gnutls_make_error (ret);
}

void
syms_of_gnutls (void)
{
  global_initialized = 0;

  Qgnutls_code = intern_c_string ("gnutls-code");
  staticpro (&Qgnutls_code);

  Qgnutls_anon = intern_c_string ("gnutls-anon");
  staticpro (&Qgnutls_anon);

  Qgnutls_x509pki = intern_c_string ("gnutls-x509pki");
  staticpro (&Qgnutls_x509pki);

  Qgnutls_e_interrupted = intern_c_string ("gnutls-e-interrupted");
  staticpro (&Qgnutls_e_interrupted);
  Fput (Qgnutls_e_interrupted, Qgnutls_code,
        make_number (GNUTLS_E_INTERRUPTED));

  Qgnutls_e_again = intern_c_string ("gnutls-e-again");
  staticpro (&Qgnutls_e_again);
  Fput (Qgnutls_e_again, Qgnutls_code,
        make_number (GNUTLS_E_AGAIN));

  Qgnutls_e_invalid_session = intern_c_string ("gnutls-e-invalid-session");
  staticpro (&Qgnutls_e_invalid_session);
  Fput (Qgnutls_e_invalid_session, Qgnutls_code,
        make_number (GNUTLS_E_INVALID_SESSION));

  Qgnutls_e_not_ready_for_handshake =
    intern_c_string ("gnutls-e-not-ready-for-handshake");
  staticpro (&Qgnutls_e_not_ready_for_handshake);
  Fput (Qgnutls_e_not_ready_for_handshake, Qgnutls_code,
        make_number (GNUTLS_E_APPLICATION_ERROR_MIN));

  defsubr (&Sgnutls_get_initstage);
  defsubr (&Sgnutls_errorp);
  defsubr (&Sgnutls_error_fatalp);
  defsubr (&Sgnutls_error_string);
  defsubr (&Sgnutls_boot);
  defsubr (&Sgnutls_deinit);
  defsubr (&Sgnutls_handshake);
  defsubr (&Sgnutls_bye);
}
#endif