summaryrefslogtreecommitdiff
path: root/src/munia_proto.cc
blob: b801009790088a36721c47b6208b076a28328af7 (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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set et sw=2 ts=2: */
/***************************************************************************
 *            munia_proto.cc
 *
 *  Fri Feb 24 08:23:16 CET 2012
 *  Copyright 2012 Bent Bisballe Nyeng
 *  deva@aasimon.org
 ****************************************************************************/

/*
 *  This file is part of Munia.
 *
 *  Munia 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.
 *
 *  Munia 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 Munia; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */
#include "munia_proto.h"

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

#include <queue>
#include <map>

#include "task.h"
#include "messageparser.h"
#include "messagehandler.h"
#include "connectionhandler.h"

#include "taskmanager.h"

extern TaskManager taskman;

#if 0
static void dump_handshake_info(struct lws_tokens *lwst)
{
  int n;
  static const char *token_names[WSI_TOKEN_COUNT] = {
    /*[WSI_TOKEN_GET_URI]     =*/ "GET URI",
    /*[WSI_TOKEN_HOST]        =*/ "Host",
    /*[WSI_TOKEN_CONNECTION]  =*/ "Connection",
    /*[WSI_TOKEN_KEY1]        =*/ "key 1",
    /*[WSI_TOKEN_KEY2]        =*/ "key 2",
    /*[WSI_TOKEN_PROTOCOL]    =*/ "Protocol",
    /*[WSI_TOKEN_UPGRADE]     =*/ "Upgrade",
    /*[WSI_TOKEN_ORIGIN]      =*/ "Origin",
    /*[WSI_TOKEN_DRAFT]       =*/ "Draft",
    /*[WSI_TOKEN_CHALLENGE]   =*/ "Challenge",

    /* new for 04 */
    /*[WSI_TOKEN_KEY]         =*/ "Key",
    /*[WSI_TOKEN_VERSION]     =*/ "Version",
    /*[WSI_TOKEN_SWORIGIN]    =*/ "Sworigin",

    /* new for 05 */
    /*[WSI_TOKEN_EXTENSIONS]  =*/ "Extensions",

    /* client receives these */
    /*[WSI_TOKEN_ACCEPT]      =*/ "Accept",
    /*[WSI_TOKEN_NONCE]       =*/ "Nonce",
    /*[WSI_TOKEN_HTTP]        =*/ "Http",
    /*[WSI_TOKEN_MUXURL]      =*/ "MuxURL",
  };

  for (n = 0; n < WSI_TOKEN_COUNT; n++) {
    if (lwst[n].token == NULL || lwst[n].token_len == 0) continue;
    fprintf(stderr, "    %s = ", token_names[n]);
    if(fwrite(lwst[n].token, 1, lwst[n].token_len, stderr)) {}
    fprintf(stderr, "\n");
  }
}
#endif

static std::map<struct libwebsocket *, std::queue<std::string> > msgqueue;

int callback_lws_task(struct libwebsocket_context * context,
                      struct libwebsocket *wsi,
                      enum libwebsocket_callback_reasons reason,
                      void *user, void *in, size_t len)
{
  taskman.tree.toStdOut();

  printf("Callback on %p\n", wsi);

  switch (reason) {
  case LWS_CALLBACK_ESTABLISHED:
    connection_handler.init(wsi);
    break;

  case LWS_CALLBACK_CLOSED:
    connection_handler.close(wsi);
    break;

  case LWS_CALLBACK_SERVER_WRITEABLE:
    {
      printf("Socket for client %p writable\n", wsi);
      if(msgqueue[wsi].size() > 0) {
        std::string msg = msgqueue[wsi].front();
        msgqueue[wsi].pop();
        int n = libwebsocket_write(wsi, (unsigned char *)
                                   msg.c_str() +
                                   LWS_SEND_BUFFER_PRE_PADDING,
                                   msg.length() - LWS_SEND_BUFFER_POST_PADDING -
                                   LWS_SEND_BUFFER_PRE_PADDING,
                                   LWS_WRITE_TEXT);
        if(n < 0) {
          fprintf(stderr, "ERROR writing to socket");
          exit(1);
        }
      }
      else {
        printf("\tNo queued data awaiting transmission\n");
      }

      if(msgqueue[wsi].size()) {
        libwebsocket_rx_flow_control(wsi, 1);
        libwebsocket_callback_on_writable(context, wsi);
      }
    }
    break;

    /*
  case LWS_CALLBACK_BROADCAST:
    printf("LWS_CALLBACK_BROADCAST\n");
    n = libwebsocket_write(wsi, (unsigned char*)in, len, LWS_WRITE_TEXT);
    if (n < 0) fprintf(stderr, "task write failed\n");
    break;
    */

  case LWS_CALLBACK_RECEIVE:
    {
      printf("LWS_CALLBACK_RECEIVE\n");

      printf("%s\n", (char*)in);
      std::string data;
      data.append((char*)in, len);

      MessageList mlst = parse_msg(data);
      printf("Handling %d incoming message\n", mlst.size());
      MessageList omsgs = handle_msg(mlst, wsi);
      printf("Handling %d outgoing messages\n", omsgs.size());

      MessageList::iterator omi = omsgs.begin();
      while(omi != omsgs.end()) {
        std::string msgcmd = msg_tostring(*omi);

        printf("%d nodes affected by command\n", omi->nodes.size());

        std::list<std::pair<clientid_t, taskid_t> > clients =
          connection_handler.observerlist(omi->nodes);
        printf("Writing message to %d clients\n", clients.size());

        std::list<std::pair<clientid_t, taskid_t> >::iterator ci = clients.begin();
        while(ci != clients.end()) {
          std::string msg;
          clientid_t clientid = (*ci).first;
          char tidstr[32];
          sprintf(tidstr, "%u", (*ci).second);
          printf("\tAdding data to %p's queue\n", clientid);

          msg.append((size_t)LWS_SEND_BUFFER_PRE_PADDING, ' ');
          msg.append(tidstr);
          msg.append(" ");
          msg.append(msgcmd);
          msg.append((size_t)LWS_SEND_BUFFER_POST_PADDING, ' ');
          
          msgqueue[clientid].push(msg);
          ci++;
        }
        
        omi++;
      }

      libwebsocket_callback_on_writable_all_protocol(
                                libwebsockets_get_protocol(wsi));
    }
    break;

  default:
    break;
  }

  return 0;
}