Skip to content
This repository
tree: 2424c8538c
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 593 lines (476 sloc) 14.597 kb
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
package main

import (
"encoding/json"
"fmt"
"go.net/websocket"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"runtime"
"strings"
"text/template"
"time"
"uuid"
)

type ServerConfig struct {
Hostname string `json:"hostname"`
Port string `json:"port"`
NotifyPrefix string `json:"notifyPrefix"`
UseTLS bool `json:"useTLS"`
CertFilename string `json:"certFilename"`
KeyFilename string `json:"keyFilename"`
}

var gServerConfig ServerConfig

type Client struct {
Websocket *websocket.Conn `json:"-"`
UAID string `json:"uaid"`
Ip string `json:"ip"`
Port float64 `json:"port"`
LastContact time.Time `json:"-"`
}

type Channel struct {
UAID string `json:"uaid"`
ChannelID string `json:"channelID"`
Version uint64 `json:"version"`
}

type ChannelIDSet map[string]*Channel

type ServerState struct {
// Mapping from a UAID to the Client object
// json field is "-" to prevent serialization
// since the connectedness of a client means nothing
// across sessions
ConnectedClients map[string]*Client `json:"-"`

// Mapping from a UAID to all channelIDs owned by that UAID
// where channelIDs are represented as a map-backed set
UAIDToChannelIDs map[string]ChannelIDSet `json:"uaidToChannels"`

// Mapping from a ChannelID to the cooresponding Channel
ChannelIDToChannel ChannelIDSet `json:"channelIDToChannel"`
}

var gServerState ServerState

type Notification struct {
UAID string
Channel *Channel
}

type Ack struct {
ChannelID string
Version uint64
}

var notifyChan chan Notification
var ackChan chan Ack

func readConfig() {

var data []byte
var err error

data, err = ioutil.ReadFile("config.json")
if err != nil {
log.Println("Not configured. Could not find config.json")
os.Exit(-1)
}

err = json.Unmarshal(data, &gServerConfig)
if err != nil {
log.Println("Could not unmarshal config.json", err)
os.Exit(-1)
return
}
}

func openState() {
var data []byte
var err error

data, err = ioutil.ReadFile("serverstate.json")
if err == nil {
err = json.Unmarshal(data, &gServerState)
if err == nil {
gServerState.ConnectedClients = make(map[string]*Client)
return
}
}

log.Println(" -> creating new server state")
gServerState.UAIDToChannelIDs = make(map[string]ChannelIDSet)
gServerState.ChannelIDToChannel = make(ChannelIDSet)
gServerState.ConnectedClients = make(map[string]*Client)
}

func saveState() {
log.Println(" -> saving state..")

var data []byte
var err error

data, err = json.Marshal(gServerState)
if err != nil {
return
}
ioutil.WriteFile("serverstate.json", data, 0644)
}

func makeNotifyURL(suffix string) string {
var scheme string
if gServerConfig.UseTLS {
scheme = "https://"
} else {
scheme = "http://"
}

return scheme + gServerConfig.Hostname + ":" + gServerConfig.Port + gServerConfig.NotifyPrefix + suffix
}

func handleRegister(client *Client, f map[string]interface{}) {
type RegisterResponse struct {
Name string `json:"messageType"`
Status int `json:"status"`
PushEndpoint string `json:"pushEndpoint"`
ChannelID string `json:"channelID"`
}

if f["channelID"] == nil {
log.Println("channelID is missing!")
return
}

var channelID = f["channelID"].(string)

register := RegisterResponse{"register", 0, "", channelID}

prevEntry, exists := gServerState.ChannelIDToChannel[channelID]
if exists && prevEntry.UAID != client.UAID {
register.Status = 409
} else {

channel := &Channel{client.UAID, channelID, 0}

if gServerState.UAIDToChannelIDs[client.UAID] == nil {
gServerState.UAIDToChannelIDs[client.UAID] = make(ChannelIDSet)
}
gServerState.UAIDToChannelIDs[client.UAID][channelID] = channel
gServerState.ChannelIDToChannel[channelID] = channel

register.Status = 200
register.PushEndpoint = makeNotifyURL(channelID)
}

if register.Status == 0 {
panic("Register(): status field was left unset when replying to client")
}

j, err := json.Marshal(register)
if err != nil {
log.Println("Could not convert register response to json %s", err)
return
}

if err = websocket.Message.Send(client.Websocket, string(j)); err != nil {
// we could not send the message to a peer
log.Println("Could not send message to ", client.Websocket, err.Error())
}
}

