summaryrefslogtreecommitdiff
path: root/sockets.c
blob: 0921e553f5f299007ac3e9f0ee6587270d8d0766 (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
/*
 * This file is part of blabouncer (https://www.blatech.co.uk/l_bratch/blabouncer).
 * Copyright (C) 2019 Luke Bratch <luke@bratch.co.uk>.
 *
 * Blabouncer 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, version 3.
 *
 * Blabouncer 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 blabouncer. If not, see <http://www.gnu.org/licenses/>.
*/

#include "sockets.h"

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa) {
  if (sa->sa_family == AF_INET) {
    return &(((struct sockaddr_in*)sa)->sin_addr);
  }

  return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

// Create socket to connect to real IRC server
// Returns the socket descriptor on success, or -1 on error
int createserversocket(char *host, char *port) {
  int sockfd;
  struct addrinfo hints, *servinfo, *p;
  int rv; // Return value for getaddrinfo (for error message)
  char s[INET6_ADDRSTRLEN];

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;

  if ((rv = getaddrinfo(host, port, &hints, &servinfo)) != 0) {
    debugprint(DEBUG_CRIT, "createserversocket(): getaddrinfo(): %s\n", gai_strerror(rv));
    freeaddrinfo(servinfo);
    return -1;
  }

  // Loop through all the results and connect to the first we can
  for (p = servinfo; p != NULL; p = p->ai_next) {
    if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
      debugprint(DEBUG_CRIT, "createserversocket(): socket(): %s\n", strerror(errno));
      continue;
    }

    if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
      close(sockfd);
      debugprint(DEBUG_CRIT, "createserversocket(): connect(): %s\n", strerror(errno));
      continue;
    }

    break;
  }

  if (p == NULL) {
    debugprint(DEBUG_CRIT, "createserversocket(): p == NULL, (%s)\n", strerror(errno));
    freeaddrinfo(servinfo);
    return -1;
  }

  inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
  debugprint(DEBUG_SOME, "bouncer-server: connecting to '%s'\n", s);

  freeaddrinfo(servinfo); // All done with this structure

  return sockfd;
}

// Create listening socket to listen for bouncer client connections
int createclientsocket(char *listenport) {
  int listener;     // listening socket descriptor
  int rv; // return value for getaddrinfo (for error message)
  struct addrinfo hints, *ai, *p;
  int yes = 1; // for enabling socket options with setsockopt

  // get us a socket and bind it
  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;

  if ((rv = getaddrinfo(NULL, listenport, &hints, &ai)) != 0) {
    fprintf(stderr, "bouncer-client: %s\n", gai_strerror(rv));
    debugprint(DEBUG_CRIT, "bouncer-client: %s\n", gai_strerror(rv));
    exit(1);
  }

  // Try for IPv6
  for (p = ai; p != NULL; p = p->ai_next) {
    if (p->ai_family == AF_INET6) {
      listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
      if (listener != -1) {
        // success, got IPv6!
        debugprint(DEBUG_FULL, "success, got IPv6!  ai_family: '%d'\n", p->ai_family);
        break;
      }
    }
  }

  // Try for IPv4 if IPv6 failed
  if (listener < 0) {
    for (p = ai; p != NULL; p = p->ai_next) {
      if (p->ai_family == AF_INET) {
        listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (listener != -1) {
          // moderate success, got IPv4!
          debugprint(DEBUG_FULL, "moderate success, got IPv4!  ai_family: '%d'\n", p->ai_family);
          break;
        }
      }
    }
  }

  // allow address re-use
  setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); // 1 as in non-zero as in enable

  if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) {
    // failed to bind
    close(listener);
    printf("bouncer-client: failed to bind, exiting...\n");
    debugprint(DEBUG_CRIT, "bouncer-client: failed to bind, exiting...\n");
    exit(1);
  }

  // if we got here, it means we didn't get bound
  if (p == NULL) {
    fprintf(stderr, "bouncer-client: failed to bind\n");
    debugprint(DEBUG_CRIT, "bouncer-client: failed to bind\n");
    exit(1);
  }

  freeaddrinfo(ai); // all done with this

    // listen
    if (listen(listener, BACKLOG) == -1) {
        perror("listen");
        debugprint(DEBUG_CRIT, "bouncer-client failed to listen(), errno '%d'.\n", errno);
        exit(1);
    }

  return listener;
}

