http.c 11 KB
Newer Older
Youness Alaoui's avatar
Youness Alaoui 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 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
/*
 * This file is part of the Nice GLib ICE library.
 *
 * (C) 2008 Collabora Ltd.
 *  Contact: Youness Alaoui
 * (C) 2008 Nokia Corporation. All rights reserved.
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Nice GLib ICE library.
 *
 * The Initial Developers of the Original Code are Collabora Ltd and Nokia
 * Corporation. All Rights Reserved.
 *
 * Contributors:
 *   Youness Alaoui, Collabora Ltd.
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
 * case the provisions of LGPL are applicable instead of those above. If you
 * wish to allow use of your version of this file only under the terms of the
 * LGPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the LGPL.
 */

/*
 * Implementation of TCP relay socket interface using TCP Berkeley sockets. (See
 * http://en.wikipedia.org/wiki/Berkeley_sockets.)
 */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "http.h"

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


#ifndef G_OS_WIN32
#include <unistd.h>
#endif


#define HTTP_USER_AGENT "libnice"

typedef enum {
  HTTP_STATE_INIT,
  HTTP_STATE_HEADERS,
  HTTP_STATE_BODY,
  HTTP_STATE_CONNECTED,
  HTTP_STATE_ERROR
} HttpState;

typedef struct {
  HttpState state;
  NiceSocket *base_socket;
  NiceAddress addr;
  gchar *username;
  gchar *password;
  GQueue send_queue;
  gchar *recv_buf;
  gint recv_len;
  gint content_length;
} HttpPriv;


struct to_be_sent {
  guint length;
  gchar *buf;
  NiceAddress to;
};


static void socket_close (NiceSocket *sock);
static gint socket_recv (NiceSocket *sock, NiceAddress *from,
    guint len, gchar *buf);
static gboolean socket_send (NiceSocket *sock, const NiceAddress *to,
    guint len, const gchar *buf);
static gboolean socket_is_reliable (NiceSocket *sock);

static void add_to_be_sent (NiceSocket *sock, const NiceAddress *to,
    const gchar *buf, guint len);
static void free_to_be_sent (struct to_be_sent *tbs);


NiceSocket *
nice_http_socket_new (NiceSocket *base_socket,
    NiceAddress *addr, gchar *username, gchar *password)
{
  HttpPriv *priv;
  NiceSocket *sock = NULL;

  if (addr) {
    sock = g_slice_new0 (NiceSocket);
    sock->priv = priv = g_slice_new0 (HttpPriv);

    priv->base_socket = base_socket;
    priv->addr = *addr;
    priv->username = g_strdup (username);
    priv->password = g_strdup (password);
    priv->recv_buf = NULL;
    priv->recv_len = 0;
    priv->content_length = 0;


    sock->fileno = priv->base_socket->fileno;
    sock->addr = priv->base_socket->addr;
    sock->send = socket_send;
    sock->recv = socket_recv;
    sock->is_reliable = socket_is_reliable;
    sock->close = socket_close;

    /* Send HTTP CONNECT */
    {
      gchar *msg = NULL;
      gchar *credential = NULL;
      gchar host[INET6_ADDRSTRLEN];
      gint port = nice_address_get_port (&priv->addr);
      nice_address_to_string (&priv->addr, host);

      if (username) {
        gchar * userpass = g_strdup_printf ("%s:%s", username,
            password ? password : "");
        gchar * auth = g_base64_encode ((guchar *)userpass, strlen (userpass));
        credential = g_strdup_printf ("Proxy-Authorization: Basic %s\r\n", auth);
        g_free (auth);
        g_free (userpass);
      }
      msg = g_strdup_printf ("CONNECT %s:%d HTTP/1.0\r\n"
          "Host: %s\r\n"
          "User-Agent: %s\r\n"
          "Content-Length: 0\r\n"
          "Proxy-Connection: Keep-Alive\r\n"
          "Connection: Keep-Alive\r\n"
          "Cache-Control: no-cache\r\n"
          "Pragma: no-cache\r\n"
          "%s\r\n", host, port, host, HTTP_USER_AGENT,
          credential? credential : "" );
      g_free (credential);

      nice_socket_send (priv->base_socket, NULL, strlen (msg), msg);
      priv->state = HTTP_STATE_INIT;
      g_free (msg);
    }
  }

  return sock;
}


