Progress on upload
[citadel.git] / webcit-ng / server / upload.c
1 // Upload handler
2 //
3 // Copyright (c) 1996-2023 by the citadel.org team
4 //
5 // This program is open source software.  Use, duplication, or
6 // disclosure are subject to the GNU General Public License v3.
7
8 #include "webcit.h"
9
10 Array *upload_list = NULL;                                      // all files uploaded to this webcit instance
11 pthread_mutex_t upload_list_mutex = PTHREAD_MUTEX_INITIALIZER;  // Lock it before modifying
12
13
14 // This function is called by the MIME parser to handle data uploaded by the browser.
15 void upload_handler(char *name, char *filename, char *partnum, char *disp,
16                     void *content, char *cbtype, char *cbcharset,
17                     size_t length, char *encoding, char *cbid, void *userdata)
18 {
19         syslog(LOG_DEBUG, "upload_handler()");
20         syslog(LOG_DEBUG, "        name: %s", name);
21         syslog(LOG_DEBUG, "    filename: %s", filename);
22         syslog(LOG_DEBUG, " part number: %s", partnum);
23         syslog(LOG_DEBUG, " disposition: %s", disp);
24         syslog(LOG_DEBUG, "content type: %s", cbtype);
25         syslog(LOG_DEBUG, "    char set: %s", cbcharset);
26         syslog(LOG_DEBUG, "      length: %ld", length);
27         syslog(LOG_DEBUG, "    encoding: %s", encoding);
28         syslog(LOG_DEBUG, "          id: %s", cbid);
29
30         struct uploaded_file u;
31
32         // create a random ID for the attachment
33         for (int i=0; i<sizeof(u.id); ++i) {
34                 u.id[i] = (rand() % 26) + 'a';
35         }
36         u.id[sizeof(u.id)-1] = 0;
37
38         safestrncpy(u.filename, filename, sizeof(u.filename));
39         safestrncpy(u.content_type, cbtype, sizeof(u.content_type));
40         u.length = length;
41
42         // Write the upload to a file that we can access later when the user saves the message.
43         // tmpfile() creates a file with zero links in the directory, so it will be deleted when it is closed.
44         u.fp = tmpfile();
45         if (!u.fp) {
46                 syslog(LOG_ERR, "upload: %m");
47                 return;
48         }
49         if (fwrite(content, length, 1, u.fp) != 1) {
50                 syslog(LOG_ERR, "upload: %m");
51                 fclose(u.fp);
52                 return;
53         }
54
55         // Add it to the list of uploads the server is holding.
56         pthread_mutex_lock(&upload_list_mutex);
57         if (upload_list == NULL) {
58                 upload_list = array_new(sizeof(struct uploaded_file));
59         }
60         array_append(upload_list, &u);
61         pthread_mutex_unlock(&upload_list_mutex);
62
63         for (int i=0; i<array_len(upload_list); ++i) {
64                 memcpy(&u, array_get_element_at(upload_list, i), sizeof(struct uploaded_file));
65                 syslog(LOG_DEBUG, "%d: %s %s", i, u.id, u.filename);
66         }
67
68         // Create a JSON object describing this upload
69         JsonValue *j_one_upload = NewJsonObject(HKEY(""));
70         JsonObjectAppend(j_one_upload, NewJsonPlainString(HKEY("ref"), u.id, -1));
71         JsonObjectAppend(j_one_upload, NewJsonPlainString(HKEY("uploadfilename"), u.filename, -1));
72         JsonObjectAppend(j_one_upload, NewJsonPlainString(HKEY("contenttype"), u.content_type, -1));
73         JsonObjectAppend(j_one_upload, NewJsonNumber(HKEY("contentlength"), u.length));
74
75         // ...and attach it to the array of uploads
76         JsonValue *j_uploads = (JsonValue *) userdata;
77         JsonArrayAppend(j_uploads, j_one_upload);
78 }
79
80 // upload handler
81 void upload_files(struct http_transaction *h, struct ctdlsession *c) {
82         // FIXME reject uploads if we're not logged in
83
84         // This will be a JSON Array of all files that were uploaded during this HTTP transaction.
85         // Normally the browser will upload only one file per transaction, but that behavior is not guaranteed.
86         JsonValue *j_uploads = NewJsonArray(HKEY(""));
87
88         // h->request_body will contain the upload(s) in MIME format
89         mime_parser(h->request_body, (h->request_body + h->request_body_length), *upload_handler, NULL, NULL, j_uploads, 0);
90
91         // probably do something more clever here
92         h->response_code = 200;
93         h->response_string = strdup("OK");
94
95         // send back a JSON array of all files uploaded
96         StrBuf *sj = NewStrBuf();
97         SerializeJson(sj, j_uploads, 1);        // '1' == free the source object
98         add_response_header(h, strdup("Content-type"), strdup("application/json"));
99         h->response_code = 200;
100         h->response_string = strdup("OK");
101         h->response_body_length = StrLength(sj);
102         h->response_body = SmashStrBuf(&sj);
103 }
104
105
106 // Caller has requested /ctdl/p or /ctdl/p/ but we still have to dispatch based on the method
107 void ctdl_p_base(struct http_transaction *h, struct ctdlsession *c) {
108         upload_files(h, c);             // we should only do this for POST requests
109 }
110
111
112 // delete an uploaded item
113 void delete_upload(struct uploaded_file this_one) {
114         int i;
115         struct uploaded_file *u;
116
117         pthread_mutex_lock(&upload_list_mutex);
118         for (i=0; i<array_len(upload_list); ++i) {
119                 u = (struct uploaded_file *) array_get_element_at(upload_list, i), sizeof(struct uploaded_file);
120                 if (!strcmp(u->id, this_one.id)) {
121                         fclose(u->fp);                          // this deletes the file because it has 0 links
122                         array_delete_element_at(upload_list, i);
123                         i = array_len(upload_list) + 1;         // Go out of scope; we're done here
124                 }
125         }
126         pthread_mutex_unlock(&upload_list_mutex);
127 }
128
129
130 // DAV delete an uploaded item
131 void dav_delete_upload(struct http_transaction *h, struct ctdlsession *c, struct uploaded_file this_one) {
132         delete_upload(this_one);
133         do_204(h);
134 }
135
136
137 // Remove an uploaded item from the upload_list.  Caller now owns the file handle and is responsible for closing it.
138 struct uploaded_file pop_upload(char *id) {
139         int i;
140         struct uploaded_file *u;
141         struct uploaded_file ret;
142
143         memset(&ret, 0, sizeof(struct uploaded_file));
144
145         pthread_mutex_lock(&upload_list_mutex);
146         for (i=0; i<array_len(upload_list); ++i) {
147                 u = (struct uploaded_file *) array_get_element_at(upload_list, i), sizeof(struct uploaded_file);
148                 if (!strcmp(u->id, id)) {
149                         ret = *u;
150                         array_delete_element_at(upload_list, i);
151                         i = array_len(upload_list) + 1;         // Go out of scope; we're done here
152                 }
153         }
154         pthread_mutex_unlock(&upload_list_mutex);
155
156         return(ret);                                            // ret will be all-zeroes if we didn't find it
157 }
158
159
160 // Handle operations on a specific upload
161 void specific_upload(struct http_transaction *h, struct ctdlsession *c, char *name) {
162         int i;
163         struct uploaded_file *u;
164         struct uploaded_file this_one;
165
166         if (upload_list == NULL) {
167                 do_404(h);
168                 return;
169         }
170
171         memset(&this_one, 0, sizeof(struct uploaded_file));
172         pthread_mutex_lock(&upload_list_mutex);
173         for (i=0; i<array_len(upload_list); ++i) {
174                 u = (struct uploaded_file *) array_get_element_at(upload_list, i), sizeof(struct uploaded_file);
175                 if (!strcmp(u->id, name)) {
176                         memcpy(&this_one, u, sizeof(struct uploaded_file));
177                         i = array_len(upload_list) + 1;         // Go out of scope; we're done here
178                 }
179         }
180         pthread_mutex_unlock(&upload_list_mutex);
181
182         // If we found a matching ID, now dispatch based on the HTTP method.
183
184         if (IsEmptyStr(this_one.id)) {                          // didn't find a match
185                 do_404(h);
186         }
187         else if (!strcasecmp(h->method, "GET")) {               // fetch the item
188                 do_405(h);
189         }
190         else if (!strcasecmp(h->method, "DELETE")) {            // delete the item
191                 dav_delete_upload(h, c, this_one);
192         }
193         else {                                                  // unsupported method
194                 do_405(h);
195         }
196 }
197
198
199 // Dispatcher for paths starting with /ctdl/p/
200 void ctdl_p(struct http_transaction *h, struct ctdlsession *c) {
201         char buf[SIZ];
202
203         if (num_tokens(h->url, '/') == 3) {     //      /ctdl/p
204                 ctdl_p_base(h, c);
205                 return;
206         }
207
208         extract_token(buf, h->url, 3, '/', sizeof buf);
209         if (num_tokens(h->url, '/') == 4) {
210                 if (IsEmptyStr(buf)) {
211                         ctdl_p_base(h, c);      //      /ctdl/p/
212                 }
213                 else {
214                         specific_upload(h, c, &h->url[8]);
215                 }
216                 return;
217         }
218
219         // If we get to this point, the client requested an action we don't know how to perform.
220         do_404(h);
221 }