void init_openssl() {
  SSL_load_error_strings();
  OpenSSL_add_ssl_algorithms();
}


void cleanup_openssl() {
  EVP_cleanup();
}

// Create OpenSSL context, type = 0 for IRC server-side (OpenSSL client)
// or type = 1 for bouncer client-side (OpenSSL server)
SSL_CTX *create_openssl_context(int type) {
  const SSL_METHOD *method;
  SSL_CTX *ctx;

  if (type == 0) {
    method = SSLv23_client_method();
  } else {
    method = SSLv23_server_method();
  }

  ctx = SSL_CTX_new(method);
  if (!ctx) {
    char* errstr = openssl_error_string();
    debugprint(DEBUG_CRIT, "Unable to create SSL context, errno '%d', type '%d' - %s", errno, type, errstr);
    if (errstr != NULL) free(errstr);
    exit(EXIT_FAILURE);
  }

  return ctx;
}

// Configure OpenSSL context, with certfile and keyfile provided if
// IRC server-side or set to NULL if bouncer client-side
void configure_openssl_context(SSL_CTX *ctx, char *certfile, char *keyfile) {
  SSL_CTX_set_ecdh_auto(ctx, 1);

  /* Set the key and cert if set or return if not */

  if (certfile == NULL || keyfile == NULL) {
    return;
  }

  if (SSL_CTX_use_certificate_file(ctx, certfile, SSL_FILETYPE_PEM) <= 0) {
    ERR_print_errors_fp(stderr);
    printf("Couldn't load certificate file '%s'.  Hint: You can generate your own with OpenSSL.  Once created, set its location in blabouncer.conf which by default is in ~/.blabouncer/.\n", certfile);
    debugprint(DEBUG_CRIT, "Couldn't load certificate file '%s'.  Hint: You can generate your own with OpenSSL.  Once created, set its location in blabouncer.conf which by default is in ~/.blabouncer/.\n", certfile);
    exit(EXIT_FAILURE);
  }

  if (SSL_CTX_use_PrivateKey_file(ctx, keyfile, SSL_FILETYPE_PEM) <= 0 ) {
    ERR_print_errors_fp(stderr);
    printf("Couldn't load key file '%s'.  Hint: You can generate your own with OpenSSL.  Once created, set its location in blabouncer.conf which by default is in ~/.blabouncer/.\n", keyfile);
    debugprint(DEBUG_CRIT, "Couldn't load key file '%s'.  Hint: You can generate your own with OpenSSL.  Once created, set its location in blabouncer.conf which by default is in ~/.blabouncer/.\n", keyfile);
    exit(EXIT_FAILURE);
  }
}

// Read from a socket, whether or not using TLS
int sockread(SSL *fd, char *buf, int bufsize, int tls) {
  if (fd == NULL) {
    debugprint(DEBUG_CRIT, "sockread(): error: fd is NULL, returning.\n");
    return -1;
  }

  if (tls) {
    return SSL_read(fd, buf, bufsize);
  } else {
    // Cast the supposed SSL *fd to a long int if we're not using TLS
    return recv((long int)fd, buf, bufsize, 0);
  }
}

// Write to a socket, whether or not using TLS
int socksend(SSL *fd, char *buf, int bufsize, int tls) {
  if (fd == NULL) {
    debugprint(DEBUG_CRIT, "socksend(): error: fd is NULL, returning.\n");
    return -1;
  }

  if (tls) {
    return SSL_write(fd, buf, bufsize);
  } else {
    // Clear errno in case send() errors
    errno = 0;
    // Cast the supposed SSL *fd to a long int if we're not using TLS
    return send((long int)fd, buf, bufsize, 0);
  }
}