static void
socket_close (NiceSocket *sock)
{
  HttpPriv *priv = sock->priv;

  if (priv->base_socket)
    nice_socket_free (priv->base_socket);

  if (priv->username)
    g_free (priv->username);

  if (priv->password)
    g_free (priv->password);

  if (priv->recv_buf)
    g_free (priv->recv_buf);

  g_queue_foreach (&priv->send_queue, (GFunc) free_to_be_sent, NULL);
  g_queue_clear (&priv->send_queue);

  g_slice_free(HttpPriv, sock->priv);
}


static gint
socket_recv (NiceSocket *sock, NiceAddress *from, guint len, gchar *buf)
{
  HttpPriv *priv = sock->priv;
  gint read = -1;

193 194 195
  if (from)
    *from = priv->addr;

Youness Alaoui's avatar
Youness Alaoui committed
196
  if (priv->base_socket)
197
    read = nice_socket_recv (priv->base_socket, NULL, len, buf);
Youness Alaoui's avatar
Youness Alaoui committed
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

  if (read <= 0 || priv->state == HTTP_STATE_CONNECTED) {
    return read;
  } else {
    priv->recv_buf = g_realloc (priv->recv_buf, priv->recv_len + read);
    memcpy (priv->recv_buf + priv->recv_len, buf, read);
    priv->recv_len += read;
  }

 retry:
  nice_debug ("Receiving from HTTP proxy (state %d) : %d \n'%s'", priv->state, priv->recv_len, priv->recv_buf);
  switch (priv->state) {
    case HTTP_STATE_INIT:
      {
        gint pos = 0;

        /* Remove any leading spaces (could happen!) */
        while (pos < priv->recv_len && priv->recv_buf[pos] == ' ')
          pos++;

        /* Make sure we have enough data */
        if (pos >= priv->recv_len)
          goto not_enough_data;

        if (pos + 7 > priv->recv_len)
          goto not_enough_data;
        if (strncmp (priv->recv_buf + pos, "HTTP/1.", 7) != 0)
          goto error;
        pos += 7;

        if (pos >= priv->recv_len)
          goto not_enough_data;
        if(priv->recv_buf[pos] != '0' && priv->recv_buf[pos] != '1')
          goto error;
        pos++;

        /* Make sure we have a space after the HTTP version */
        if (pos >= priv->recv_len)
          goto not_enough_data;
        if (priv->recv_buf[pos] != ' ')
          goto error;

        /* Skip all spaces (could be more than one!) */
        while (pos < priv->recv_len && priv->recv_buf[pos] == ' ')
          pos++;
        if (pos >= priv->recv_len)
          goto not_enough_data;

        /* Check for a successfull 2xx code */
        if (pos + 3 > priv->recv_len)
          goto not_enough_data;
        if (priv->recv_buf[pos] != '2' ||
            priv->recv_buf[pos+1] < '0' || priv->recv_buf[pos+1] > '9' ||
            priv->recv_buf[pos+2] < '0' || priv->recv_buf[pos+2] > '9')
          goto error;

        /* Clear any trailing chars */
        while (pos + 1 < priv->recv_len &&
            priv->recv_buf[pos] != '\r' && priv->recv_buf[pos+1] != '\n')
          pos++;
        if (pos + 1 >= priv->recv_len)
          goto not_enough_data;
        pos += 2;

        /* consume the data we just parsed */
        priv->recv_len -= pos;
        memmove (priv->recv_buf, priv->recv_buf + pos, priv->recv_len);
        priv->recv_buf = g_realloc (priv->recv_buf, priv->recv_len);

        priv->content_length = 0;
        priv->state = HTTP_STATE_HEADERS;
        goto retry;
      }
      break;
    case HTTP_STATE_HEADERS:
      {
        gint pos = 0;

        if (pos + 15 < priv->recv_len &&
            g_ascii_strncasecmp (priv->recv_buf, "Content-Length:", 15) == 0) {
          priv->content_length = atoi(priv->recv_buf + 15);
        }
        while (pos + 1 < priv->recv_len &&
            priv->recv_buf[pos] != '\r' && priv->recv_buf[pos+1] != '\n')
          pos++;
        nice_debug ("pos = %d, len = %d", pos, priv->recv_len);
        if (pos + 1 >= priv->recv_len)
          goto not_enough_data;
        pos += 2;

        /* consume the data we just parsed */
        priv->recv_len -= pos;
        memmove (priv->recv_buf, priv->recv_buf + pos, priv->recv_len);
        priv->recv_buf = g_realloc (priv->recv_buf, priv->recv_len);

        if (pos == 2)
          priv->state = HTTP_STATE_BODY;
        goto retry;
      }
      break;
    case HTTP_STATE_BODY:
      {
        gint consumed = priv->content_length;
        if (priv->content_length == 0) {
          priv->state = HTTP_STATE_CONNECTED;
          goto retry;
        }
        if (priv->recv_len == 0)
          goto not_enough_data;

        if (priv->content_length > priv->recv_len)
          consumed = priv->recv_len;

        priv->recv_len -= consumed;
        priv->content_length -= consumed;
        memmove (priv->recv_buf, priv->recv_buf + consumed, priv->recv_len);
        priv->recv_buf = g_realloc (priv->recv_buf, priv->recv_len);
        goto retry;
      }
      break;
    case HTTP_STATE_CONNECTED:
      {
Philip Withnall's avatar
Philip Withnall committed
320
        guint recv_len = priv->recv_len;
Youness Alaoui's avatar
Youness Alaoui committed
321 322
        struct to_be_sent *tbs = NULL;

Philip Withnall's avatar
Philip Withnall committed
323 324
        if (recv_len > len)
          recv_len = len;
Youness Alaoui's avatar
Youness Alaoui committed
325

Philip Withnall's avatar
Philip Withnall committed
326
        memcpy (buf, priv->recv_buf, recv_len);
Youness Alaoui's avatar
Youness Alaoui committed
327 328

        /* consume the data we returned */
Philip Withnall's avatar
Philip Withnall committed
329 330
        priv->recv_len -= recv_len;
        memmove (priv->recv_buf, priv->recv_buf + recv_len, priv->recv_len);
Youness Alaoui's avatar
Youness Alaoui committed
331 332 333 334 335 336 337 338 339 340
        priv->recv_buf = g_realloc (priv->recv_buf, priv->recv_len);

        /* Send the pending data */
        while ((tbs = g_queue_pop_head (&priv->send_queue))) {
          nice_socket_send (priv->base_socket, &tbs->to,
              tbs->length, tbs->buf);
          g_free (tbs->buf);
          g_slice_free (struct to_be_sent, tbs);
        }

Philip Withnall's avatar
Philip Withnall committed
341
        return recv_len;
Youness Alaoui's avatar
Youness Alaoui committed
342 343
      }
      break;
344
    case HTTP_STATE_ERROR:
Youness Alaoui's avatar
Youness Alaoui committed
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
    default:
      /* Unknown status */
      goto error;
  }

 not_enough_data:
  return 0;

 error:
  nice_debug ("http error");
  if (priv->base_socket)
    nice_socket_free (priv->base_socket);
  priv->base_socket = NULL;
  priv->state = HTTP_STATE_ERROR;

  return -1;
}

