-
Notifications
You must be signed in to change notification settings - Fork 143
/
http_jmap.c
1882 lines (1625 loc) · 55.3 KB
/
http_jmap.c
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
/* http_jmap.c -- Routines for handling JMAP requests in httpd
*
* Copyright (c) 1994-2014 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Carnegie Mellon University
* Center for Technology Transfer and Enterprise Creation
* 4615 Forbes Avenue
* Suite 302
* Pittsburgh, PA 15213
* (412) 268-7393, fax: (412) 268-7395
* innovation@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <config.h>
#include <sasl/sasl.h>
#include <sasl/saslutil.h>
#ifdef HAVE_SSL
#include <openssl/hmac.h>
#include <openssl/rand.h>
#endif /* HAVE_SSL */
#include "append.h"
#include "cyrusdb.h"
#include "hash.h"
#include "httpd.h"
#include "http_dav.h"
#include "http_proxy.h"
#include "mboxname.h"
#include "msgrecord.h"
#include "proxy.h"
#include "times.h"
#include "syslog.h"
#include "xstrlcpy.h"
/* generated headers are not necessarily in current directory */
#include "imap/http_err.h"
#include "imap/imap_err.h"
#include "http_jmap.h"
struct namespace jmap_namespace;
static time_t compile_time;
/* HTTP method handlers */
static int jmap_get(struct transaction_t *txn, void *params);
static int jmap_post(struct transaction_t *txn, void *params);
static int jmap_delete(struct transaction_t *txn, void *params);
/* Namespace callbacks */
static void jmap_init(struct buf *serverinfo);
static int jmap_checkurl(struct transaction_t *txn);
static void jmap_auth(const char *userid);
static int jmap_bearer(const char *bearer, char *userbuf, size_t buflen);
/* Authentication handlers */
static int jmap_authreq(struct transaction_t *txn);
static int jmap_authdel(struct transaction_t *txn);
static int jmap_settings(struct transaction_t *txn);
static int jmap_initreq(jmap_req_t *req);
static void jmap_finireq(jmap_req_t *req);
static int myrights(struct auth_state *authstate,
const mbentry_t *mbentry,
hash_table *mboxrights);
static int myrights_byname(struct auth_state *authstate,
const char *mboxname,
hash_table *mboxrights);
/* Namespace for JMAP */
struct namespace_t namespace_jmap = {
URL_NS_JMAP, 0, "jmap", "/jmap", "/.well-known/jmap",
jmap_checkurl, 1 << AUTH_BEARER,
/*mbtype*/0,
(ALLOW_READ | ALLOW_POST),
&jmap_init, &jmap_auth, NULL, NULL, NULL, &jmap_bearer,
{
{ NULL, NULL }, /* ACL */
{ NULL, NULL }, /* BIND */
{ NULL, NULL }, /* COPY */
{ &jmap_delete, NULL }, /* DELETE */
{ &jmap_get, NULL }, /* GET */
{ &jmap_get, NULL }, /* HEAD */
{ NULL, NULL }, /* LOCK */
{ NULL, NULL }, /* MKCALENDAR */
{ NULL, NULL }, /* MKCOL */
{ NULL, NULL }, /* MOVE */
{ &meth_options, NULL }, /* OPTIONS */
{ NULL, NULL }, /* PATCH */
{ &jmap_post, NULL }, /* POST */
{ NULL, NULL }, /* PROPFIND */
{ NULL, NULL }, /* PROPPATCH */
{ NULL, NULL }, /* PUT */
{ NULL, NULL }, /* REPORT */
{ &meth_trace, NULL }, /* TRACE */
{ NULL, NULL }, /* UNBIND */
{ NULL, NULL } /* UNLOCK */
}
};
static ptrarray_t messages = PTRARRAY_INITIALIZER;
static jmap_msg_t *find_message(const char *name)
{
jmap_msg_t *mp = NULL;
int i;
for (i = 0; i < messages.count; i++) {
mp = (jmap_msg_t*) ptrarray_nth(&messages, i);
if (!strcmp(mp->name, name)) {
break;
}
}
if (i == messages.count) {
mp = NULL;
}
return mp;
}
struct mymblist_rock {
mboxlist_cb *proc;
void *rock;
struct auth_state *authstate;
hash_table *mboxrights;
int all;
};
static int mymblist_cb(const mbentry_t *mbentry, void *rock)
{
struct mymblist_rock *myrock = rock;
if (!myrock->all) {
if (mbentry->mbtype & MBTYPE_DELETED)
return 0;
int rights = myrights(myrock->authstate, mbentry, myrock->mboxrights);
if (!(rights & ACL_LOOKUP))
return 0;
}
return myrock->proc(mbentry, myrock->rock);
}
static int mymblist(const char *userid,
const char *accountid,
struct auth_state *authstate,
hash_table *mboxrights,
mboxlist_cb *proc,
void *rock,
int all)
{
if (!strcmp(userid, accountid)) {
int flags = all ? (MBOXTREE_TOMBSTONES|MBOXTREE_DELETED) : 0;
return mboxlist_usermboxtree(userid, proc, rock, flags);
}
/* Open the INBOX first */
struct mymblist_rock myrock = { proc, rock, authstate, mboxrights, all };
struct buf buf = BUF_INITIALIZER;
buf_printf(&buf, "user%c%s", jmap_namespace.hier_sep, accountid);
mbentry_t *mbentry = NULL;
int r = mboxlist_lookup(buf_cstring(&buf), &mbentry, NULL);
if (r) goto done;
r = mymblist_cb(mbentry, &myrock);
if (r) goto done;
/* Visit any mailboxes underneath the INBOX */
buf_putc(&buf, jmap_namespace.hier_sep);
r = mboxlist_allmbox(buf_cstring(&buf), mymblist_cb, &myrock, all);
done:
mboxlist_entry_free(&mbentry);
buf_free(&buf);
return r;
}
EXPORTED int jmap_mboxlist(jmap_req_t *req, mboxlist_cb *proc, void *rock)
{
return mymblist(req->userid, req->accountid, req->authstate,
req->mboxrights, proc, rock, 0/*all*/);
}
EXPORTED int jmap_allmbox(jmap_req_t *req, mboxlist_cb *proc, void *rock)
{
return mymblist(req->userid, req->accountid, req->authstate,
req->mboxrights, proc, rock, 1/*all*/);
}
static void jmap_init(struct buf *serverinfo __attribute__((unused)))
{
namespace_jmap.enabled =
config_httpmodules & IMAP_ENUM_HTTPMODULES_JMAP;
if (config_jmapauth_allowsasl)
namespace_jmap.auth_schemes = ~0;
if (!namespace_jmap.enabled) return;
compile_time = calc_compile_time(__TIME__, __DATE__);
jmap_msg_t *mp;
for (mp = jmap_mail_messages; mp->name; mp++) {
ptrarray_append(&messages, mp);
}
for (mp = jmap_contact_messages; mp->name; mp++) {
ptrarray_append(&messages, mp);
}
for (mp = jmap_calendar_messages; mp->name; mp++) {
ptrarray_append(&messages, mp);
}
}
static void jmap_auth(const char *userid __attribute__((unused)))
{
/* Set namespace */
mboxname_init_namespace(&jmap_namespace,
httpd_userisadmin || httpd_userisproxyadmin);
}
/* Perform a DELETE request */
static int jmap_delete(struct transaction_t *txn,
void *params __attribute__((unused)))
{
if (!strcmp(txn->req_uri->path, "/jmap/auth/")) {
return jmap_authdel(txn);
}
return HTTP_NOT_ALLOWED;
}
/* Perform a GET/HEAD request */
static int jmap_get(struct transaction_t *txn,
void *params __attribute__((unused)))
{
if (!strncmp(txn->req_uri->path, "/jmap/download/", 15)) {
return jmap_download(txn);
}
if (!strcmp(txn->req_uri->path, "/jmap/auth/")) {
return jmap_settings(txn);
}
return HTTP_NOT_FOUND;
}
static int is_accessible(const mbentry_t *mbentry, void *rock __attribute__((unused)))
{
if ((mbentry->mbtype & MBTYPE_DELETED) ||
(mbentry->mbtype & MBTYPE_MOVING) ||
(mbentry->mbtype & MBTYPE_REMOTE) ||
(mbentry->mbtype & MBTYPE_RESERVE)) {
return 0;
}
return IMAP_OK_COMPLETED;
}
/* Perform a POST request */
static int jmap_post(struct transaction_t *txn,
void *params __attribute__((unused)))
{
const char **hdr;
json_t *req, *resp = NULL;
json_error_t jerr;
struct jmap_idmap idmap = {
HASH_TABLE_INITIALIZER,
HASH_TABLE_INITIALIZER,
HASH_TABLE_INITIALIZER,
HASH_TABLE_INITIALIZER,
HASH_TABLE_INITIALIZER,
HASH_TABLE_INITIALIZER
};
size_t i, flags = JSON_PRESERVE_ORDER;
int ret;
char *buf, *inboxname = NULL;
hash_table accounts = HASH_TABLE_INITIALIZER;
hash_table mboxrights = HASH_TABLE_INITIALIZER;
/* Read body */
txn->req_body.flags |= BODY_DECODE;
ret = http_read_body(httpd_in, httpd_out,
txn->req_hdrs, &txn->req_body, &txn->error.desc);
if (ret) {
txn->flags.conn = CONN_CLOSE;
return ret;
}
/* Handle uploads */
if (!strncmp(txn->req_uri->path, "/jmap/upload/", 13)) {
return jmap_upload(txn);
}
/* Handle POST to the authentication endpoint */
if (!strcmp(txn->req_uri->path, "/jmap/auth/")) {
return jmap_authreq(txn);
}
/* Must be a regular JMAP POST request */
/* Canonicalize URL */
if (!strcmp(txn->req_uri->path, "/jmap")) {
txn->location = "/jmap/";
return HTTP_MOVED;
}
if (strcmp(txn->req_uri->path, "/jmap/")) {
return HTTP_NOT_FOUND;
}
/* Check Content-Type */
if (!(hdr = spool_getheader(txn->req_hdrs, "Content-Type")) ||
!is_mediatype("application/json", hdr[0])) {
txn->error.desc = "This method requires a JSON request body";
return HTTP_BAD_MEDIATYPE;
}
if (!buf_len(&txn->req_body.payload)) return HTTP_BAD_REQUEST;
/* Allocate map to store uids */
construct_hash_table(&idmap.mailboxes, 64, 0);
construct_hash_table(&idmap.messages, 64, 0);
construct_hash_table(&idmap.calendars, 64, 0);
construct_hash_table(&idmap.calendarevents, 64, 0);
construct_hash_table(&idmap.contactgroups, 64, 0);
construct_hash_table(&idmap.contacts, 64, 0);
/* Parse the JSON request */
req = json_loads(buf_cstring(&txn->req_body.payload), 0, &jerr);
if (!req || !json_is_array(req)) {
txn->error.desc = "Unable to parse JSON request body";
ret = HTTP_BAD_REQUEST;
goto done;
}
/* Start JSON response */
resp = json_array();
if (!resp) {
txn->error.desc = "Unable to create JSON response body";
ret = HTTP_SERVER_ERROR;
goto done;
}
construct_hash_table(&accounts, 8, 0);
construct_hash_table(&mboxrights, 64, 0);
/* Process each message in the request */
for (i = 0; i < json_array_size(req); i++) {
const jmap_msg_t *mp;
json_t *msg = json_array_get(req, i);
const char *tag, *name = json_string_value(json_array_get(msg, 0));
json_t *args = json_array_get(msg, 1), *arg;
json_t *id = json_array_get(msg, 2);
int r = 0;
/* XXX - better error reporting */
if (!id) {
txn->error.desc = "Missing id on request";
ret = HTTP_BAD_REQUEST;
goto done;
}
tag = json_string_value(id);
/* Find the message processor */
if (!(mp = find_message(name))) {
json_array_append(resp, json_pack("[s {s:s} s]",
"error", "type", "unknownMethod", tag));
continue;
}
/* Determine account */
const char *accountid = httpd_userid;
arg = json_object_get(json_array_get(msg, 1), "accountId");
if (arg && arg != json_null()) {
if ((accountid = json_string_value(arg)) == NULL) {
json_t *err = json_pack("{s:s, s:[s]}",
"type", "invalidArguments", "arguments", "accountId");
json_array_append(resp, json_pack("[s,o,s]", "error", err, tag));
continue;
}
/* Check if any shared mailbox is accessible */
if (!hash_lookup(accountid, &accounts)) {
r = mymblist(httpd_userid, accountid, httpd_authstate, &mboxrights,
is_accessible, NULL, 0/*all*/);
if (r != IMAP_OK_COMPLETED) {
json_t *err = json_pack("{s:s}", "type", "accountNotFound");
json_array_append_new(resp, json_pack("[s,o,s]", "error", err, tag));
continue;
}
hash_insert(accountid, (void*)1, &accounts);
}
}
free(inboxname);
inboxname = mboxname_user_mbox(accountid, NULL);
struct conversations_state *cstate = NULL;
r = conversations_open_user(accountid, &cstate);
if (r) {
txn->error.desc = error_message(r);
ret = HTTP_SERVER_ERROR;
goto done;
}
struct jmap_req req;
req.userid = httpd_userid;
req.accountid = accountid;
req.inboxname = inboxname;
req.cstate = cstate;
req.authstate = httpd_authstate;
req.args = args;
req.response = resp;
req.tag = tag;
req.idmap = &idmap;
req.txn = txn;
req.mboxrights = &mboxrights;
req.is_shared_account = strcmp(accountid, httpd_userid);
/* Initialize request context */
jmap_initreq(&req);
/* Read the modseq counters again, just in case something changed. */
r = mboxname_read_counters(inboxname, &req.counters);
if (r) goto done;
/* Call the message processor. */
r = mp->proc(&req);
/* Finalize request context */
jmap_finireq(&req);
if (r) {
conversations_abort(&req.cstate);
txn->error.desc = error_message(r);
ret = HTTP_SERVER_ERROR;
goto done;
}
conversations_commit(&req.cstate);
}
/* Dump JSON object into a text buffer */
flags |= (config_httpprettytelemetry ? JSON_INDENT(2) : JSON_COMPACT);
buf = json_dumps(resp, flags);
if (!buf) {
txn->error.desc = "Error dumping JSON response object";
ret = HTTP_SERVER_ERROR;
goto done;
}
/* Output the JSON object */
txn->resp_body.type = "application/json; charset=utf-8";
write_body(HTTP_OK, txn, buf, strlen(buf));
free(buf);
done:
free_hash_table(&idmap.mailboxes, free);
free_hash_table(&idmap.messages, free);
free_hash_table(&idmap.calendars, free);
free_hash_table(&idmap.calendarevents, free);
free_hash_table(&idmap.contactgroups, free);
free_hash_table(&idmap.contacts, free);
free_hash_table(&accounts, NULL);
free_hash_table(&mboxrights, free);
free(inboxname);
if (req) json_decref(req);
if (resp) json_decref(resp);
return ret;
}
struct _mboxcache_rec {
struct mailbox *mbox;
int refcount;
int rw;
};
static int jmap_initreq(jmap_req_t *req)
{
req->mboxes = ptrarray_new();
return 0;
}
static void jmap_finireq(jmap_req_t *req)
{
assert(req->mboxes->count == 0);
ptrarray_free(req->mboxes);
req->mboxes = NULL;
}
EXPORTED int jmap_openmbox(jmap_req_t *req, const char *name, struct mailbox **mboxp, int rw)
{
int i, r;
struct _mboxcache_rec *rec;
for (i = 0; i < req->mboxes->count; i++) {
rec = (struct _mboxcache_rec*) ptrarray_nth(req->mboxes, i);
if (!strcmp(name, rec->mbox->name)) {
if (rw && !rec->rw) {
/* Lock promotions are not supported */
syslog(LOG_ERR, "jmapmbox: won't reopen mailbox %s", name);
return IMAP_INTERNAL;
}
rec->refcount++;
*mboxp = rec->mbox;
return 0;
}
}
r = rw ? mailbox_open_iwl(name, mboxp) : mailbox_open_irl(name, mboxp);
if (r) {
syslog(LOG_ERR, "jmap_openmbox(%s): %s", name, error_message(r));
return r;
}
rec = xzmalloc(sizeof(struct _mboxcache_rec));
rec->mbox = *mboxp;
rec->refcount = 1;
rec->rw = rw;
ptrarray_add(req->mboxes, rec);
return 0;
}
EXPORTED int jmap_isopenmbox(jmap_req_t *req, const char *name)
{
int i;
struct _mboxcache_rec *rec;
for (i = 0; i < req->mboxes->count; i++) {
rec = (struct _mboxcache_rec*) ptrarray_nth(req->mboxes, i);
if (!strcmp(name, rec->mbox->name))
return 1;
}
return 0;
}
EXPORTED void jmap_closembox(jmap_req_t *req, struct mailbox **mboxp)
{
struct _mboxcache_rec *rec = NULL;
int i;
for (i = 0; i < req->mboxes->count; i++) {
rec = (struct _mboxcache_rec*) ptrarray_nth(req->mboxes, i);
if (rec->mbox == *mboxp)
break;
}
assert(i < req->mboxes->count);
if (!(--rec->refcount)) {
ptrarray_remove(req->mboxes, i);
mailbox_close(&rec->mbox);
free(rec);
}
*mboxp = NULL;
}
EXPORTED char *jmap_blobid(const struct message_guid *guid)
{
char *blobid = xzmalloc(42);
blobid[0] = 'G';
memcpy(blobid+1, message_guid_encode(guid), 40);
return blobid;
}
struct findblob_data {
jmap_req_t *req;
struct mailbox *mbox;
msgrecord_t *mr;
char *part_id;
};
static int findblob_cb(const conv_guidrec_t *rec, void *rock)
{
struct findblob_data *d = (struct findblob_data*) rock;
jmap_req_t *req = d->req;
int r = 0;
r = jmap_openmbox(req, rec->mboxname, &d->mbox, 0);
if (r) return r;
r = msgrecord_find(d->mbox, rec->uid, &d->mr);
if (r) {
jmap_closembox(req, &d->mbox);
d->mr = NULL;
return r;
}
d->part_id = rec->part ? xstrdup(rec->part) : NULL;
return IMAP_OK_COMPLETED;
}
EXPORTED int jmap_findblob(jmap_req_t *req, const char *blobid,
struct mailbox **mbox, msgrecord_t **mr,
struct body **body, const struct body **part)
{
struct findblob_data data = { req, NULL, NULL, NULL };
struct body *mybody = NULL;
const struct body *mypart = NULL;
int i, r;
if (blobid[0] != 'G')
return IMAP_NOTFOUND;
r = conversations_guid_foreach(req->cstate, blobid+1, findblob_cb, &data);
if (r != IMAP_OK_COMPLETED) {
if (!r) r = IMAP_NOTFOUND;
goto done;
}
r = msgrecord_get_bodystructure(data.mr, &mybody);
if (r) goto done;
/* Find part containing the data */
if (data.part_id) {
ptrarray_t parts = PTRARRAY_INITIALIZER;
struct message_guid content_guid;
message_guid_decode(&content_guid, blobid+1);
ptrarray_push(&parts, mybody);
while ((mypart = ptrarray_shift(&parts))) {
if (!message_guid_cmp(&content_guid, &mypart->content_guid)) {
break;
}
if (!mypart->subpart) continue;
ptrarray_push(&parts, mypart->subpart);
for (i = 1; i < mypart->numparts; i++)
ptrarray_push(&parts, mypart->subpart + i);
}
ptrarray_fini(&parts);
if (!mypart) {
r = IMAP_NOTFOUND;
goto done;
}
}
*mbox = data.mbox;
*mr = data.mr;
*part = mypart;
*body = mybody;
r = 0;
done:
if (r) {
if (data.mbox) jmap_closembox(req, &data.mbox);
if (mybody) message_free_body(mybody);
}
if (data.part_id) free(data.part_id);
return r;
}
EXPORTED int jmap_download(struct transaction_t *txn)
{
if (strncmp(txn->req_uri->path, "/jmap/download/", 15))
return HTTP_NOT_FOUND;
const char *userid = txn->req_uri->path + 15;
const char *slash = strchr(userid, '/');
if (!slash) {
/* XXX - error, needs AccountId */
return HTTP_NOT_FOUND;
}
#if 0
size_t userlen = slash - userid;
/* invalid user? */
if (!strncmp(userid, httpd_userid, userlen)) {
txn->error.desc = "failed to match userid";
return HTTP_BAD_REQUEST;
}
#endif
const char *blobbase = slash + 1;
slash = strchr(blobbase, '/');
if (!slash) {
/* XXX - error, needs blobid */
txn->error.desc = "failed to find blobid";
return HTTP_BAD_REQUEST;
}
size_t bloblen = slash - blobbase;
if (*blobbase != 'G') {
txn->error.desc = "invalid blobid (doesn't start with G)";
return HTTP_BAD_REQUEST;
}
if (bloblen != 41) {
/* incomplete or incorrect blobid */
txn->error.desc = "invalid blobid (not 41 chars)";
return HTTP_BAD_REQUEST;
}
const char *name = slash + 1;
struct conversations_state *cstate = NULL;
int r = conversations_open_user(httpd_userid, &cstate);
if (r) {
txn->error.desc = error_message(r);
return HTTP_SERVER_ERROR;
}
/* now we're allocating memory, so don't return from here! */
char *inboxname = mboxname_user_mbox(httpd_userid, NULL);
struct jmap_req req;
req.userid = httpd_userid;
req.inboxname = inboxname;
req.cstate = cstate;
req.authstate = httpd_authstate;
req.args = NULL;
req.response = NULL;
req.tag = NULL;
req.idmap = NULL;
req.txn = txn;
jmap_initreq(&req);
char *blobid = xstrndup(blobbase, bloblen);
struct mailbox *mbox = NULL;
msgrecord_t *mr = NULL;
struct body *body = NULL;
const struct body *part = NULL;
struct buf msg_buf = BUF_INITIALIZER;
char *decbuf = NULL;
char *ctype = NULL;
strarray_t headers = STRARRAY_INITIALIZER;
int res = 0;
/* Find part containing blob */
r = jmap_findblob(&req, blobid, &mbox, &mr, &body, &part);
if (r) {
res = HTTP_NOT_FOUND; // XXX errors?
txn->error.desc = "failed to find blob by id";
goto done;
}
/* Map the message into memory */
r = msgrecord_get_body(mr, &msg_buf);
if (r) {
res = HTTP_NOT_FOUND; // XXX errors?
txn->error.desc = "failed to map record";
goto done;
}
// default with no part is the whole message
const char *base = msg_buf.s;
size_t len = msg_buf.len;
txn->resp_body.type = "message/rfc822";
if (part) {
// map into just this part
txn->resp_body.type = "application/octet-stream";
base += part->content_offset;
len = part->content_size;
// update content type header if present
strarray_add(&headers, "Content-Type");
ctype = xstrndup(msg_buf.s + part->header_offset, part->header_size);
message_pruneheader(ctype, &headers, NULL);
strarray_truncate(&headers, 0);
if (ctype) {
char *p = strchr(ctype, ':');
if (p) {
p++;
while (*p == ' ') p++;
char *end = strchr(p, '\n');
if (end) *end = '\0';
end = strchr(p, '\r');
if (end) *end = '\0';
}
if (p && *p) txn->resp_body.type = p;
}
// binary decode if needed
int encoding = part->charset_enc & 0xff;
base = charset_decode_mimebody(base, len, encoding, &decbuf, &len);
}
txn->resp_body.len = len;
txn->resp_body.fname = name;
write_body(HTTP_OK, txn, base, len);
done:
free(decbuf);
free(ctype);
strarray_fini(&headers);
if (mbox) jmap_closembox(&req, &mbox);
conversations_commit(&cstate);
if (body) {
message_free_body(body);
free(body);
}
if (mr) {
msgrecord_unref(&mr);
}
buf_free(&msg_buf);
free(blobid);
jmap_finireq(&req);
free(inboxname);
return res;
}
static int lookup_upload_collection(const char *accountid, mbentry_t **mbentry)
{
mbname_t *mbname;
const char *uploadname;
int r;
/* Create notification mailbox name from the parsed path */
mbname = mbname_from_userid(accountid);
mbname_push_boxes(mbname, config_getstring(IMAPOPT_JMAPUPLOADFOLDER));
/* XXX - hack to allow @domain parts for non-domain-split users */
if (httpd_extradomain) {
/* not allowed to be cross domain */
if (mbname_localpart(mbname) &&
strcmpsafe(mbname_domain(mbname), httpd_extradomain)) {
r = HTTP_NOT_FOUND;
goto done;
}
mbname_set_domain(mbname, NULL);
}
/* Locate the mailbox */
uploadname = mbname_intname(mbname);
r = http_mlookup(uploadname, mbentry, NULL);
if (r == IMAP_MAILBOX_NONEXISTENT) {
/* Find location of INBOX */
char *inboxname = mboxname_user_mbox(accountid, NULL);
int r1 = http_mlookup(inboxname, mbentry, NULL);
free(inboxname);
if (r1 == IMAP_MAILBOX_NONEXISTENT) {
r = IMAP_INVALID_USER;
goto done;
}
int rights = httpd_myrights(httpd_authstate, *mbentry);
if (!(rights & ACL_CREATE)) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
if (*mbentry) free((*mbentry)->name);
else *mbentry = mboxlist_entry_create();
(*mbentry)->name = xstrdup(uploadname);
}
else if (!r) {
int rights = httpd_myrights(httpd_authstate, *mbentry);
if (!(rights & ACL_INSERT)) {
r = IMAP_PERMISSION_DENIED;
goto done;
}
}
done:
mbname_free(&mbname);
return r;
}
static int create_upload_collection(const char *accountid, struct mailbox **mailbox)
{
/* notifications collection */
mbentry_t *mbentry = NULL;
int r = lookup_upload_collection(accountid, &mbentry);
if (r == IMAP_INVALID_USER) {
goto done;
}
else if (r == IMAP_PERMISSION_DENIED) {
goto done;
}
else if (r == IMAP_MAILBOX_NONEXISTENT) {
if (!mbentry) goto done;
else if (mbentry->server) {
proxy_findserver(mbentry->server, &http_protocol, httpd_userid,
&backend_cached, NULL, NULL, httpd_in);
goto done;
}
r = mboxlist_createmailbox(mbentry->name, MBTYPE_COLLECTION,
NULL, 1 /* admin */, accountid, NULL,
0, 0, 0, 0, mailbox);
/* we lost the race, that's OK */
if (r == IMAP_MAILBOX_LOCKED) r = 0;
if (r) syslog(LOG_ERR, "IOERROR: failed to create %s (%s)",
mbentry->name, error_message(r));
}
else if (mailbox) {
/* Open mailbox for writing */
r = mailbox_open_iwl(mbentry->name, mailbox);
if (r) {
syslog(LOG_ERR, "mailbox_open_iwl(%s) failed: %s",
mbentry->name, error_message(r));
}
}
done:
mboxlist_entry_free(&mbentry);
return r;
}
/* Helper function to determine domain of data */
enum {
DOMAIN_7BIT = 0,
DOMAIN_8BIT,
DOMAIN_BINARY
};
static int data_domain(const char *p, size_t n)
{
int r = DOMAIN_7BIT;
while (n--) {
if (!*p) return DOMAIN_BINARY;
if (*p & 0x80) r = DOMAIN_8BIT;
p++;
}
return r;
}
EXPORTED int jmap_upload(struct transaction_t *txn)
{
strarray_t flags = STRARRAY_INITIALIZER;
strarray_append(&flags, "\\Deleted");
strarray_append(&flags, "\\Expunged"); // custom flag to insta-expunge!
struct body *body = NULL;
const char *data = buf_base(&txn->req_body.payload);
size_t datalen = buf_len(&txn->req_body.payload);
int ret = HTTP_CREATED;
hdrcache_t hdrcache = txn->req_hdrs;
struct stagemsg *stage = NULL;
FILE *f = NULL;
const char **hdr;
time_t now = time(NULL);
struct appendstate as;
struct mailbox *mailbox = NULL;
int r = 0;
const char *accountid = httpd_userid;
if ((hdr = spool_getheader(hdrcache, "X-JMAP-AccountId"))) {
accountid = hdr[0];
}
r = create_upload_collection(accountid, &mailbox);
if (r) {
syslog(LOG_ERR, "create_upload_collection: %s", error_message(r));
ret = HTTP_BAD_REQUEST;
goto done;
}
json_t *resp = json_pack("{s:s}", "accountId", accountid);
/* Prepare to stage the message */