// Return character array of latest OpenSSL error
char *openssl_error_string() {
  BIO *bio = BIO_new (BIO_s_mem ());
  ERR_print_errors (bio);
  char *buf = NULL;
  size_t len = BIO_get_mem_data (bio, &buf);
  char *ret = (char *)calloc(1, 1 + len);
  if (ret) {
    memcpy(ret, buf, len);
  }
  BIO_free (bio);
  return ret;
}

// Set a socket "fd" to be blocking ("blocking" = 1) or non-blocking ("blocking" = 0).
// Returns 1 on success or 0 on failure.
int fd_toggle_blocking(int fd, int blocking) {
  debugprint(DEBUG_FULL, "fd_toggle_blocking(): setting blocking to %d for fd %d.\n", blocking, fd);

  // Save the current flags
  int flags = fcntl(fd, F_GETFL, 0);
  if (flags == -1) {
    // Error getting current flags
    return 0;
  }

  // Add or remove O_NONBLOCK as appropriate
  if (blocking) {
    flags &= ~O_NONBLOCK;
  } else {
    flags |= O_NONBLOCK;
  }

  if (fcntl(fd, F_SETFL, flags) == -1) {
    return 0;
  } else {
    return 1;
  }
}

// Attempt to do SSL_accept() on a client with fd "fd".  Expects the socket fd to have just been set
// to non-blocking.  Will make the socket blocking again and set the client's pendingsslaccept status
// to 0 if SSL_accept() succeeds.  Calls disconnectclient() on hard failure.
// Returns 1 on success, 0 on hard failure, or -1 on SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE.
int openssl_accept(int fd, struct client *clients, struct ircdstate *ircdstate, struct settings *settings, struct clientcodes *clientcodes) {
  // Get the index of the this client fd
  int clientindex = arrindex(clients, fd);
  if (clientindex < 0) {
    debugprint(DEBUG_CRIT, "openssl_accept(): error: arrindex() returned '%d', exiting!\n", clientindex);
    exit(1);
  }

  // Clear OpenSSL errors before proceeding so we can reliably get errors from SSL_accept
  ERR_clear_error();
  // Try to SSL_accept();
  int ret;
  if ((ret = SSL_accept(clients[clientindex].ssl)) <= 0) {
    // SSL_accept() either failed (bad) or is just pending read or write (which is OK)
    int sslerr = SSL_get_error(clients[clientindex].ssl, ret);
    if (sslerr == SSL_ERROR_WANT_READ || sslerr == SSL_ERROR_WANT_WRITE) {
      debugprint(DEBUG_FULL, "SSL_accept() pending for new connection fd %d (ret = %d, sslerr = %d), looping...\n", clients[clientindex].fd, ret, sslerr);
      return -1;
    } else {
      char* errstr = openssl_error_string();
      debugprint(DEBUG_CRIT, "SSL_accept failed for new connection fd %d (ret = %d) - %s", clients[clientindex].fd, ret, errstr);
      if (errstr != NULL) free(errstr);
      disconnectclient(clients[clientindex].fd, clients, ircdstate, settings, clientcodes);
      return 0;
    }
  } else {
    debugprint(DEBUG_FULL, "SSL_accept succeeded for new connection fd %d.\n", clients[clientindex].fd);
    // Change the socket back to blocking
    if (!fd_toggle_blocking(clients[clientindex].fd, 1)) {
      debugprint(DEBUG_CRIT, "fd_toggle_blocking off failed for fd %d: %s.\n", clients[clientindex].fd, strerror(errno));
      disconnectclient(clients[clientindex].fd, clients, ircdstate, settings, clientcodes);
      return 0;
    }
    // And mark as no longer pending SSL_accept()
    clients[clientindex].pendingsslaccept = 0;
    return 1;
  }
}