This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
protocol.js
688 lines (610 loc) · 24.4 KB
/
protocol.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
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function (root, factory) {
if (typeof exports === 'object')
module.exports = factory(require('wbxml'), require('activesync/codepages'));
else if (typeof define === 'function' && define.amd)
define(['wbxml', 'activesync/codepages'], factory);
else
root.ActiveSyncProtocol = factory(WBXML, ActiveSyncCodepages);
}(this, function(WBXML, ASCP) {
'use strict';
var exports = {};
var USER_AGENT = 'JavaScript ActiveSync (jsas) Client';
function nullCallback() {}
/**
* Create a constructor for a custom error type that works like a built-in
* Error.
*
* @param name the string name of the error
* @param parent (optional) a parent class for the error, defaults to Error
* @param extraArgs an array of extra arguments that can be passed to the
* constructor of this error type
* @return the constructor for this error
*/
function makeError(name, parent, extraArgs) {
function CustomError() {
// Try to let users call this as CustomError(...) without the "new". This
// is imperfect, and if you call this function directly and give it a
// |this| that's a CustomError, things will break. Don't do it!
var self = this instanceof CustomError ?
this : Object.create(CustomError.prototype);
var tmp = Error();
var offset = 1;
self.stack = tmp.stack.substring(tmp.stack.indexOf('\n') + 1);
self.message = arguments[0] || tmp.message;
if (extraArgs) {
offset += extraArgs.length;
for (var i = 0; i < extraArgs.length; i++)
self[extraArgs[i]] = arguments[i+1];
}
var m = /@(.+):(.+)/.exec(self.stack);
self.fileName = arguments[offset] || (m && m[1]) || "";
self.lineNumber = arguments[offset + 1] || (m && m[2]) || 0;
return self;
}
CustomError.prototype = Object.create((parent || Error).prototype);
CustomError.prototype.name = name;
CustomError.prototype.constructor = CustomError;
return CustomError;
}
var AutodiscoverError = makeError('ActiveSync.AutodiscoverError');
exports.AutodiscoverError = AutodiscoverError;
var AutodiscoverDomainError = makeError('ActiveSync.AutodiscoverDomainError',
AutodiscoverError);
exports.AutodiscoverDomainError = AutodiscoverDomainError;
var HttpError = makeError('ActiveSync.HttpError', null, ['status']);
exports.HttpError = HttpError;
function nsResolver(prefix) {
var baseUrl = 'http://schemas.microsoft.com/exchange/autodiscover/';
var ns = {
rq: baseUrl + 'mobilesync/requestschema/2006',
ad: baseUrl + 'responseschema/2006',
ms: baseUrl + 'mobilesync/responseschema/2006',
};
return ns[prefix] || null;
}
function Version(str) {
var details = str.split('.').map(function(x) {
return parseInt(x);
});
this.major = details[0], this.minor = details[1];
}
exports.Version = Version;
Version.prototype = {
eq: function(other) {
if (!(other instanceof Version))
other = new Version(other);
return this.major === other.major && this.minor === other.minor;
},
ne: function(other) {
return !this.eq(other);
},
gt: function(other) {
if (!(other instanceof Version))
other = new Version(other);
return this.major > other.major ||
(this.major === other.major && this.minor > other.minor);
},
gte: function(other) {
if (!(other instanceof Version))
other = new Version(other);
return this.major >= other.major ||
(this.major === other.major && this.minor >= other.minor);
},
lt: function(other) {
return !this.gte(other);
},
lte: function(other) {
return !this.gt(other);
},
toString: function() {
return this.major + '.' + this.minor;
},
};
/**
* Set the Authorization header on an XMLHttpRequest.
*
* @param xhr the XMLHttpRequest
* @param username the username
* @param password the user's password
*/
function setAuthHeader(xhr, username, password) {
var authorization = 'Basic ' + btoa(username + ':' + password);
xhr.setRequestHeader('Authorization', authorization);
}
/**
* Perform autodiscovery for the server associated with this account.
*
* @param aEmailAddress the user's email address
* @param aPassword the user's password
* @param aTimeout a timeout (in milliseconds) for the request
* @param aCallback a callback taking an error status (if any) and the
* server's configuration
* @param aNoRedirect true if autodiscovery should *not* follow any
* specified redirects (typically used when autodiscover has already
* told us about a redirect)
*/
function autodiscover(aEmailAddress, aPassword, aTimeout, aCallback,
aNoRedirect) {
if (!aCallback) aCallback = nullCallback;
var domain = aEmailAddress.substring(aEmailAddress.indexOf('@') + 1);
// The first time we try autodiscovery, we should try to recover from
// AutodiscoverDomainErrors and HttpErrors. The second time, *all* errors
// should be reported to the callback.
do_autodiscover(domain, aEmailAddress, aPassword, aTimeout, aNoRedirect,
function(aError, aConfig) {
if (aError instanceof AutodiscoverDomainError ||
aError instanceof HttpError)
do_autodiscover('autodiscover.' + domain, aEmailAddress, aPassword,
aTimeout, aNoRedirect, aCallback);
else
aCallback(aError, aConfig);
});
}
exports.autodiscover = autodiscover;
/**
* Perform the actual autodiscovery process for a given URL.
*
* @param aHost the host name to attempt autodiscovery for
* @param aEmailAddress the user's email address
* @param aPassword the user's password
* @param aTimeout a timeout (in milliseconds) for the request
* @param aNoRedirect true if autodiscovery should *not* follow any
* specified redirects (typically used when autodiscover has already
* told us about a redirect)
* @param aCallback a callback taking an error status (if any) and the
* server's configuration
*/
function do_autodiscover(aHost, aEmailAddress, aPassword, aTimeout,
aNoRedirect, aCallback) {
var xhr = new XMLHttpRequest({mozSystem: true, mozAnon: true});
xhr.open('POST', 'https://' + aHost + '/autodiscover/autodiscover.xml',
true);
setAuthHeader(xhr, aEmailAddress, aPassword);
xhr.setRequestHeader('Content-Type', 'text/xml');
xhr.setRequestHeader('User-Agent', USER_AGENT);
xhr.timeout = aTimeout;
xhr.upload.onprogress = xhr.upload.onload = function() {
xhr.timeout = 0;
};
xhr.onload = function() {
if (xhr.status < 200 || xhr.status >= 300)
return aCallback(new HttpError(xhr.statusText, xhr.status));
var doc = new DOMParser().parseFromString(xhr.responseText, 'text/xml');
function getNode(xpath, rel) {
return doc.evaluate(xpath, rel, nsResolver,
XPathResult.FIRST_ORDERED_NODE_TYPE, null)
.singleNodeValue;
}
function getNodes(xpath, rel) {
return doc.evaluate(xpath, rel, nsResolver,
XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
}
function getString(xpath, rel) {
return doc.evaluate(xpath, rel, nsResolver, XPathResult.STRING_TYPE,
null).stringValue;
}
if (doc.documentElement.tagName === 'parsererror')
return aCallback(new AutodiscoverDomainError(
'Error parsing autodiscover response'));
var responseNode = getNode('/ad:Autodiscover/ms:Response', doc);
if (!responseNode)
return aCallback(new AutodiscoverDomainError(
'Missing Autodiscover Response node'));
var error = getNode('ms:Error', responseNode) ||
getNode('ms:Action/ms:Error', responseNode);
if (error)
return aCallback(new AutodiscoverError(
getString('ms:Message/text()', error)));
var redirect = getNode('ms:Action/ms:Redirect', responseNode);
if (redirect) {
if (aNoRedirect)
return aCallback(new AutodiscoverError(
'Multiple redirects occurred during autodiscovery'));
var redirectedEmail = getString('text()', redirect);
return autodiscover(redirectedEmail, aPassword, aTimeout, aCallback,
true);
}
var user = getNode('ms:User', responseNode);
var config = {
culture: getString('ms:Culture/text()', responseNode),
user: {
name: getString('ms:DisplayName/text()', user),
email: getString('ms:EMailAddress/text()', user),
},
servers: [],
};
var servers = getNodes('ms:Action/ms:Settings/ms:Server', responseNode);
var server;
while ((server = servers.iterateNext())) {
config.servers.push({
type: getString('ms:Type/text()', server),
url: getString('ms:Url/text()', server),
name: getString('ms:Name/text()', server),
serverData: getString('ms:ServerData/text()', server),
});
}
// Try to find a MobileSync server from Autodiscovery.
for (var iter in Iterator(config.servers)) {
var server = iter[1];
if (server.type === 'MobileSync') {
config.mobileSyncServer = server;
break;
}
}
if (!config.mobileSyncServer) {
return aCallback(new AutodiscoverError('No MobileSync server found'),
config);
}
aCallback(null, config);
};
xhr.ontimeout = xhr.onerror = function() {
// Something bad happened in the network layer, so treat this like an HTTP
// error.
aCallback(new HttpError('Error getting Autodiscover URL', null));
};
// TODO: use something like
// http://ejohn.org/blog/javascript-micro-templating/ here?
var postdata =
'<?xml version="1.0" encoding="utf-8"?>\n' +
'<Autodiscover xmlns="' + nsResolver('rq') + '">\n' +
' <Request>\n' +
' <EMailAddress>' + aEmailAddress + '</EMailAddress>\n' +
' <AcceptableResponseSchema>' + nsResolver('ms') +
'</AcceptableResponseSchema>\n' +
' </Request>\n' +
'</Autodiscover>';
xhr.send(postdata);
}
/**
* Create a new ActiveSync connection.
*
* ActiveSync connections use XMLHttpRequests to communicate with the
* server. These XHRs are created with mozSystem: true and mozAnon: true to,
* respectively, help with CORS, and to ignore the authentication cache. The
* latter is important because 1) it prevents the HTTP auth dialog from
* appearing if the user's credentials are wrong and 2) it allows us to
* connect to the same server as multiple users.
*
* @param aDeviceId (optional) a string identifying this device
* @param aDeviceType (optional) a string identifying the type of this device
*/
function Connection(aDeviceId, aDeviceType) {
this._deviceId = aDeviceId || 'v140Device';
this._deviceType = aDeviceType || 'SmartPhone';
this.timeout = 0;
this._connected = false;
this._waitingForConnection = false;
this._connectionError = null;
this._connectionCallbacks = [];
this.baseUrl = null;
this._username = null;
this._password = null;
this.versions = [];
this.supportedCommands = [];
this.currentVersion = null;
}
exports.Connection = Connection;
Connection.prototype = {
/**
* Perform any callbacks added during the connection process.
*
* @param aError the error status (if any)
*/
_notifyConnected: function(aError) {
if (aError)
this.disconnect();
for (var iter in Iterator(this._connectionCallbacks)) {
var callback = iter[1];
callback.apply(callback, arguments);
}
this._connectionCallbacks = [];
},
/**
* Get the connection status.
*
* @return true iff we are fully connected to the server
*/
get connected() {
return this._connected;
},
/*
* Initialize the connection with a server and account credentials.
*
* @param aURL the ActiveSync URL to connect to
* @param aUsername the account's username
* @param aPassword the account's password
*/
open: function(aURL, aUsername, aPassword) {
// XXX: We add the default service path to the URL if it's not already
// there. This is a hack to work around the failings of Hotmail (and
// possibly other servers), which doesn't provide the service path in its
// URL. If it turns out this causes issues with other domains, remove it.
var servicePath = '/Microsoft-Server-ActiveSync';
this.baseUrl = aURL;
if (!this.baseUrl.endsWith(servicePath))
this.baseUrl += servicePath;
this._username = aUsername;
this._password = aPassword;
},
/**
* Connect to the server with this account by getting the OPTIONS from
* the server (and verifying the account's credentials).
*
* @param aCallback a callback taking an error status (if any) and the
* server's options.
*/
connect: function(aCallback) {
// If we're already connected, just run the callback and return.
if (this.connected) {
if (aCallback)
aCallback(null);
return;
}
// Otherwise, queue this callback up to fire when we do connect.
if (aCallback)
this._connectionCallbacks.push(aCallback);
// Don't do anything else if we're already trying to connect.
if (this._waitingForConnection)
return;
this._waitingForConnection = true;
this._connectionError = null;
this.getOptions((function(aError, aOptions) {
this._waitingForConnection = false;
this._connectionError = aError;
if (aError) {
console.error('Error connecting to ActiveSync:', aError);
return this._notifyConnected(aError, aOptions);
}
this._connected = true;
this.versions = aOptions.versions;
this.supportedCommands = aOptions.commands;
this.currentVersion = new Version(aOptions.versions.slice(-1)[0]);
return this._notifyConnected(null, aOptions);
}).bind(this));
},
/**
* Disconnect from the ActiveSync server, and reset the connection state.
* The server and credentials remain set however, so you can safely call
* connect() again immediately after.
*/
disconnect: function() {
if (this._waitingForConnection)
throw new Error("Can't disconnect while waiting for server response");
this._connected = false;
this.versions = [];
this.supportedCommands = [];
this.currentVersion = null;
},
/**
* Attempt to provision this account. XXX: Currently, this doesn't actually
* do anything, but it's useful as a test command for Gmail to ensure that
* the user entered their password correctly.
*
* @param aCallback a callback taking an error status (if any) and the
* WBXML response
*/
provision: function(aCallback) {
var pv = ASCP.Provision.Tags;
var w = new WBXML.Writer('1.3', 1, 'UTF-8');
w.stag(pv.Provision)
.etag();
this.postCommand(w, aCallback);
},
/**
* Get the options for the server associated with this account.
*
* @param aCallback a callback taking an error status (if any), and the
* resulting options.
*/
getOptions: function(aCallback) {
if (!aCallback) aCallback = nullCallback;
var conn = this;
var xhr = new XMLHttpRequest({mozSystem: true, mozAnon: true});
xhr.open('OPTIONS', this.baseUrl, true);
setAuthHeader(xhr, this._username, this._password);
xhr.setRequestHeader('User-Agent', USER_AGENT);
xhr.timeout = this.timeout;
xhr.upload.onprogress = xhr.upload.onload = function() {
xhr.timeout = 0;
};
xhr.onload = function() {
if (xhr.status < 200 || xhr.status >= 300) {
console.error('ActiveSync options request failed with response ' +
xhr.status);
aCallback(new HttpError(xhr.statusText, xhr.status));
return;
}
// These headers are comma-separated lists. Sometimes, people like to
// put spaces after the commas, so make sure we trim whitespace too.
var result = {
versions: xhr.getResponseHeader('MS-ASProtocolVersions')
.split(/\s*,\s*/),
commands: xhr.getResponseHeader('MS-ASProtocolCommands')
.split(/\s*,\s*/)
};
aCallback(null, result);
};
xhr.ontimeout = xhr.onerror = function() {
var error = new Error('Error getting OPTIONS URL');
console.error(error);
aCallback(error);
};
// Set the response type to "text" so that we don't try to parse an empty
// body as XML.
xhr.responseType = 'text';
xhr.send();
},
/**
* Check if the server supports a particular command. Requires that we be
* connected to the server already.
*
* @param aCommand a string/tag representing the command type
* @return true iff the command is supported
*/
supportsCommand: function(aCommand) {
if (!this.connected)
throw new Error('Connection required to get command');
if (typeof aCommand === 'number')
aCommand = ASCP.__tagnames__[aCommand];
return this.supportedCommands.indexOf(aCommand) !== -1;
},
/**
* DEPRECATED. See postCommand() below.
*/
doCommand: function() {
console.warn('doCommand is deprecated. Use postCommand instead.');
this.postCommand.apply(this, arguments);
},
/**
* Send a WBXML command to the ActiveSync server and listen for the
* response.
*
* @param aCommand the WBXML representing the command or a string/tag
* representing the command type for empty commands
* @param aCallback a callback to call when the server has responded; takes
* two arguments: an error status (if any) and the response as a
* WBXML reader. If the server returned an empty response, the
* response argument is null.
* @param aExtraParams (optional) an object containing any extra URL
* parameters that should be added to the end of the request URL
* @param aExtraHeaders (optional) an object containing any extra HTTP
* headers to send in the request
* @param aProgressCallback (optional) a callback to invoke with progress
* information, when available. Two arguments are provided: the
* number of bytes received so far, and the total number of bytes
* expected (when known, 0 if unknown).
*/
postCommand: function(aCommand, aCallback, aExtraParams, aExtraHeaders,
aProgressCallback) {
var contentType = 'application/vnd.ms-sync.wbxml';
if (typeof aCommand === 'string' || typeof aCommand === 'number') {
this.postData(aCommand, contentType, null, aCallback, aExtraParams,
aExtraHeaders);
}
else {
var r = new WBXML.Reader(aCommand, ASCP);
var commandName = r.document[0].localTagName;
this.postData(commandName, contentType, aCommand.buffer, aCallback,
aExtraParams, aExtraHeaders, aProgressCallback);
}
},
/**
* Send arbitrary data to the ActiveSync server and listen for the response.
*
* @param aCommand a string (or WBXML tag) representing the command type
* @param aContentType the content type of the post data
* @param aData the data to be posted
* @param aCallback a callback to call when the server has responded; takes
* two arguments: an error status (if any) and the response as a
* WBXML reader. If the server returned an empty response, the
* response argument is null.
* @param aExtraParams (optional) an object containing any extra URL
* parameters that should be added to the end of the request URL
* @param aExtraHeaders (optional) an object containing any extra HTTP
* headers to send in the request
* @param aProgressCallback (optional) a callback to invoke with progress
* information, when available. Two arguments are provided: the
* number of bytes received so far, and the total number of bytes
* expected (when known, 0 if unknown).
*/
postData: function(aCommand, aContentType, aData, aCallback, aExtraParams,
aExtraHeaders, aProgressCallback) {
// Make sure our command name is a string.
if (typeof aCommand === 'number')
aCommand = ASCP.__tagnames__[aCommand];
if (!this.supportsCommand(aCommand)) {
var error = new Error("This server doesn't support the command " +
aCommand);
console.error(error);
aCallback(error);
return;
}
// Build the URL parameters.
var params = [
['Cmd', aCommand],
['User', this._username],
['DeviceId', this._deviceId],
['DeviceType', this._deviceType]
];
if (aExtraParams) {
for (var iter in Iterator(params)) {
var param = iter[1];
if (param[0] in aExtraParams)
throw new TypeError('reserved URL parameter found');
}
for (var kv in Iterator(aExtraParams))
params.push(kv);
}
var paramsStr = params.map(function(i) {
return encodeURIComponent(i[0]) + '=' + encodeURIComponent(i[1]);
}).join('&');
// Now it's time to make our request!
var xhr = new XMLHttpRequest({mozSystem: true, mozAnon: true});
xhr.open('POST', this.baseUrl + '?' + paramsStr, true);
setAuthHeader(xhr, this._username, this._password);
xhr.setRequestHeader('MS-ASProtocolVersion', this.currentVersion);
xhr.setRequestHeader('Content-Type', aContentType);
xhr.setRequestHeader('User-Agent', USER_AGENT);
// Add extra headers if we have any.
if (aExtraHeaders) {
for (var iter in Iterator(aExtraHeaders)) {
var key = iter[0], value = iter[1];
xhr.setRequestHeader(key, value);
}
}
xhr.timeout = this.timeout;
xhr.upload.onprogress = xhr.upload.onload = function() {
xhr.timeout = 0;
};
xhr.onprogress = function(event) {
if (aProgressCallback)
aProgressCallback(event.loaded, event.total);
};
var conn = this;
var parentArgs = arguments;
xhr.onload = function() {
// This status code is a proprietary Microsoft extension used to
// indicate a redirect, not to be confused with the draft-standard
// "Unavailable For Legal Reasons" status. More info available here:
// <http://msdn.microsoft.com/en-us/library/gg651019.aspx>
if (xhr.status === 451) {
conn.baseUrl = xhr.getResponseHeader('X-MS-Location');
conn.postData.apply(conn, parentArgs);
return;
}
if (xhr.status < 200 || xhr.status >= 300) {
console.error('ActiveSync command ' + aCommand + ' failed with ' +
'response ' + xhr.status);
aCallback(new HttpError(xhr.statusText, xhr.status));
return;
}
var response = null;
if (xhr.response.byteLength > 0)
response = new WBXML.Reader(new Uint8Array(xhr.response), ASCP);
aCallback(null, response);
};
xhr.ontimeout = xhr.onerror = function() {
var error = new Error('Error getting command URL');
console.error(error);
aCallback(error);
};
xhr.responseType = 'arraybuffer';
xhr.send(aData);
},
};
return exports;
}));