func handleUnregister(client *Client, f map[string]interface{}) {

if f["channelID"] == nil {
log.Println("channelID is missing!")
return
}

var channelID = f["channelID"].(string)
_, ok := gServerState.ChannelIDToChannel[channelID]
if ok {
// only delete if UA owns this channel
_, owns := gServerState.UAIDToChannelIDs[client.UAID][channelID]
if owns {
// remove ownership
delete(gServerState.UAIDToChannelIDs[client.UAID], channelID)
// delete the channel itself
delete(gServerState.ChannelIDToChannel, channelID)
}
}

type UnregisterResponse struct {
Name string `json:"messageType"`
Status int `json:"status"`
ChannelID string `json:"channelID"`
}

unregister := UnregisterResponse{"unregister", 200, channelID}

j, err := json.Marshal(unregister)
if err != nil {
log.Println("Could not convert unregister response to json %s", err)
return
}

if err = websocket.Message.Send(client.Websocket, string(j)); err != nil {
// we could not send the message to a peer
log.Println("Could not send message to ", client.Websocket, err.Error())
}
}

func handleHello(client *Client, f map[string]interface{}) {

status := 200

if f["uaid"] == nil {
uaid, err := uuid.GenUUID()
if err != nil {
status = 400
log.Println("GenUUID error %s", err)
}
client.UAID = uaid
} else {
client.UAID = f["uaid"].(string)

resetClient := false

if f["channelIDs"] != nil {
for _, foo := range f["channelIDs"].([]interface{}) {
channelID := foo.(string)

if gServerState.UAIDToChannelIDs[client.UAID] == nil {
gServerState.UAIDToChannelIDs[client.UAID] = make(ChannelIDSet)
// since we don't have any channelIDs, don't bother looping any more
resetClient = true
break
}

if _, ok := gServerState.UAIDToChannelIDs[client.UAID][channelID]; !ok {
resetClient = true
break
}
}
}

if resetClient {
// delete the older connection
delete(gServerState.ConnectedClients, client.UAID)
delete(gServerState.UAIDToChannelIDs, client.UAID)
// TODO(nsm) clear up ChannelIDToChannels which now has extra
// channelIDs not associated with any client

uaid, err := uuid.GenUUID()
if err != nil {
status = 400
log.Println("GenUUID error %s", err)
}
client.UAID = uaid
}
}

gServerState.ConnectedClients[client.UAID] = client

if f["wakeup_hostport"] != nil {
m := f["wakeup_hostport"].(map[string]interface{})
client.Ip = m["ip"].(string)
client.Port = m["port"].(float64)
log.Println("Got hostport pair ", client.Ip, client.Port)
} else {
log.Println("No hostport ", f)
}

type HelloResponse struct {
Name string `json:"messageType"`
Status int `json:"status"`
UAID string `json:"uaid"`
}

hello := HelloResponse{"hello", status, client.UAID}

j, err := json.Marshal(hello)
if err != nil {
log.Println("Could not convert hello response to json %s", err)
return
}

if err = websocket.Message.Send(client.Websocket, string(j)); err != nil {
log.Println("Could not send message to ", client.Websocket, err.Error())
}
}

func handleAck(client *Client, f map[string]interface{}) {
for _, update := range f["updates"].([]interface{}) {
typeConverted := update.(map[string]interface{})
version := uint64(typeConverted["version"].(float64))
ack := Ack{typeConverted["channelID"].(string), version}
log.Println(ack)
ackChan <- ack
}
}

func pushHandler(ws *websocket.Conn) {

client := &Client{ws, "", "", 0, time.Now()}

for {
var f map[string]interface{}

var err error
if err = websocket.JSON.Receive(ws, &f); err != nil {
log.Println("Websocket Disconnected.", err.Error())
break
}

client.LastContact = time.Now()
log.Println("pushHandler msg: ", f["messageType"])

switch f["messageType"] {
case "hello":
handleHello(client, f)
break

case "register":
handleRegister(client, f)
break

case "unregister":
handleUnregister(client, f)
break

case "ack":
handleAck(client, f)
break

default:
log.Println(" -> Unknown", f)
break
}

saveState()
}

log.Println("Closing Websocket!")
ws.Close()

// if a client disconnected before completing the handshake
// it'll have an empty UAID
if client.UAID != "" {
gServerState.ConnectedClients[client.UAID].Websocket = nil
}
}

func notifyHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Got notification from app server ", r.URL)

if r.Method != "PUT" {
log.Println("NOT A PUT")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Method must be PUT."))
return
}

channelID := strings.Replace(r.URL.Path, gServerConfig.NotifyPrefix, "", 1)

if strings.Contains(channelID, "/") {
log.Println("Could not find a valid channelID")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Could not find a valid channelID."))
return
}

channel, found := gServerState.ChannelIDToChannel[channelID]
if !found {
log.Println("Could not find channel " + channelID)
return
}
channel.Version++

saveState()

notifyChan <- Notification{channel.UAID, channel}

w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}

func wakeupClient(client *Client) {
log.Println("wakeupClient: ", client)
service := fmt.Sprintf("%s:%g", client.Ip, client.Port)

udpAddr, err := net.ResolveUDPAddr("udp4", service)
if err != nil {
log.Println("ResolveUDPAddr error ", err.Error())
return
}

conn, err := net.DialUDP("udp", nil, udpAddr)
if err != nil {
log.Println("DialUDP error ", err.Error())
return
}

_, err = conn.Write([]byte("push"))
if err != nil {
log.Println("UDP Write error ", err.Error())
return
}

}