static gboolean
socket_send (NiceSocket *sock, const NiceAddress *to,
    guint len, const gchar *buf)
{
  HttpPriv *priv = sock->priv;

  if (priv->state == HTTP_STATE_CONNECTED) {
    if (priv->base_socket)
      return nice_socket_send (priv->base_socket, to, len, buf);
    else
      return FALSE;
  } else if (priv->state == HTTP_STATE_ERROR) {
    return FALSE;
  } else {
    add_to_be_sent (sock, to, buf, len);
  }
  return TRUE;
}


static gboolean
socket_is_reliable (NiceSocket *sock)
{
  return TRUE;
}


static void
add_to_be_sent (NiceSocket *sock, const NiceAddress *to,
    const gchar *buf, guint len)
{
  HttpPriv *priv = sock->priv;
  struct to_be_sent *tbs = NULL;

  if (len <= 0)
    return;

  tbs = g_slice_new0 (struct to_be_sent);
  tbs->buf = g_memdup (buf, len);
  tbs->length = len;
  if (to)
    tbs->to = *to;
  g_queue_push_tail (&priv->send_queue, tbs);

}


static void
free_to_be_sent (struct to_be_sent *tbs)
{
  g_free (tbs->buf);
  g_slice_free (struct to_be_sent, tbs);
}