/
cockpit.js
4566 lines (3883 loc) · 143 KB
/
cockpit.js
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of Cockpit.
*
* Copyright (C) 2014 Red Hat, Inc.
*
* Cockpit is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Cockpit 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/
var url_root;
try {
// Sometimes this throws a SecurityError such as during testing
url_root = window.localStorage.getItem('url-root');
} catch(e) { }
var mock = mock || { };
(function() {
"use strict";
var cockpit = { };
event_mixin(cockpit, { });
if (typeof window.debugging === "undefined") {
try {
// Sometimes this throws a SecurityError such as during testing
window.debugging = window.sessionStorage["debugging"] ||
window.localStorage["debugging"];
} catch(e) { }
}
function in_array(array, val) {
var length = array.length;
for (var i = 0; i < length; i++) {
if (val === array[i])
return true;
}
return false;
}
/* HACK: http://web.mit.edu/jwalden/www/isArray.html */
function is_array(it) {
return Object.prototype.toString.call(it) === '[object Array]';
}
function is_function(x) {
return typeof x === 'function';
}
function is_object(x) {
return x !== null && typeof x === 'object';
}
function is_plain_object(x) {
return is_object(x) && Object.prototype.toString.call(x) === '[object Object]';
}
/* Also works for negative zero */
function is_negative(n) {
return ((n = +n) || 1 / n) < 0;
}
/* Object.assign() workalike */
function extend(to/* , from ... */) {
var j, len, key, from;
for (j = 1, len = arguments.length; j < len; j++) {
from = arguments[j];
if (from) {
for (key in from) {
if (from[key] !== undefined)
to[key] = from[key];
}
}
}
return to;
}
function invoke_functions(functions, self, args) {
var length = functions ? functions.length : 0;
for (var i = 0; i < length; i++) {
if (functions[i])
functions[i].apply(self, args);
}
}
/* -------------------------------------------------------------------------
* Channels
*
* Public: http://cockpit-project.org/guide/latest/api-base1.html
*/
var default_transport = null;
var public_transport = null;
var reload_after_disconnect = false;
var expect_disconnect = false;
var init_callback = null;
var default_host = null;
var process_hints = null;
var incoming_filters = null;
var outgoing_filters = null;
var transport_origin = window.location.origin;
if (!transport_origin) {
transport_origin = window.location.protocol + "//" + window.location.hostname +
(window.location.port ? ':' + window.location.port: '');
}
function array_from_raw_string(str, constructor) {
var length = str.length;
/* jshint -W056 */
var data = new (constructor || Array)(length);
for (var i = 0; i < length; i++)
data[i] = str.charCodeAt(i) & 0xFF;
return data;
}
function array_to_raw_string(data) {
var length = data.length, str = "";
for (var i = 0; i < length; i++)
str += String.fromCharCode(data[i]);
return str;
}
/*
* These are the polyfills from Mozilla. It's pretty nasty that
* these weren't in the typed array standardization.
*
* https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
*/
function uint6_to_b64 (x) {
return x < 26 ? x + 65 : x < 52 ? x + 71 : x < 62 ? x - 4 : x === 62 ? 43 : x === 63 ? 47 : 65;
}
function base64_encode(data) {
if (typeof data === "string")
return window.btoa(data);
/* For when the caller has chosen to use ArrayBuffer */
if (data instanceof window.ArrayBuffer)
data = new window.Uint8Array(data);
var length = data.length, mod3 = 2, str = "";
for (var uint24 = 0, i = 0; i < length; i++) {
mod3 = i % 3;
uint24 |= data[i] << (16 >>> mod3 & 24);
if (mod3 === 2 || length - i === 1) {
str += String.fromCharCode(uint6_to_b64(uint24 >>> 18 & 63),
uint6_to_b64(uint24 >>> 12 & 63),
uint6_to_b64(uint24 >>> 6 & 63),
uint6_to_b64(uint24 & 63));
uint24 = 0;
}
}
return str.substr(0, str.length - 2 + mod3) + (mod3 === 2 ? '' : mod3 === 1 ? '=' : '==');
}
function b64_to_uint6 (x) {
return x > 64 && x < 91 ? x - 65 : x > 96 && x < 123 ?
x - 71 : x > 47 && x < 58 ? x + 4 : x === 43 ? 62 : x === 47 ? 63 : 0;
}
function base64_decode(str, constructor) {
if (constructor === String)
return window.atob(str);
var ilen = str.length;
for (var eq = 0; eq < 3; eq++) {
if (str[ilen - (eq + 1)] != '=')
break;
}
var olen = (ilen * 3 + 1 >> 2) - eq;
/* jshint -W056 */
var data = new (constructor || Array)(olen);
for (var mod3, mod4, uint24 = 0, oi = 0, ii = 0; ii < ilen; ii++) {
mod4 = ii & 3;
uint24 |= b64_to_uint6(str.charCodeAt(ii)) << 18 - 6 * mod4;
if (mod4 === 3 || ilen - ii === 1) {
for (mod3 = 0; mod3 < 3 && oi < olen; mod3++, oi++)
data[oi] = uint24 >>> (16 >>> mod3 & 24) & 255;
uint24 = 0;
}
}
return data;
}
window.addEventListener('beforeunload', function() {
expect_disconnect = true;
}, false);
function transport_debug() {
if (window.debugging == "all" || window.debugging == "channel")
console.debug.apply(console, arguments);
}
/*
* Extends an object to have the standard DOM style addEventListener
* removeEventListener and dispatchEvent methods. The dispatchEvent
* method has the additional capability to create a new event from a type
* string and arguments.
*/
function event_mixin(obj, handlers) {
Object.defineProperties(obj, {
addEventListener: {
enumerable: false,
value: function addEventListener(type, handler) {
if (handlers[type] === undefined)
handlers[type] = [ ];
handlers[type].push(handler);
}
},
removeEventListener: {
enumerable: false,
value: function removeEventListener(type, handler) {
var length = handlers[type] ? handlers[type].length : 0;
for (var i = 0; i < length; i++) {
if (handlers[type][i] === handler) {
handlers[type][i] = null;
break;
}
}
}
},
dispatchEvent: {
enumerable: false,
value: function dispatchEvent(event) {
var type, args;
if (typeof event === "string") {
type = event;
args = Array.prototype.slice.call(arguments, 1);
event = document.createEvent("CustomEvent");
if (arguments.length == 2)
event.initCustomEvent(type, false, false, arguments[1]);
else if (arguments.length > 2)
event.initCustomEvent(type, false, false, args);
else
event.initCustomEvent(type, false, false, null);
args.unshift(event);
} else {
type = event.type;
args = arguments;
}
if (is_function(obj['on' + type]))
obj['on' + type].apply(obj, args);
invoke_functions(handlers[type], obj, args);
}
}
});
}
function calculate_application() {
var path = window.location.pathname || "/";
var _url_root = url_root;
if (window.mock && window.mock.pathname)
path = window.mock.pathname;
if (window.mock && window.mock.url_root)
_url_root = window.mock.url_root;
if (_url_root && path.indexOf('/' + _url_root) === 0)
path = path.replace('/' + _url_root, '') || '/';
if (path.indexOf("/cockpit/") !== 0 && path.indexOf("/cockpit+") !== 0) {
if (path.indexOf("/=") === 0)
path = "/cockpit+" + path.split("/")[1];
else
path = "/cockpit";
}
return path.split("/")[1];
}
function calculate_url(suffix) {
if (!suffix)
suffix = "socket";
var window_loc = window.location.toString();
var _url_root = url_root;
if (window.mock && window.mock.url)
return window.mock.url;
if (window.mock && window.mock.url_root)
_url_root = window.mock.url_root;
var prefix = calculate_application();
if (_url_root)
prefix = _url_root + "/" + prefix;
if (window_loc.indexOf('http:') === 0) {
return "ws://" + window.location.host + "/" + prefix + "/" + suffix;
} else if (window_loc.indexOf('https:') === 0) {
return "wss://" + window.location.host + "/" + prefix + "/" + suffix;
} else {
transport_debug("Cockpit must be used over http or https");
return null;
}
}
function join_data(buffers, binary) {
if (!binary)
return buffers.join("");
var data;
var j, k, total = 0;
var i, length = buffers.length;
for (i = 0; i < length; i++)
total += buffers[i].length;
if (window.Uint8Array)
data = new window.Uint8Array(total);
else
data = new Array(total);
if (data.set) {
for (j = 0, i = 0; i < length; i++) {
data.set(buffers[i], j);
j += buffers[i].length;
}
} else {
for (j = 0, i = 0; i < length; i++) {
for (k = 0; k < buffers[i].length; k++)
data[i + j] = buffers[i][k];
j += buffers[i].length;
}
}
return data;
}
/*
* A WebSocket that connects to parent frame. The mechanism
* for doing this will eventually be documented publicly,
* but for now:
*
* * Forward raw cockpit1 string protocol messages via window.postMessage
* * Listen for cockpit1 string protocol messages via window.onmessage
* * Never accept or send messages to another origin
* * An empty string message means "close" (not completely used yet)
*/
function ParentWebSocket(parent) {
var self = this;
self.readyState = 0;
window.addEventListener("message", function receive(event) {
if (event.origin !== transport_origin || event.source !== parent)
return;
var data = event.data;
if (data === undefined || (data.length === undefined && data.byteLength === undefined))
return;
if (data.length === 0) {
self.readyState = 3;
self.onclose();
} else {
self.onmessage(event);
}
}, false);
self.send = function send(message) {
parent.postMessage(message, transport_origin);
};
self.close = function close() {
self.readyState = 3;
parent.postMessage("", transport_origin);
self.onclose();
};
window.setTimeout(function() {
self.readyState = 1;
self.onopen();
}, 0);
}
function parse_channel(data) {
var binary, length, pos, channel;
/* A binary message, split out the channel */
if (data instanceof window.ArrayBuffer) {
binary = new window.Uint8Array(data);
length = binary.length;
for (pos = 0; pos < length; pos++) {
if (binary[pos] == 10) /* new line */
break;
}
if (pos === length) {
console.warn("binary message without channel");
return null;
} else if (pos === 0) {
console.warn("binary control message");
return null;
} else {
channel = String.fromCharCode.apply(null, binary.subarray(0, pos));
}
/* A textual message */
} else {
pos = data.indexOf('\n');
if (pos === -1) {
console.warn("text message without channel");
return null;
}
channel = data.substring(0, pos);
}
return channel;
}
/* Private Transport class */
function Transport() {
var self = this;
self.application = calculate_application();
/* We can trigger events */
event_mixin(self, { });
var last_channel = 0;
var channel_seed = "";
if (window.mock)
window.mock.last_transport = self;
var ws;
var check_health_timer;
var ignore_health_check = false;
var got_message = false;
/* See if we should communicate via parent */
if (window.parent !== window && window.name.indexOf("cockpit1:") === 0)
ws = new ParentWebSocket(window.parent);
/* HACK: Compatibility if we're hosted by older Cockpit versions */
try {
/* See if we should communicate via parent */
if (!ws && window.parent !== window && window.parent.options &&
window.parent.options.protocol == "cockpit1") {
ws = new ParentWebSocket(window.parent);
}
} catch (ex) {
/* permission access errors */
}
if (!ws) {
var ws_loc = calculate_url();
transport_debug("connecting to " + ws_loc);
if (ws_loc) {
if ("WebSocket" in window) {
ws = new window.WebSocket(ws_loc, "cockpit1");
} else if ("MozWebSocket" in window) { // Firefox 6
ws = new window.MozWebSocket(ws_loc);
} else {
console.error("WebSocket not supported, application will not work!");
}
}
check_health_timer = window.setInterval(function () {
if (!got_message) {
if (ignore_health_check) {
console.log("health check failure ignored");
} else {
console.log("health check failed");
self.close({ "problem": "timeout" });
}
}
got_message = false;
}, 30000);
}
if (!ws) {
ws = { close: function() { } };
window.setTimeout(function() {
self.close({"problem": "no-cockpit"});
}, 50);
}
var control_cbs = { };
var message_cbs = { };
var waiting_for_init = true;
self.ready = false;
/* Called when ready for channels to interact */
function ready_for_channels() {
if (!self.ready) {
self.ready = true;
self.dispatchEvent("ready");
}
}
ws.onopen = function() {
if (ws) {
if (typeof ws.binaryType !== "undefined")
ws.binaryType = "arraybuffer";
ws.send("\n{ \"command\": \"init\", \"version\": 1 }");
}
};
ws.onclose = function() {
transport_debug("WebSocket onclose");
ws = null;
if (reload_after_disconnect) {
expect_disconnect = true;
window.location.reload(true);
}
self.close();
};
ws.onmessage = self.dispatch_data = function(arg) {
got_message = true;
/* The first line of a message is the channel */
var message = arg.data;
var channel = parse_channel(message);
if (channel === null)
return false;
var payload, control;
if (message instanceof window.ArrayBuffer)
payload = new window.Uint8Array(message, channel.length + 1);
else
payload = message.substring(channel.length + 1);
/* A control message, always string */
if (!channel) {
transport_debug("recv control:", payload);
control = JSON.parse(payload);
} else {
transport_debug("recv " + channel + ":", payload);
}
var i, length = incoming_filters ? incoming_filters.length : 0;
for (i = 0; i < length; i++) {
if (incoming_filters[i](message, channel, control) === false)
return false;
}
if (!channel)
process_control(control);
else
process_message(channel, payload);
return true;
};
self.close = function close(options) {
if (!options)
options = { "problem": "disconnected" };
options.command = "close";
window.clearInterval(check_health_timer);
var ows = ws;
ws = null;
if (ows)
ows.close();
if (expect_disconnect)
return;
ready_for_channels(); /* ready to fail */
/* Broadcast to everyone */
for (var chan in control_cbs)
control_cbs[chan].apply(null, [options]);
};
self.next_channel = function next_channel() {
last_channel++;
return channel_seed + String(last_channel);
};
function process_init(options) {
if (options.problem){
self.close({ "problem": options.problem });
return;
}
if (options.version !== 1) {
console.error("received unsupported version in init message: " + options.version);
self.close({"problem": "not-supported"});
return;
}
if (options["channel-seed"])
channel_seed = String(options["channel-seed"]);
if (options["host"])
default_host = options["host"];
if (public_transport) {
public_transport.options = options;
public_transport.csrf_token = options["csrf-token"];
public_transport.host = default_host;
}
if (init_callback)
init_callback(options);
if (waiting_for_init) {
waiting_for_init = false;
ready_for_channels();
}
}
function process_control(data) {
var channel = data.channel;
var func;
/* Init message received */
if (data.command == "init") {
process_init(data);
} else if (waiting_for_init) {
waiting_for_init = false;
if (data.command != "close" || channel) {
console.error("received message before init: ", data.command);
data = { "problem": "protocol-error" };
}
self.close(data);
} else if (data.command == "ping") {
/* 'ping' messages are ignored */
} else if (data.command == "hint") {
if (process_hints)
process_hints(data);
} else if (channel !== undefined) {
func = control_cbs[channel];
if (func)
func.apply(null, [data]);
}
}
function process_message(channel, payload) {
var func = message_cbs[channel];
if (func)
func.apply(null, [payload]);
}
/* The channel/control arguments is used by filters, and auto-populated if necessary */
self.send_data = function send_data(data, channel, control) {
if (!ws) {
console.log("transport closed, dropped message: ", data);
return false;
}
var i, length = outgoing_filters ? outgoing_filters.length : 0;
for (i = 0; i < length; i++) {
if (channel === undefined)
channel = parse_channel(data);
if (!channel && control === undefined)
control = JSON.parse(data);
if (outgoing_filters[i](data, channel, control) === false)
return false;
}
ws.send(data);
return true;
};
/* The control arguments is used by filters, and auto populated if necessary */
self.send_message = function send_message(payload, channel, control) {
if (channel)
transport_debug("send " + channel, payload);
else
transport_debug("send control:", payload);
/* A binary message */
if (payload.byteLength || is_array(payload)) {
if (payload instanceof window.ArrayBuffer)
payload = new window.Uint8Array(payload);
var output = join_data([array_from_raw_string(channel), [ 10 ], payload ], true);
return self.send_data(output.buffer, channel, control);
/* A string message */
} else {
return self.send_data(channel.toString() + "\n" + payload, channel, control);
}
};
self.send_control = function send_control(data) {
if(!ws && (data.command == "close" || data.command == "kill"))
return; /* don't complain if closed and closing */
if (check_health_timer &&
data.command == "hint" && data.hint == "ignore_transport_health_check") {
/* This is for us, process it directly. */
ignore_health_check = data.data;
return;
}
return self.send_message(JSON.stringify(data), "", data);
};
self.register = function register(channel, control_cb, message_cb) {
control_cbs[channel] = control_cb;
message_cbs[channel] = message_cb;
};
self.unregister = function unregister(channel) {
delete control_cbs[channel];
delete message_cbs[channel];
};
}
function ensure_transport(callback) {
var transport;
if (!default_transport)
default_transport = new Transport();
transport = default_transport;
if (transport.ready) {
callback(transport);
} else {
transport.addEventListener("ready", function() {
callback(transport);
});
}
}
/* Always close the transport explicitly: allows parent windows to track us */
window.addEventListener("unload", function() {
if (default_transport)
default_transport.close();
});
function Channel(options) {
var self = this;
/* We can trigger events */
event_mixin(self, { });
var transport;
var ready = null;
var closed = null;
var waiting = null;
var received_done = false;
var sent_done = false;
var id = null;
var binary = (options.binary === true);
/*
* Queue while waiting for transport, items are tuples:
* [is_control ? true : false, payload]
*/
var queue = [ ];
/* Handy for callers, but not used by us */
self.valid = true;
self.options = options;
self.binary = binary;
self.id = id;
function on_message(payload) {
if (received_done) {
console.warn("received message after done");
self.close("protocol-error");
} else {
self.dispatchEvent("message", payload);
}
}
function on_close(data) {
closed = data;
self.valid = false;
if (transport && id)
transport.unregister(id);
if (closed.message)
console.warn(closed.message);
self.dispatchEvent("close", closed);
if (waiting)
waiting.resolve(closed);
}
function on_ready(data) {
ready = data;
self.dispatchEvent("ready", ready);
}
function on_control(data) {
if (data.command == "close") {
on_close(data);
return;
} else if (data.command == "ready") {
on_ready(data);
}
var done = data.command === "done";
if (done && received_done) {
console.warn("received two done commands on channel");
self.close("protocol-error");
} else {
if (done)
received_done = true;
self.dispatchEvent("control", data);
}
}
function send_payload(payload) {
if (!binary) {
if (typeof payload !== "string")
payload = String(payload);
}
transport.send_message(payload, id);
}
ensure_transport(function(trans) {
transport = trans;
if (closed)
return;
id = transport.next_channel();
self.id = id;
/* Register channel handlers */
transport.register(id, on_control, on_message);
/* Now open the channel */
var command = { };
for (var i in options)
command[i] = options[i];
command.command = "open";
command.channel = id;
if (!command.host) {
if (default_host)
command.host = default_host;
}
if (binary)
command.binary = "raw";
else
delete command.binary;
transport.send_control(command);
/* Now drain the queue */
while(queue.length > 0) {
var item = queue.shift();
if (item[0]) {
item[1]["channel"] = id;
transport.send_control(item[1]);
} else {
send_payload(item[1]);
}
}
});
self.send = function send(message) {
if (closed)
console.warn("sending message on closed channel");
else if (sent_done)
console.warn("sending message after done");
else if (!transport)
queue.push([false, message]);
else
send_payload(message);
};
self.control = function control(options) {
options = options || { };
if (!options.command)
options.command = "options";
if (options.command === "done")
sent_done = true;
options.channel = id;
if (!transport)
queue.push([true, options]);
else
transport.send_control(options);
};
self.wait = function wait(callback) {
if (!waiting) {
waiting = cockpit.defer();
if (closed) {
waiting.reject(closed);
} else if (ready) {
waiting.resolve(ready);
} else {
self.addEventListener("ready", function(event, data) {
waiting.resolve(data);
});
self.addEventListener("close", function(event, data) {
waiting.reject(data);
});
}
}
var promise = waiting.promise;
if (callback)
promise.then(callback, callback);
return promise;
};
self.close = function close(options) {
if (closed)
return;
if (!options)
options = { };
else if (typeof options == "string")
options = { "problem" : options };
options["command"] = "close";
options["channel"] = id;
if (!transport)
queue.push([true, options]);
else
transport.send_control(options);
on_close(options);
};
self.buffer = function buffer(callback) {
var buffers = [];
buffers.callback = callback;
buffers.squash = function squash() {
return join_data(buffers, binary);
};
function on_message(event, data) {
var consumed, block;
buffers.push(data);
if (buffers.callback) {
block = join_data(buffers, binary);
if (block.length > 0) {
consumed = buffers.callback.call(self, block);
if (typeof consumed !== "number" || consumed === block.length) {
buffers.length = 0;
} else if (consumed === 0) {
buffers.length = 1;
buffers[0] = block;
} else if (consumed !== 0) {
buffers.length = 1;
if (block.subarray)
buffers[0] = block.subarray(consumed);
else if (block.substring)
buffers[0] = block.substring(consumed);
else
buffers[0] = block.slice(consumed);
}
}
}
}
function on_close() {
self.removeEventListener("message", on_message);
self.removeEventListener("close", on_close);
}
self.addEventListener("message", on_message);
self.addEventListener("close", on_close);
return buffers;
};
self.toString = function toString() {
var host = options["host"] || "localhost";
return "[Channel " + (self.valid ? id : "<invalid>") + " -> " + host + "]";
};
}
/* Resolve dots and double dots */
function resolve_path_dots(parts) {
var out = [ ];
var length = parts.length;
for (var i = 0; i < length; i++) {
var part = parts[i];
if (part === "" || part == ".") {
continue;
} else if (part == "..") {
if (out.length === 0)
return null;
out.pop();
} else {
out.push(part);
}
}
return out;
}
function factory() {
cockpit.channel = function channel(options) {
return new Channel(options);
};
cockpit.event_target = function event_target(obj) {
event_mixin(obj, { });
return obj;
};
cockpit.extend = extend;
/* These can be filled in by loading ../manifests.js */
cockpit.manifests = { };
/* ------------------------------------------------------------
* Text Encoding