func sendNotificationToClient(client *Client, channel *Channel) {

type NotificationResponse struct {
Name string `json:"messageType"`
Channels []Channel `json:"updates"`
}

var channels []Channel
channels = append(channels, *channel)

notification := NotificationResponse{"notification", channels}

j, err := json.Marshal(notification)
if err != nil {
log.Println("Could not convert hello response to json %s", err)
return
}

if err = websocket.Message.Send(client.Websocket, string(j)); err != nil {
log.Println("Could not send message to ", channel, err.Error())
}
}

func disconnectUDPClient(uaid string) {
if gServerState.ConnectedClients[uaid].Websocket == nil {
return
}
gServerState.ConnectedClients[uaid].Websocket.CloseWithStatus(4774)
gServerState.ConnectedClients[uaid].Websocket = nil
}

func attemptDelivery(notification Notification) {
log.Println("AttemptDelivery ", notification)
client, ok := gServerState.ConnectedClients[notification.UAID]
if !ok {
log.Println("no connected/wake-capable client for the channel.")
} else if client.Websocket == nil {
wakeupClient(client)
} else {
sendNotificationToClient(client, notification.Channel)
}

}

func deliverNotifications(notifyChan chan Notification, ackChan chan Ack) {
// indexed by channelID so that new notifications
// automatically remove old ones
// if a new version comes in for a 'pending' channelID
// that's ok, because if the client gives an ack for an older
// version we just ignore it and try to deliver the new version
pending := make(map[string]Notification, 0)
lastAttempt := time.Now()
for {
select {
case newPending := <-notifyChan:
log.Println("Got new notification to deliver ", newPending)
pending[newPending.Channel.ChannelID] = newPending
attemptDelivery(newPending)

case newAck := <-ackChan:
log.Println("Got new ACK ", newAck)
entry, ok := pending[newAck.ChannelID]
if ok {
// if Version < newAck.Version
// the client acknowledged a future notification, bad client
// if Version > newAck.Version
// the client acknowledged an old notification, ignore
if entry.Channel.Version == newAck.Version {
log.Println("Deleting from pending")
delete(pending, entry.Channel.ChannelID)
}
}

case <-time.After(10 * time.Millisecond):
if time.Since(lastAttempt).Seconds() > 15 {
lastAttempt = time.Now()
log.Println("Attempting to deliver ", len(pending), " pending notifications")
for _, notification := range pending {
attemptDelivery(notification)
}
}
}
}
}

func admin(w http.ResponseWriter, r *http.Request) {

memstats := new(runtime.MemStats)
runtime.ReadMemStats(memstats)

totalMemory := memstats.Alloc
type User struct {
UAID string
Connected bool
Channels []*Channel
}

type Arguments struct {
PushEndpointPrefix string
TotalMemory uint64
Users []User
}

arguments := Arguments{makeNotifyURL(""), totalMemory, nil}

for uaid, channelIDSet := range gServerState.UAIDToChannelIDs {
connected := gServerState.ConnectedClients[uaid].Websocket != nil
var channels []*Channel
for _, channel := range channelIDSet {
channels = append(channels, channel)
}
u := User{uaid, connected, channels}
arguments.Users = append(arguments.Users, u)
}

t := template.New("users.template")
s1, _ := t.ParseFiles("templates/users.template")
s1.Execute(w, arguments)
}

func main() {

readConfig()

openState()

notifyChan = make(chan Notification)
ackChan = make(chan Ack)

http.HandleFunc("/admin", admin)

http.Handle("/", websocket.Handler(pushHandler))

http.HandleFunc(gServerConfig.NotifyPrefix, notifyHandler)

go deliverNotifications(notifyChan, ackChan)

go func() {
c := time.Tick(10 * time.Second)
for now := range c {
for uaid, client := range gServerState.ConnectedClients {
if now.Sub(client.LastContact).Seconds() > 15 && client.Ip != "" {
log.Println("Will wake up ", client.Ip, ". closing connection")
disconnectUDPClient(uaid)
}
}
}
}()

log.Println("Listening on", gServerConfig.Hostname+":"+gServerConfig.Port)

var err error
if gServerConfig.UseTLS {
err = http.ListenAndServeTLS(gServerConfig.Hostname+":"+gServerConfig.Port,
gServerConfig.CertFilename,
gServerConfig.KeyFilename,
nil)
} else {
for i := 0; i < 5; i++ {
log.Println("This is a really unsafe way to run the push server. Really. Don't do this in production.")
}
err = http.ListenAndServe(gServerConfig.Hostname+":"+gServerConfig.Port, nil)
}

log.Println("Exiting... ", err)
}
Something went wrong with that request. Please try again.