• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

processone / ejabberd / 1293

15 Jan 2026 07:25PM UTC coverage: 33.083% (+23.2%) from 9.847%
1293

push

github

badlop
mod_http_upload: Pass ServerHost, not Host which may be "upload.HOST"

0 of 2 new or added lines in 1 file covered. (0.0%)

2 existing lines in 1 file now uncovered.

15358 of 46422 relevant lines covered (33.08%)

828.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

47.62
/src/mod_http_upload.erl
1
%%%----------------------------------------------------------------------
2
%%% File    : mod_http_upload.erl
3
%%% Author  : Holger Weiss <holger@zedat.fu-berlin.de>
4
%%% Purpose : HTTP File Upload (XEP-0363)
5
%%% Created : 20 Aug 2015 by Holger Weiss <holger@zedat.fu-berlin.de>
6
%%%
7
%%%
8
%%% ejabberd, Copyright (C) 2015-2026   ProcessOne
9
%%%
10
%%% This program is free software; you can redistribute it and/or
11
%%% modify it under the terms of the GNU General Public License as
12
%%% published by the Free Software Foundation; either version 2 of the
13
%%% License, or (at your option) any later version.
14
%%%
15
%%% This program is distributed in the hope that it will be useful,
16
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
17
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
%%% General Public License for more details.
19
%%%
20
%%% You should have received a copy of the GNU General Public License along
21
%%% with this program; if not, write to the Free Software Foundation, Inc.,
22
%%% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
%%%
24
%%%----------------------------------------------------------------------
25

26
-module(mod_http_upload).
27
-author('holger@zedat.fu-berlin.de').
28
-behaviour(gen_server).
29
-behaviour(gen_mod).
30
-protocol({xep, 363, '0.3.0', '15.10', "complete", ""}).
31

32
-define(SERVICE_REQUEST_TIMEOUT, 5000). % 5 seconds.
33
-define(CALL_TIMEOUT, 60000). % 1 minute.
34
-define(SLOT_TIMEOUT, timer:hours(5)).
35
-define(DEFAULT_CONTENT_TYPE, <<"application/octet-stream">>).
36

37
%% gen_mod/supervisor callbacks.
38
-export([start/2,
39
         stop/1,
40
         reload/3,
41
         depends/2,
42
         mod_doc/0,
43
         mod_opt_type/1,
44
         mod_options/1]).
45

46
%% gen_server callbacks.
47
-export([init/1,
48
         handle_call/3,
49
         handle_cast/2,
50
         handle_info/2,
51
         terminate/2,
52
         code_change/3]).
53

54
%% ejabberd_http callback.
55
-export([process/2]).
56

57
%% ejabberd_hooks callback.
58
-export([remove_user/2]).
59

60
%% Utility functions.
61
-export([get_proc_name/2,
62
         expand_home/1,
63
         expand_host/2]).
64

65
-include("ejabberd_http.hrl").
66
-include_lib("xmpp/include/xmpp.hrl").
67
-include("logger.hrl").
68
-include("translate.hrl").
69

70
-record(state,
71
        {server_host = <<>>     :: binary(),
72
         hosts = []             :: [binary()],
73
         name = <<>>            :: binary(),
74
         access = none          :: atom(),
75
         max_size = infinity    :: pos_integer() | infinity,
76
         secret_length = 40     :: pos_integer(),
77
         jid_in_url = sha1      :: sha1 | node,
78
         file_mode              :: integer() | undefined,
79
         dir_mode               :: integer() | undefined,
80
         docroot = <<>>         :: binary(),
81
         put_url = <<>>         :: binary(),
82
         get_url = <<>>         :: binary(),
83
         service_url            :: binary() | undefined,
84
         thumbnail = false      :: boolean(),
85
         custom_headers = []    :: [{binary(), binary()}],
86
         slots = #{}            :: slots(),
87
         external_secret = <<>> :: binary()}).
88

89
-record(media_info,
90
        {path   :: binary(),
91
         type   :: atom(),
92
         height :: integer(),
93
         width  :: integer()}).
94

95
-type state() :: #state{}.
96
-type slot() :: [binary(), ...].
97
-type slots() :: #{slot() => {pos_integer(), reference()}}.
98
-type media_info() :: #media_info{}.
99

100
%%--------------------------------------------------------------------
101
%% gen_mod/supervisor callbacks.
102
%%--------------------------------------------------------------------
103
-spec start(binary(), gen_mod:opts()) -> {ok, pid()} | {error, term()}.
104
start(ServerHost, Opts) ->
105
    Proc = get_proc_name(ServerHost, ?MODULE),
90✔
106
    case gen_mod:start_child(?MODULE, ServerHost, Opts, Proc) of
90✔
107
        {ok, _} = Ret -> Ret;
90✔
108
        {error, {already_started, _}} = Err ->
109
            ?ERROR_MSG("Multiple virtual hosts can't use a single 'put_url' "
×
110
                       "without the @HOST@ keyword", []),
×
111
            Err;
×
112
        Err ->
113
            Err
×
114
    end.
115

116
-spec stop(binary()) -> ok | {error, any()}.
117
stop(ServerHost) ->
118
    Proc = get_proc_name(ServerHost, ?MODULE),
90✔
119
    gen_mod:stop_child(Proc).
90✔
120

121
-spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok | {ok, pid()} | {error, term()}.
122
reload(ServerHost, NewOpts, OldOpts) ->
123
    NewURL = mod_http_upload_opt:put_url(NewOpts),
×
124
    OldURL = mod_http_upload_opt:put_url(OldOpts),
×
125
    OldProc = get_proc_name(ServerHost, ?MODULE, OldURL),
×
126
    NewProc = get_proc_name(ServerHost, ?MODULE, NewURL),
×
127
    if OldProc /= NewProc ->
×
128
            gen_mod:stop_child(OldProc),
×
129
            start(ServerHost, NewOpts);
×
130
       true ->
131
            gen_server:cast(NewProc, {reload, NewOpts, OldOpts})
×
132
    end.
133

134
-spec mod_opt_type(atom()) -> econf:validator().
135
mod_opt_type(name) ->
136
    econf:binary();
108✔
137
mod_opt_type(access) ->
138
    econf:acl();
108✔
139
mod_opt_type(max_size) ->
140
    econf:pos_int(infinity);
108✔
141
mod_opt_type(secret_length) ->
142
    econf:int(8, 1000);
108✔
143
mod_opt_type(jid_in_url) ->
144
    econf:enum([sha1, node]);
108✔
145
mod_opt_type(file_mode) ->
146
    econf:octal();
108✔
147
mod_opt_type(dir_mode) ->
148
    econf:octal();
108✔
149
mod_opt_type(docroot) ->
150
    econf:binary();
108✔
151
mod_opt_type(put_url) ->
152
    econf:url();
108✔
153
mod_opt_type(get_url) ->
154
    econf:url();
108✔
155
mod_opt_type(service_url) ->
156
    econf:url();
108✔
157
mod_opt_type(content_types) ->
158
    econf:map(econf:binary(), econf:binary());
108✔
159
mod_opt_type(custom_headers) ->
160
    econf:map(econf:binary(), econf:binary());
108✔
161
mod_opt_type(rm_on_unregister) ->
162
    econf:bool();
108✔
163
mod_opt_type(thumbnail) ->
164
    econf:and_then(
108✔
165
      econf:bool(),
166
      fun(true) ->
167
              case eimp:supported_formats() of
×
168
                  [] -> econf:fail(eimp_error);
×
169
                  [_|_] -> true
×
170
              end;
171
         (false) ->
172
              false
×
173
      end);
174
mod_opt_type(external_secret) ->
175
    econf:binary();
108✔
176
mod_opt_type(host) ->
177
    econf:host();
108✔
178
mod_opt_type(hosts) ->
179
    econf:hosts();
108✔
180
mod_opt_type(vcard) ->
181
    econf:vcard_temp().
108✔
182

183
-spec mod_options(binary()) -> [{thumbnail, boolean()} |
184
                                {atom(), any()}].
185
mod_options(Host) ->
186
    [{host, <<"upload.", Host/binary>>},
108✔
187
     {hosts, []},
188
     {name, ?T("HTTP File Upload")},
189
     {vcard, undefined},
190
     {access, local},
191
     {max_size, 104857600},
192
     {secret_length, 40},
193
     {jid_in_url, sha1},
194
     {file_mode, undefined},
195
     {dir_mode, undefined},
196
     {docroot, <<"@HOME@/upload">>},
197
     {put_url, <<"https://", Host/binary, ":5443/upload">>},
198
     {get_url, undefined},
199
     {service_url, undefined},
200
     {external_secret, <<"">>},
201
     {content_types, []},
202
     {custom_headers, []},
203
     {rm_on_unregister, true},
204
     {thumbnail, false}].
205

206
mod_doc() ->
207
    #{desc =>
×
208
          [?T("This module allows for requesting permissions to "
209
              "upload a file via HTTP as described in "
210
              "https://xmpp.org/extensions/xep-0363.html"
211
              "[XEP-0363: HTTP File Upload]. If the request is accepted, "
212
              "the client receives a URL for uploading the file and "
213
              "another URL from which that file can later be downloaded."), "",
214
           ?T("In order to use this module, it must be enabled "
215
              "in 'listen' -> 'ejabberd_http' -> "
216
              "_`listen-options.md#request_handlers|request_handlers`_.")],
217
      note => "added 'content_types' in 26.xx",
218
      opts =>
219
          [{host,
220
            #{desc => ?T("Deprecated. Use 'hosts' instead.")}},
221
           {hosts,
222
            #{value => ?T("[Host, ...]"),
223
              desc =>
224
                  ?T("This option defines the Jabber IDs of the service. "
225
                     "If the 'hosts' option is not specified, the only Jabber ID will "
226
                     "be the hostname of the virtual host with the prefix '\"upload.\"'. "
227
                     "The keyword '@HOST@' is replaced with the real virtual host name.")}},
228
           {name,
229
            #{value => ?T("Name"),
230
              desc =>
231
                  ?T("A name of the service in the Service Discovery. "
232
                     "The default value is '\"HTTP File Upload\"'. "
233
                     "Please note this will only be displayed by some XMPP clients.")}},
234
           {access,
235
            #{value => ?T("AccessName"),
236
              desc =>
237
                  ?T("This option defines the access rule to limit who is "
238
                     "permitted to use the HTTP upload service. "
239
                     "The default value is 'local'. If no access rule of "
240
                     "that name exists, no user will be allowed to use the service.")}},
241
           {max_size,
242
            #{value => ?T("Size"),
243
              desc =>
244
                  ?T("This option limits the acceptable file size. "
245
                     "Either a number of bytes (larger than zero) or "
246
                     "'infinity' must be specified. "
247
                     "The default value is '104857600'.")}},
248
           {secret_length,
249
            #{value => ?T("Length"),
250
              desc =>
251
                  ?T("This option defines the length of the random "
252
                     "string included in the GET and PUT URLs generated "
253
                     "by 'mod_http_upload'. The minimum length is '8' characters, "
254
                     "but it is recommended to choose a larger value. "
255
                     "The default value is '40'.")}},
256
           {jid_in_url,
257
            #{value => "node | sha1",
258
              desc =>
259
                  ?T("When this option is set to 'node', the node identifier "
260
                     "of the user's JID (i.e., the user name) is included in "
261
                     "the GET and PUT URLs generated by 'mod_http_upload'. "
262
                     "Otherwise, a SHA-1 hash of the user's bare JID is "
263
                     "included instead. The default value is 'sha1'.")}},
264
           {thumbnail,
265
            #{value => "true | false",
266
              desc =>
267
                  ?T("This option specifies whether ejabberd should create "
268
                     "thumbnails of uploaded images. If a thumbnail is created, "
269
                     "a <thumbnail/> element that contains the download <uri/> "
270
                     "and some metadata is returned with the PUT response. "
271
                     "The default value is 'false'.")}},
272
           {file_mode,
273
            #{value => ?T("Permission"),
274
              desc =>
275
                  ?T("This option defines the permission bits of uploaded files. "
276
                     "The bits are specified as an octal number (see the 'chmod(1)' "
277
                     "manual page) within double quotes. For example: '\"0644\"'. "
278
                     "The default is undefined, which means no explicit permissions "
279
                     "will be set.")}},
280
           {dir_mode,
281
            #{value => ?T("Permission"),
282
              desc =>
283
                  ?T("This option defines the permission bits of the 'docroot' "
284
                     "directory and any directories created during file uploads. "
285
                     "The bits are specified as an octal number (see the 'chmod(1)' "
286
                     "manual page) within double quotes. For example: '\"0755\"'. "
287
                     "The default is undefined, which means no explicit permissions "
288
                     "will be set.")}},
289
           {docroot,
290
            #{value => ?T("Path"),
291
              desc =>
292
                  ?T("Uploaded files are stored below the directory specified "
293
                       "(as an absolute path) with this option. The keyword "
294
                     "'@HOME@' is replaced with the home directory of the user "
295
                     "running ejabberd, and the keyword '@HOST@' with the virtual "
296
                     "host name. The default value is '\"@HOME@/upload\"'.")}},
297
           {put_url,
298
            #{value => ?T("URL"),
299
              desc =>
300
                  ?T("This option specifies the initial part of the PUT URLs "
301
                     "used for file uploads. The keyword '@HOST@' is replaced "
302
                     "with the virtual host name. "
303
                     "And '@HOST_URL_ENCODE@' is replaced with the host name encoded for URL, "
304
                     "useful when your virtual hosts contain non-latin characters. "
305
                     "NOTE: different virtual hosts cannot use the same PUT URL. "
306
                     "The default value is '\"https://@HOST@:5443/upload\"'.")}},
307
           {get_url,
308
            #{value => ?T("URL"),
309
              desc =>
310
                  ?T("This option specifies the initial part of the GET URLs "
311
                     "used for downloading the files. The default value is 'undefined'. "
312
                     "When this option is 'undefined', this option is set "
313
                     "to the same value as 'put_url'. The keyword '@HOST@' is "
314
                     "replaced with the virtual host name. NOTE: if GET requests "
315
                     "are handled by this module, the 'get_url' must match the "
316
                     "'put_url'. Setting it to a different value only makes "
317
                     "sense if an external web server or _`mod_http_fileserver`_ "
318
                     "is used to serve the uploaded files.")}},
319
           {service_url,
320
            #{desc => ?T("Deprecated.")}},
321
           {content_types,
322
            #{value => "{Extension: Type}",
323
              note => "added in 26.xx",
324
              desc =>
325
                  ?T("Specify mappings of extension to content type, similarly to "
326
                     "the option `content_types` of _`mod_http_fileserver`_.")}},
327
           {custom_headers,
328
            #{value => "{Name: Value}",
329
              desc =>
330
                  ?T("This option specifies additional header fields to be "
331
                     "included in all HTTP responses. By default no custom "
332
                     "headers are included.")}},
333
           {external_secret,
334
            #{value => ?T("Text"),
335
              desc =>
336
                  ?T("This option makes it possible to offload all HTTP "
337
                     "Upload processing to a separate HTTP server. "
338
                     "Both ejabberd and the HTTP server should share this "
339
                     "secret and behave exactly as described at "
340
                     "https://modules.prosody.im/mod_http_upload_external.html#implementation"
341
                     "[Prosody's mod_http_upload_external: Implementation]. "
342
                     "There is no default value.")}},
343
           {rm_on_unregister,
344
            #{value => "true | false",
345
              desc =>
346
                  ?T("This option specifies whether files uploaded by a user "
347
                     "should be removed when that user is unregistered. "
348
                     "The default value is 'true'.")}},
349
           {vcard,
350
            #{value => ?T("vCard"),
351
              desc =>
352
                  ?T("A custom vCard of the service that will be displayed "
353
                     "by some XMPP clients in Service Discovery. The value of "
354
                     "'vCard' is a YAML map constructed from an XML representation "
355
                     "of vCard. Since the representation has no attributes, "
356
                     "the mapping is straightforward."),
357
              example =>
358
                  ["# This XML representation of vCard:",
359
                   "#   <vCard xmlns='vcard-temp'>",
360
                   "#     <FN>Conferences</FN>",
361
                   "#     <ADR>",
362
                   "#       <WORK/>",
363
                   "#       <STREET>Elm Street</STREET>",
364
                   "#     </ADR>",
365
                   "#   </vCard>",
366
                   "# ",
367
                   "# is translated to:",
368
                   "vcard:",
369
                   "  fn: Conferences",
370
                   "  adr:",
371
                   "    -",
372
                   "      work: true",
373
                   "      street: Elm Street"]}}],
374
      example =>
375
          ["listen:",
376
           "  -",
377
           "    port: 5443",
378
           "    module: ejabberd_http",
379
           "    tls: true",
380
           "    request_handlers:",
381
           "      /upload: mod_http_upload",
382
           "",
383
           "modules:",
384
           "  mod_http_upload:",
385
           "    docroot: /ejabberd/upload",
386
           "    put_url: \"https://@HOST@:5443/upload\""]}.
387

388
-spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}].
389
depends(_Host, _Opts) ->
390
    [].
108✔
391

392
%%--------------------------------------------------------------------
393
%% gen_server callbacks.
394
%%--------------------------------------------------------------------
395
-spec init(list()) -> {ok, state()}.
396
init([ServerHost|_]) ->
397
    process_flag(trap_exit, true),
90✔
398
    Opts = gen_mod:get_module_opts(ServerHost, ?MODULE),
90✔
399
    Hosts = gen_mod:get_opt_hosts(Opts),
90✔
400
    case mod_http_upload_opt:rm_on_unregister(Opts) of
90✔
401
        true ->
402
            ejabberd_hooks:add(remove_user, ServerHost, ?MODULE,
90✔
403
                               remove_user, 50);
404
        false ->
405
            ok
×
406
    end,
407
    State = init_state(ServerHost, Hosts, Opts),
90✔
408
    {ok, State}.
90✔
409

410
-spec handle_call(_, {pid(), _}, state())
411
      -> {reply, {ok, pos_integer(), binary(),
412
                      pos_integer() | undefined,
413
                      pos_integer() | undefined}, state()} |
414
         {reply, {error, atom()}, state()} | {noreply, state()}.
415
handle_call({use_slot, Slot, Size}, _From,
416
            #state{file_mode = FileMode,
417
                   dir_mode = DirMode,
418
                   get_url = GetPrefix,
419
                   thumbnail = Thumbnail,
420
                   custom_headers = CustomHeaders,
421
                   docroot = DocRoot} = State) ->
422
    case get_slot(Slot, State) of
3✔
423
        {ok, {Size, TRef}} ->
424
            misc:cancel_timer(TRef),
3✔
425
            NewState = del_slot(Slot, State),
3✔
426
            Path = str:join([DocRoot | Slot], <<$/>>),
3✔
427
            {reply,
3✔
428
             {ok, Path, FileMode, DirMode, GetPrefix, Thumbnail, CustomHeaders},
429
             NewState};
430
        {ok, {_WrongSize, _TRef}} ->
431
            {reply, {error, size_mismatch}, State};
×
432
        error ->
433
            {reply, {error, invalid_slot}, State}
×
434
    end;
435
handle_call(get_conf, _From,
436
            #state{docroot = DocRoot,
437
                   server_host = ServerHost,
438
                   custom_headers = CustomHeaders} = State) ->
NEW
439
    {reply, {ok, DocRoot, ServerHost, CustomHeaders}, State};
3✔
440
handle_call(Request, From, State) ->
441
    ?WARNING_MSG("Unexpected call from ~p: ~p", [From, Request]),
×
442
    {noreply, State}.
×
443

444
-spec handle_cast(_, state()) -> {noreply, state()}.
445
handle_cast({reload, NewOpts, OldOpts},
446
            #state{server_host = ServerHost} = State) ->
447
    case {mod_http_upload_opt:rm_on_unregister(NewOpts),
×
448
          mod_http_upload_opt:rm_on_unregister(OldOpts)} of
449
        {true, false} ->
450
            ejabberd_hooks:add(remove_user, ServerHost, ?MODULE,
×
451
                               remove_user, 50);
452
        {false, true} ->
453
            ejabberd_hooks:delete(remove_user, ServerHost, ?MODULE,
×
454
                                  remove_user, 50);
455
        _ ->
456
            ok
×
457
    end,
458
    NewHosts = gen_mod:get_opt_hosts(NewOpts),
×
459
    OldHosts = gen_mod:get_opt_hosts(OldOpts),
×
460
    lists:foreach(fun ejabberd_router:unregister_route/1, OldHosts -- NewHosts),
×
461
    NewState = init_state(State#state{hosts = NewHosts -- OldHosts}, NewOpts),
×
462
    {noreply, NewState};
×
463
handle_cast(Request, State) ->
464
    ?WARNING_MSG("Unexpected cast: ~p", [Request]),
×
465
    {noreply, State}.
×
466

467
-spec handle_info(timeout | _, state()) -> {noreply, state()}.
468
handle_info({route, #iq{lang = Lang} = Packet}, State) ->
469
    try xmpp:decode_els(Packet) of
17✔
470
        IQ ->
471
            {Reply, NewState} = case process_iq(IQ, State) of
17✔
472
                                    R when is_record(R, iq) ->
473
                                        {R, State};
11✔
474
                                    {R, S} ->
475
                                        {R, S};
6✔
476
                                    not_request ->
477
                                        {none, State}
×
478
                                end,
479
            if Reply /= none ->
17✔
480
                    ejabberd_router:route(Reply);
17✔
481
               true ->
482
                    ok
×
483
            end,
484
            {noreply, NewState}
17✔
485
    catch _:{xmpp_codec, Why} ->
486
            Txt = xmpp:io_format_error(Why),
×
487
            Err = xmpp:err_bad_request(Txt, Lang),
×
488
            ejabberd_router:route_error(Packet, Err),
×
489
            {noreply, State}
×
490
    end;
491
handle_info({timeout, _TRef, Slot}, State) ->
492
    NewState = del_slot(Slot, State),
×
493
    {noreply, NewState};
×
494
handle_info(Info, State) ->
495
    ?WARNING_MSG("Unexpected info: ~p", [Info]),
×
496
    {noreply, State}.
×
497

498
-spec terminate(normal | shutdown | {shutdown, _} | _, state()) -> ok.
499
terminate(Reason, #state{server_host = ServerHost, hosts = Hosts}) ->
500
    ?DEBUG("Stopping HTTP upload process for ~ts: ~p", [ServerHost, Reason]),
90✔
501
    ejabberd_hooks:delete(remove_user, ServerHost, ?MODULE, remove_user, 50),
90✔
502
    lists:foreach(fun ejabberd_router:unregister_route/1, Hosts).
90✔
503

504
-spec code_change({down, _} | _, state(), _) -> {ok, state()}.
505
code_change(_OldVsn, #state{server_host = ServerHost} = State, _Extra) ->
506
    ?DEBUG("Updating HTTP upload process for ~ts", [ServerHost]),
×
507
    {ok, State}.
×
508

509
%%--------------------------------------------------------------------
510
%% ejabberd_http callback.
511
%%--------------------------------------------------------------------
512
-spec process([binary()], #request{})
513
      -> {pos_integer(), [{binary(), binary()}], binary()}.
514
process(LocalPath, #request{method = Method, host = Host, ip = IP})
515
    when length(LocalPath) < 3,
516
         Method == 'PUT' orelse
517
         Method == 'GET' orelse
518
         Method == 'HEAD' ->
519
    ?DEBUG("Rejecting ~ts request from ~ts for ~ts: Too few path components",
×
520
           [Method, encode_addr(IP), Host]),
×
521
    http_response(404);
×
522
process(_LocalPath, #request{method = 'PUT', host = Host, ip = IP,
523
                             length = Length} = Request0) ->
524
    Request = Request0#request{host = redecode_url(Host)},
3✔
525
    {Proc, Slot} = parse_http_request(Request),
3✔
526
    try gen_server:call(Proc, {use_slot, Slot, Length}, ?CALL_TIMEOUT) of
3✔
527
        {ok, Path, FileMode, DirMode, GetPrefix, Thumbnail, CustomHeaders} ->
528
            ?DEBUG("Storing file from ~ts for ~ts: ~ts",
3✔
529
                   [encode_addr(IP), Host, Path]),
3✔
530
            case store_file(Path, Request, FileMode, DirMode,
3✔
531
                            GetPrefix, Slot, Thumbnail) of
532
                ok ->
533
                    http_response(201, CustomHeaders);
3✔
534
                {ok, Headers, OutData} ->
535
                    http_response(201, ejabberd_http:apply_custom_headers(Headers, CustomHeaders), OutData);
×
536
                {error, closed} ->
537
                    ?DEBUG("Cannot store file ~ts from ~ts for ~ts: connection closed",
×
538
                           [Path, encode_addr(IP), Host]),
×
539
                    http_response(404);
×
540
                {error, Error} ->
541
                    ?ERROR_MSG("Cannot store file ~ts from ~ts for ~ts: ~ts",
×
542
                               [Path, encode_addr(IP), Host, format_error(Error)]),
×
543
                    http_response(500)
×
544
            end;
545
        {error, size_mismatch} ->
546
            ?WARNING_MSG("Rejecting file ~ts from ~ts for ~ts: Unexpected size (~B)",
×
547
                      [lists:last(Slot), encode_addr(IP), Host, Length]),
×
548
            http_response(413);
×
549
        {error, invalid_slot} ->
550
            ?WARNING_MSG("Rejecting file ~ts from ~ts for ~ts: Invalid slot",
×
551
                      [lists:last(Slot), encode_addr(IP), Host]),
×
552
            http_response(403)
×
553
    catch
554
        exit:{noproc, _} ->
555
            ?WARNING_MSG("Cannot handle PUT request from ~ts for ~ts: "
×
556
                         "Upload not configured for this host",
557
                         [encode_addr(IP), Host]),
×
558
            http_response(404);
×
559
        _:Error ->
560
            ?ERROR_MSG("Cannot handle PUT request from ~ts for ~ts: ~p",
×
561
                       [encode_addr(IP), Host, Error]),
×
562
            http_response(500)
×
563
    end;
564
process(_LocalPath, #request{method = Method, host = Host, ip = IP} = Request0)
565
    when Method == 'GET';
566
         Method == 'HEAD' ->
567
    Request = Request0#request{host = redecode_url(Host)},
3✔
568
    {Proc, [_UserDir, _RandDir, FileName] = Slot} = parse_http_request(Request),
3✔
569
    try gen_server:call(Proc, get_conf, ?CALL_TIMEOUT) of
3✔
570
        {ok, DocRoot, ServerHost, CustomHeaders} ->
571
            Path = str:join([DocRoot | Slot], <<$/>>),
3✔
572
            case file:open(Path, [read]) of
3✔
573
                {ok, Fd} ->
574
                    file:close(Fd),
3✔
575
                    ?INFO_MSG("Serving ~ts to ~ts", [Path, encode_addr(IP)]),
3✔
NEW
576
                    ContentType = get_content_type(ServerHost, FileName),
3✔
577
                    Headers1 = case ContentType of
3✔
578
                                 <<"image/", _SubType/binary>> -> [];
3✔
579
                                 <<"text/", _SubType/binary>> -> [];
×
580
                                 _ ->
581
                                     [{<<"Content-Disposition">>,
×
582
                                       <<"attachment; filename=",
583
                                         $", FileName/binary, $">>}]
584
                               end,
585
                    Headers2 = [{<<"Content-Type">>, ContentType} | Headers1],
3✔
586
                    Headers3 = ejabberd_http:apply_custom_headers(Headers2, CustomHeaders),
3✔
587
                    http_response(200, Headers3, {file, Path});
3✔
588
                {error, eacces} ->
589
                    ?WARNING_MSG("Cannot serve ~ts to ~ts: Permission denied",
×
590
                              [Path, encode_addr(IP)]),
×
591
                    http_response(403);
×
592
                {error, enoent} ->
593
                    ?WARNING_MSG("Cannot serve ~ts to ~ts: No such file",
×
594
                              [Path, encode_addr(IP)]),
×
595
                    http_response(404);
×
596
                {error, eisdir} ->
597
                    ?WARNING_MSG("Cannot serve ~ts to ~ts: Is a directory",
×
598
                              [Path, encode_addr(IP)]),
×
599
                    http_response(404);
×
600
                {error, Error} ->
601
                    ?WARNING_MSG("Cannot serve ~ts to ~ts: ~ts",
×
602
                              [Path, encode_addr(IP), format_error(Error)]),
×
603
                    http_response(500)
×
604
            end
605
    catch
606
        exit:{noproc, _} ->
607
            ?WARNING_MSG("Cannot handle ~ts request from ~ts for ~ts: "
×
608
                         "Upload not configured for this host",
609
                         [Method, encode_addr(IP), Host]),
×
610
            http_response(404);
×
611
        _:Error ->
612
            ?ERROR_MSG("Cannot handle ~ts request from ~ts for ~ts: ~p",
×
613
                       [Method, encode_addr(IP), Host, Error]),
×
614
            http_response(500)
×
615
    end;
616
process(_LocalPath, #request{method = 'OPTIONS', host = Host,
617
                             ip = IP} = Request) ->
618
    ?DEBUG("Responding to OPTIONS request from ~ts for ~ts",
×
619
           [encode_addr(IP), Host]),
×
620
    {Proc, _Slot} = parse_http_request(Request),
×
621
    try gen_server:call(Proc, get_conf, ?CALL_TIMEOUT) of
×
622
        {ok, _DocRoot, _ServerHost, CustomHeaders} ->
623
            AllowHeader = {<<"Allow">>, <<"OPTIONS, HEAD, GET, PUT">>},
×
624
            http_response(200, ejabberd_http:apply_custom_headers([AllowHeader], CustomHeaders))
×
625
    catch
626
        exit:{noproc, _} ->
627
            ?WARNING_MSG("Cannot handle OPTIONS request from ~ts for ~ts: "
×
628
                         "Upload not configured for this host",
629
                         [encode_addr(IP), Host]),
×
630
            http_response(404);
×
631
        _:Error ->
632
            ?ERROR_MSG("Cannot handle OPTIONS request from ~ts for ~ts: ~p",
×
633
                       [encode_addr(IP), Host, Error]),
×
634
            http_response(500)
×
635
    end;
636
process(_LocalPath, #request{method = Method, host = Host, ip = IP}) ->
637
    ?DEBUG("Rejecting ~ts request from ~ts for ~ts",
×
638
           [Method, encode_addr(IP), Host]),
×
639
    http_response(405, [{<<"Allow">>, <<"OPTIONS, HEAD, GET, PUT">>}]).
×
640

641
%%--------------------------------------------------------------------
642
%% State initialization
643
%%--------------------------------------------------------------------
644
-spec init_state(binary(), [binary()], gen_mod:opts()) -> state().
645
init_state(ServerHost, Hosts, Opts) ->
646
    init_state(#state{server_host = ServerHost, hosts = Hosts}, Opts).
90✔
647

648
-spec init_state(state(), gen_mod:opts()) -> state().
649
init_state(#state{server_host = ServerHost, hosts = Hosts} = State, Opts) ->
650
    Name = mod_http_upload_opt:name(Opts),
90✔
651
    Access = mod_http_upload_opt:access(Opts),
90✔
652
    MaxSize = mod_http_upload_opt:max_size(Opts),
90✔
653
    SecretLength = mod_http_upload_opt:secret_length(Opts),
90✔
654
    JIDinURL = mod_http_upload_opt:jid_in_url(Opts),
90✔
655
    DocRoot = mod_http_upload_opt:docroot(Opts),
90✔
656
    FileMode = mod_http_upload_opt:file_mode(Opts),
90✔
657
    DirMode = mod_http_upload_opt:dir_mode(Opts),
90✔
658
    PutURL = mod_http_upload_opt:put_url(Opts),
90✔
659
    GetURL = case mod_http_upload_opt:get_url(Opts) of
90✔
660
                 undefined -> PutURL;
×
661
                 URL -> URL
90✔
662
             end,
663
    ServiceURL = mod_http_upload_opt:service_url(Opts),
90✔
664
    Thumbnail = mod_http_upload_opt:thumbnail(Opts),
90✔
665
    ExternalSecret = mod_http_upload_opt:external_secret(Opts),
90✔
666
    CustomHeaders = mod_http_upload_opt:custom_headers(Opts),
90✔
667
    DocRoot1 = expand_home(str:strip(DocRoot, right, $/)),
90✔
668
    DocRoot2 = expand_host(DocRoot1, ServerHost),
90✔
669
    case DirMode of
90✔
670
        undefined ->
671
            ok;
90✔
672
        Mode ->
673
            file:change_mode(DocRoot2, Mode)
×
674
    end,
675
    lists:foreach(
90✔
676
      fun(Host) ->
677
              ejabberd_router:register_route(Host, ServerHost)
90✔
678
      end, Hosts),
679
    State#state{server_host = ServerHost, hosts = Hosts, name = Name,
90✔
680
                access = Access, max_size = MaxSize,
681
                secret_length = SecretLength, jid_in_url = JIDinURL,
682
                file_mode = FileMode, dir_mode = DirMode,
683
                thumbnail = Thumbnail,
684
                docroot = DocRoot2,
685
                put_url = expand_host(str:strip(PutURL, right, $/), ServerHost),
686
                get_url = expand_host(str:strip(GetURL, right, $/), ServerHost),
687
                service_url = ServiceURL,
688
                external_secret = ExternalSecret,
689
                custom_headers = CustomHeaders}.
690

691
%%--------------------------------------------------------------------
692
%% Exported utility functions.
693
%%--------------------------------------------------------------------
694
-spec get_proc_name(binary(), atom()) -> atom().
695
get_proc_name(ServerHost, ModuleName) ->
696
    PutURL = mod_http_upload_opt:put_url(ServerHost),
180✔
697
    get_proc_name(ServerHost, ModuleName, PutURL).
180✔
698

699
-spec get_proc_name(binary(), atom(), binary()) -> atom().
700
get_proc_name(ServerHost, ModuleName, PutURL) ->
701
    %% Once we depend on OTP >= 20.0, we can use binaries with http_uri.
702
    {ok, _Scheme, _UserInfo, Host0, _Port, Path0, _Query} =
180✔
703
        misc:uri_parse(expand_host(PutURL, ServerHost)),
704
    Host = jid:nameprep(iolist_to_binary(Host0)),
180✔
705
    Path = str:strip(iolist_to_binary(Path0), right, $/),
180✔
706
    ProcPrefix = <<Host/binary, Path/binary>>,
180✔
707
    gen_mod:get_module_proc(ProcPrefix, ModuleName).
180✔
708

709
-spec expand_home(binary()) -> binary().
710
expand_home(Input) ->
711
    Home = misc:get_home(),
91✔
712
    misc:expand_keyword(<<"@HOME@">>, Input, Home).
91✔
713

714
-spec expand_host(binary(), binary()) -> binary().
715
expand_host(Input, Host) ->
716
    misc:expand_keyword(<<"@HOST@">>, Input, Host).
451✔
717

718
%%--------------------------------------------------------------------
719
%% Internal functions.
720
%%--------------------------------------------------------------------
721

722
%% XMPP request handling.
723

724
-spec process_iq(iq(), state()) -> {iq(), state()} | iq() | not_request.
725
process_iq(#iq{type = get, lang = Lang, sub_els = [#disco_info{}]} = IQ,
726
           #state{server_host = ServerHost, name = Name}) ->
727
    AddInfo = ejabberd_hooks:run_fold(disco_info, ServerHost, [],
7✔
728
                                      [ServerHost, ?MODULE, <<"">>, <<"">>]),
729
    xmpp:make_iq_result(IQ, iq_disco_info(ServerHost, Lang, Name, AddInfo));
7✔
730
process_iq(#iq{type = get, sub_els = [#disco_items{}]} = IQ, _State) ->
731
    xmpp:make_iq_result(IQ, #disco_items{});
×
732
process_iq(#iq{type = get, sub_els = [#vcard_temp{}], lang = Lang} = IQ,
733
           #state{server_host = ServerHost}) ->
734
    VCard = case mod_http_upload_opt:vcard(ServerHost) of
1✔
735
                undefined ->
736
                    #vcard_temp{fn = <<"ejabberd/mod_http_upload">>,
×
737
                                url = ejabberd_config:get_uri(),
738
                                desc = misc:get_descr(
739
                                         Lang, ?T("ejabberd HTTP Upload service"))};
740
                V ->
741
                    V
1✔
742
            end,
743
    xmpp:make_iq_result(IQ, VCard);
1✔
744
process_iq(#iq{type = get, sub_els = [#upload_request{filename = File,
745
                                                      size = Size,
746
                                                      'content-type' = CType,
747
                                                      xmlns = XMLNS}]} = IQ,
748
           State) ->
749
    process_slot_request(IQ, File, Size, CType, XMLNS, State);
6✔
750
process_iq(#iq{type = get, sub_els = [#upload_request_0{filename = File,
751
                                                        size = Size,
752
                                                        'content-type' = CType,
753
                                                        xmlns = XMLNS}]} = IQ,
754
           State) ->
755
    process_slot_request(IQ, File, Size, CType, XMLNS, State);
3✔
756
process_iq(#iq{type = T, lang = Lang} = IQ, _State) when T == get; T == set ->
757
    Txt = ?T("No module is handling this query"),
×
758
    xmpp:make_error(IQ, xmpp:err_service_unavailable(Txt, Lang));
×
759
process_iq(#iq{}, _State) ->
760
    not_request.
×
761

762
-spec process_slot_request(iq(), binary(), pos_integer(), binary(), binary(),
763
                           state()) -> {iq(), state()} | iq().
764
process_slot_request(#iq{lang = Lang, from = From} = IQ,
765
                     File, Size, CType, XMLNS,
766
                     #state{server_host = ServerHost,
767
                            access = Access} = State) ->
768
    case acl:match_rule(ServerHost, Access, From) of
9✔
769
        allow ->
770
            ContentType = yield_content_type(CType),
9✔
771
            case create_slot(State, From, File, Size, ContentType, XMLNS,
9✔
772
                             Lang) of
773
                {ok, Slot} ->
774
                    Query = make_query_string(Slot, Size, State),
6✔
775
                    NewState = add_slot(Slot, Size, State),
6✔
776
                    NewSlot = mk_slot(Slot, State, XMLNS, Query),
6✔
777
                    {xmpp:make_iq_result(IQ, NewSlot), NewState};
6✔
778
                {ok, PutURL, GetURL} ->
779
                    Slot = mk_slot(PutURL, GetURL, XMLNS, <<"">>),
×
780
                    xmpp:make_iq_result(IQ, Slot);
×
781
                {error, Error} ->
782
                    xmpp:make_error(IQ, Error)
3✔
783
            end;
784
        deny ->
785
            ?DEBUG("Denying HTTP upload slot request from ~ts",
×
786
                   [jid:encode(From)]),
×
787
            Txt = ?T("Access denied by service policy"),
×
788
            xmpp:make_error(IQ, xmpp:err_forbidden(Txt, Lang))
×
789
    end.
790

791
-spec create_slot(state(), jid(), binary(), pos_integer(), binary(), binary(),
792
                  binary())
793
      -> {ok, slot()} | {ok, binary(), binary()} | {error, xmpp_element()}.
794
create_slot(#state{service_url = undefined, max_size = MaxSize},
795
            JID, File, Size, _ContentType, XMLNS, Lang)
796
  when MaxSize /= infinity,
797
       Size > MaxSize ->
798
    Text = {?T("File larger than ~w bytes"), [MaxSize]},
3✔
799
    ?WARNING_MSG("Rejecting file ~ts from ~ts (too large: ~B bytes)",
3✔
800
              [File, jid:encode(JID), Size]),
3✔
801
    Error = xmpp:err_not_acceptable(Text, Lang),
3✔
802
    Els = xmpp:get_els(Error),
3✔
803
    Els1 = [#upload_file_too_large{'max-file-size' = MaxSize,
3✔
804
                                   xmlns = XMLNS} | Els],
805
    Error1 = xmpp:set_els(Error, Els1),
3✔
806
    {error, Error1};
3✔
807
create_slot(#state{service_url = undefined,
808
                   jid_in_url = JIDinURL,
809
                   secret_length = SecretLength,
810
                   server_host = ServerHost,
811
                   docroot = DocRoot},
812
            JID, File, Size, _ContentType, _XMLNS, Lang) ->
813
    UserStr = make_user_string(JID, JIDinURL),
6✔
814
    UserDir = <<DocRoot/binary, $/, UserStr/binary>>,
6✔
815
    case ejabberd_hooks:run_fold(http_upload_slot_request, ServerHost, allow,
6✔
816
                                 [ServerHost, JID, UserDir, Size, Lang]) of
817
        allow ->
818
            RandStr = p1_rand:get_alphanum_string(SecretLength),
6✔
819
            FileStr = make_file_string(File),
6✔
820
            ?INFO_MSG("Got HTTP upload slot for ~ts (file: ~ts, size: ~B)",
6✔
821
                      [jid:encode(JID), File, Size]),
6✔
822
            {ok, [UserStr, RandStr, FileStr]};
6✔
823
        deny ->
824
            {error, xmpp:err_service_unavailable()};
×
825
        #stanza_error{} = Error ->
826
            {error, Error}
×
827
    end;
828
create_slot(#state{service_url = ServiceURL},
829
            #jid{luser = U, lserver = S} = JID,
830
            File, Size, ContentType, _XMLNS, Lang) ->
831
    Options = [{body_format, binary}, {full_result, false}],
×
832
    HttpOptions = [{timeout, ?SERVICE_REQUEST_TIMEOUT}],
×
833
    SizeStr = integer_to_binary(Size),
×
834
    JidStr = jid:encode({U, S, <<"">>}),
×
835
    GetRequest = <<ServiceURL/binary,
×
836
                   "?jid=", (misc:url_encode(JidStr))/binary,
837
                   "&name=", (misc:url_encode(File))/binary,
838
                   "&size=", (misc:url_encode(SizeStr))/binary,
839
                   "&content_type=", (misc:url_encode(ContentType))/binary>>,
840
    case httpc:request(get, {binary_to_list(GetRequest), []},
×
841
                       HttpOptions, Options) of
842
        {ok, {Code, Body}} when Code >= 200, Code =< 299 ->
843
            case binary:split(Body, <<$\n>>, [global, trim]) of
×
844
                [<<"http", _/binary>> = PutURL,
845
                 <<"http", _/binary>> = GetURL] ->
846
                    ?INFO_MSG("Got HTTP upload slot for ~ts (file: ~ts, size: ~B)",
×
847
                              [jid:encode(JID), File, Size]),
×
848
                    {ok, PutURL, GetURL};
×
849
                Lines ->
850
                    ?ERROR_MSG("Can't parse data received for ~ts from <~ts>: ~p",
×
851
                               [jid:encode(JID), ServiceURL, Lines]),
×
852
                    Txt = ?T("Failed to parse HTTP response"),
×
853
                    {error, xmpp:err_service_unavailable(Txt, Lang)}
×
854
            end;
855
        {ok, {402, _Body}} ->
856
            ?WARNING_MSG("Got status code 402 for ~ts from <~ts>",
×
857
                      [jid:encode(JID), ServiceURL]),
×
858
            {error, xmpp:err_resource_constraint()};
×
859
        {ok, {403, _Body}} ->
860
            ?WARNING_MSG("Got status code 403 for ~ts from <~ts>",
×
861
                      [jid:encode(JID), ServiceURL]),
×
862
            {error, xmpp:err_not_allowed()};
×
863
        {ok, {413, _Body}} ->
864
            ?WARNING_MSG("Got status code 413 for ~ts from <~ts>",
×
865
                      [jid:encode(JID), ServiceURL]),
×
866
            {error, xmpp:err_not_acceptable()};
×
867
        {ok, {Code, _Body}} ->
868
            ?ERROR_MSG("Unexpected status code for ~ts from <~ts>: ~B",
×
869
                       [jid:encode(JID), ServiceURL, Code]),
×
870
            {error, xmpp:err_service_unavailable()};
×
871
        {error, Reason} ->
872
            ?ERROR_MSG("Error requesting upload slot for ~ts from <~ts>: ~p",
×
873
                       [jid:encode(JID), ServiceURL, Reason]),
×
874
            {error, xmpp:err_service_unavailable()}
×
875
    end.
876

877
-spec add_slot(slot(), pos_integer(), state()) -> state().
878
add_slot(Slot, Size, #state{external_secret = <<>>, slots = Slots} = State) ->
879
    TRef = erlang:start_timer(?SLOT_TIMEOUT, self(), Slot),
6✔
880
    NewSlots = maps:put(Slot, {Size, TRef}, Slots),
6✔
881
    State#state{slots = NewSlots};
6✔
882
add_slot(_Slot, _Size, State) ->
883
    State.
×
884

885
-spec get_slot(slot(), state()) -> {ok, {pos_integer(), reference()}} | error.
886
get_slot(Slot, #state{slots = Slots}) ->
887
    maps:find(Slot, Slots).
3✔
888

889
-spec del_slot(slot(), state()) -> state().
890
del_slot(Slot, #state{slots = Slots} = State) ->
891
    NewSlots = maps:remove(Slot, Slots),
3✔
892
    State#state{slots = NewSlots}.
3✔
893

894
-spec mk_slot(slot(), state(), binary(), binary()) -> upload_slot();
895
             (binary(), binary(), binary(), binary()) -> upload_slot().
896
mk_slot(Slot, #state{put_url = PutPrefix, get_url = GetPrefix}, XMLNS, Query) ->
897
    PutURL = str:join([PutPrefix | Slot], <<$/>>),
6✔
898
    GetURL = str:join([GetPrefix | Slot], <<$/>>),
6✔
899
    mk_slot(PutURL, GetURL, XMLNS, Query);
6✔
900
mk_slot(PutURL, GetURL, XMLNS, Query) ->
901
    PutURL1 = <<(reencode_url(PutURL))/binary, Query/binary>>,
6✔
902
    GetURL1 = reencode_url(GetURL),
6✔
903
    case XMLNS of
6✔
904
        ?NS_HTTP_UPLOAD_0 ->
905
            #upload_slot_0{get = GetURL1, put = PutURL1, xmlns = XMLNS};
2✔
906
        _ ->
907
            #upload_slot{get = GetURL1, put = PutURL1, xmlns = XMLNS}
4✔
908
    end.
909

910
reencode_url(UrlString) ->
911
    {ok, _, _, Host, _, _, _} = yconf:parse_uri(misc:url_encode(UrlString)),
12✔
912
    HostDecoded = uri_string:percent_decode(Host),
12✔
913
    HostIdna = idna:encode(uri_string:percent_decode(HostDecoded)),
12✔
914
    re:replace(UrlString, HostDecoded, HostIdna, [{return, binary}]).
12✔
915

916
redecode_url(UrlString) ->
917
    {ok, _, _, HostIdna, _, _, _} = yconf:parse_uri(<<"http://", UrlString/binary>>),
6✔
918
    HostDecoded = idna:decode(HostIdna),
6✔
919
    Host = uri_string:quote(HostDecoded),
6✔
920
    re:replace(UrlString, HostIdna, Host, [{return, binary}]).
6✔
921

922
-spec make_user_string(jid(), sha1 | node) -> binary().
923
make_user_string(#jid{luser = U, lserver = S}, sha1) ->
924
    str:sha(<<U/binary, $@, S/binary>>);
7✔
925
make_user_string(#jid{luser = U}, node) ->
926
    replace_special_chars(U).
×
927

928
-spec make_file_string(binary()) -> binary().
929
make_file_string(File) ->
930
    replace_special_chars(File).
6✔
931

932
-spec make_query_string(slot(), non_neg_integer(), state()) -> binary().
933
make_query_string(Slot, Size, #state{external_secret = Key}) when Key /= <<>> ->
934
    UrlPath = str:join(Slot, <<$/>>),
×
935
    SizeStr = integer_to_binary(Size),
×
936
    Data = <<UrlPath/binary, " ", SizeStr/binary>>,
×
937
    HMAC = str:to_hexlist(crypto:mac(hmac, sha256, Key, Data)),
×
938
    <<"?v=", HMAC/binary>>;
×
939
make_query_string(_Slot, _Size, _State) ->
940
    <<>>.
6✔
941

942
-spec replace_special_chars(binary()) -> binary().
943
replace_special_chars(S) ->
944
    re:replace(S, <<"[^\\p{Xan}_.-]">>, <<$_>>,
6✔
945
               [unicode, global, {return, binary}]).
946

947
-spec yield_content_type(binary()) -> binary().
948
yield_content_type(<<"">>) -> ?DEFAULT_CONTENT_TYPE;
×
949
yield_content_type(Type) -> Type.
9✔
950

951
-spec encode_addr(inet:ip_address() | {inet:ip_address(), inet:port_number()} |
952
                  undefined) -> binary().
953
encode_addr(IP) ->
954
    ejabberd_config:may_hide_data(misc:ip_to_list(IP)).
3✔
955

956
-spec iq_disco_info(binary(), binary(), binary(), [xdata()]) -> disco_info().
957
iq_disco_info(Host, Lang, Name, AddInfo) ->
958
    Form = case mod_http_upload_opt:max_size(Host) of
7✔
959
               infinity ->
960
                   AddInfo;
×
961
               MaxSize ->
962
                   lists:foldl(
7✔
963
                     fun(NS, Acc) ->
964
                             Fs = http_upload:encode(
14✔
965
                                    [{'max-file-size', MaxSize}], NS, Lang),
966
                             [#xdata{type = result, fields = Fs}|Acc]
14✔
967
                     end, AddInfo, [?NS_HTTP_UPLOAD_0, ?NS_HTTP_UPLOAD])
968
           end,
969
    #disco_info{identities = [#identity{category = <<"store">>,
7✔
970
                                        type = <<"file">>,
971
                                        name = translate:translate(Lang, Name)}],
972
                features = [?NS_HTTP_UPLOAD,
973
                            ?NS_HTTP_UPLOAD_0,
974
                            ?NS_HTTP_UPLOAD_OLD,
975
                            ?NS_VCARD,
976
                            ?NS_DISCO_INFO,
977
                            ?NS_DISCO_ITEMS],
978
                xdata = Form}.
979

980
%% HTTP request handling.
981

982
-spec parse_http_request(#request{}) -> {atom(), slot()}.
983
parse_http_request(#request{host = Host0, path = Path}) ->
984
    Host = jid:nameprep(Host0),
6✔
985
    PrefixLength = length(Path) - 3,
6✔
986
    {ProcURL, Slot} = if PrefixLength > 0 ->
6✔
987
                              Prefix = lists:sublist(Path, PrefixLength),
6✔
988
                              {str:join([Host | Prefix], $/),
6✔
989
                               lists:nthtail(PrefixLength, Path)};
990
                         true ->
991
                              {Host, Path}
×
992
                      end,
993
    {gen_mod:get_module_proc(ProcURL, ?MODULE), Slot}.
6✔
994

995
-spec store_file(binary(), http_request(),
996
                 integer() | undefined,
997
                 integer() | undefined,
998
                 binary(), slot(), boolean())
999
      -> ok | {ok, [{binary(), binary()}], binary()} | {error, term()}.
1000
store_file(Path, Request, FileMode, DirMode, GetPrefix, Slot, Thumbnail) ->
1001
    case do_store_file(Path, Request, FileMode, DirMode) of
3✔
1002
        ok when Thumbnail ->
1003
            case read_image(Path) of
×
1004
                {ok, Data, MediaInfo} ->
1005
                    case convert(Data, MediaInfo) of
×
1006
                        {ok, #media_info{path = OutPath} = OutMediaInfo} ->
1007
                            [UserDir, RandDir | _] = Slot,
×
1008
                            FileName = filename:basename(OutPath),
×
1009
                            URL = str:join([GetPrefix, UserDir,
×
1010
                                            RandDir, FileName], <<$/>>),
1011
                            ThumbEl = thumb_el(OutMediaInfo, URL),
×
1012
                            {ok,
×
1013
                             [{<<"Content-Type">>,
1014
                               <<"text/xml; charset=utf-8">>}],
1015
                             fxml:element_to_binary(ThumbEl)};
1016
                        pass ->
1017
                            ok
×
1018
                    end;
1019
                pass ->
1020
                    ok
×
1021
            end;
1022
        ok ->
1023
            ok;
3✔
1024
        Err ->
1025
            Err
×
1026
    end.
1027

1028
-spec do_store_file(file:filename_all(), http_request(),
1029
                    integer() | undefined,
1030
                    integer() | undefined)
1031
      -> ok | {error, term()}.
1032
do_store_file(Path, Request, FileMode, DirMode) ->
1033
    try
3✔
1034
        ok = filelib:ensure_dir(Path),
3✔
1035
        ok = ejabberd_http:recv_file(Request, Path),
3✔
1036
        if is_integer(FileMode) ->
3✔
1037
                ok = file:change_mode(Path, FileMode);
×
1038
           FileMode == undefined ->
1039
                ok
3✔
1040
        end,
1041
        if is_integer(DirMode) ->
3✔
1042
                RandDir = filename:dirname(Path),
×
1043
                UserDir = filename:dirname(RandDir),
×
1044
                ok = file:change_mode(RandDir, DirMode),
×
1045
                ok = file:change_mode(UserDir, DirMode);
×
1046
           DirMode == undefined ->
1047
                ok
3✔
1048
        end
1049
    catch
1050
        _:{badmatch, {error, Error}} ->
1051
            {error, Error}
×
1052
    end.
1053

1054
-spec get_content_type(binary(), binary()) -> binary().
1055
get_content_type(Host, FileName) ->
1056
    OptionCTs = mod_http_upload_opt:content_types(Host),
3✔
1057
    ContentTypes = mod_http_fileserver:build_list_content_types(OptionCTs),
3✔
1058
    mod_http_fileserver:content_type(FileName,
3✔
1059
                                     ?DEFAULT_CONTENT_TYPE,
1060
                                     ContentTypes).
1061

1062
-spec http_response(100..599)
1063
      -> {pos_integer(), [{binary(), binary()}], binary()}.
1064
http_response(Code) ->
1065
    http_response(Code, []).
×
1066

1067
-spec http_response(100..599, [{binary(), binary()}])
1068
      -> {pos_integer(), [{binary(), binary()}], binary()}.
1069
http_response(Code, ExtraHeaders) ->
1070
    Message = <<(code_to_message(Code))/binary, $\n>>,
3✔
1071
    http_response(Code, ExtraHeaders, Message).
3✔
1072

1073
-type http_body() :: binary() | {file, file:filename_all()}.
1074
-spec http_response(100..599, [{binary(), binary()}], http_body())
1075
      -> {pos_integer(), [{binary(), binary()}], http_body()}.
1076
http_response(Code, ExtraHeaders, Body) ->
1077
    Headers = case proplists:is_defined(<<"Content-Type">>, ExtraHeaders) of
6✔
1078
                  true ->
1079
                      ExtraHeaders;
3✔
1080
                  false ->
1081
                      [{<<"Content-Type">>, <<"text/plain">>} | ExtraHeaders]
3✔
1082
              end,
1083
    {Code, Headers, Body}.
6✔
1084

1085
-spec code_to_message(100..599) -> binary().
1086
code_to_message(201) -> <<"Upload successful.">>;
3✔
1087
code_to_message(403) -> <<"Forbidden.">>;
×
1088
code_to_message(404) -> <<"Not found.">>;
×
1089
code_to_message(405) -> <<"Method not allowed.">>;
×
1090
code_to_message(413) -> <<"File size doesn't match requested size.">>;
×
1091
code_to_message(500) -> <<"Internal server error.">>;
×
1092
code_to_message(_Code) -> <<"">>.
×
1093

1094
-spec format_error(atom()) -> string().
1095
format_error(Reason) ->
1096
    case file:format_error(Reason) of
×
1097
        "unknown POSIX error" ->
1098
            case inet:format_error(Reason) of
×
1099
                "unknown POSIX error" ->
1100
                    atom_to_list(Reason);
×
1101
                Txt ->
1102
                    Txt
×
1103
            end;
1104
        Txt ->
1105
            Txt
×
1106
    end.
1107

1108
%%--------------------------------------------------------------------
1109
%% Image manipulation stuff.
1110
%%--------------------------------------------------------------------
1111
-spec read_image(binary()) -> {ok, binary(), media_info()} | pass.
1112
read_image(Path) ->
1113
    case file:read_file(Path) of
×
1114
        {ok, Data} ->
1115
            case eimp:identify(Data) of
×
1116
                {ok, Info} ->
1117
                    {ok, Data,
×
1118
                     #media_info{
1119
                        path = Path,
1120
                        type = proplists:get_value(type, Info),
1121
                        width = proplists:get_value(width, Info),
1122
                        height = proplists:get_value(height, Info)}};
1123
                {error, Why} ->
1124
                    ?DEBUG("Cannot identify type of ~ts: ~ts",
×
1125
                           [Path, eimp:format_error(Why)]),
×
1126
                    pass
×
1127
            end;
1128
        {error, Reason} ->
1129
            ?DEBUG("Failed to read file ~ts: ~ts",
×
1130
                   [Path, format_error(Reason)]),
×
1131
            pass
×
1132
    end.
1133

1134
-spec convert(binary(), media_info()) -> {ok, media_info()} | pass.
1135
convert(InData, #media_info{path = Path, type = T, width = W, height = H} = Info) ->
1136
    if W * H >= 25000000 ->
×
1137
            ?DEBUG("The image ~ts is more than 25 Mpix", [Path]),
×
1138
            pass;
×
1139
       W =< 300, H =< 300 ->
1140
            {ok, Info};
×
1141
       true ->
1142
            Dir = filename:dirname(Path),
×
1143
            Ext = atom_to_binary(T, latin1),
×
1144
            FileName = <<(p1_rand:get_string())/binary, $., Ext/binary>>,
×
1145
            OutPath = filename:join(Dir, FileName),
×
1146
            {W1, H1} = if W > H -> {300, round(H*300/W)};
×
1147
                          H > W -> {round(W*300/H), 300};
×
1148
                          true -> {300, 300}
×
1149
                       end,
1150
            OutInfo = #media_info{path = OutPath, type = T, width = W1, height = H1},
×
1151
            case eimp:convert(InData, T, [{scale, {W1, H1}}]) of
×
1152
                {ok, OutData} ->
1153
                    case file:write_file(OutPath, OutData) of
×
1154
                        ok ->
1155
                            {ok, OutInfo};
×
1156
                        {error, Why} ->
1157
                            ?ERROR_MSG("Failed to write to ~ts: ~ts",
×
1158
                                       [OutPath, format_error(Why)]),
×
1159
                            pass
×
1160
                    end;
1161
                {error, Why} ->
1162
                    ?ERROR_MSG("Failed to convert ~ts to ~ts: ~ts",
×
1163
                               [Path, OutPath, eimp:format_error(Why)]),
×
1164
                    pass
×
1165
            end
1166
    end.
1167

1168
-spec thumb_el(media_info(), binary()) -> xmlel().
1169
thumb_el(#media_info{type = T, height = H, width = W}, URI) ->
1170
    MimeType = <<"image/", (atom_to_binary(T, latin1))/binary>>,
×
1171
    Thumb = #thumbnail{'media-type' = MimeType, uri = URI,
×
1172
                       height = H, width = W},
1173
    xmpp:encode(Thumb).
×
1174

1175
%%--------------------------------------------------------------------
1176
%% Remove user.
1177
%%--------------------------------------------------------------------
1178
-spec remove_user(binary(), binary()) -> ok.
1179
remove_user(User, Server) ->
1180
    ServerHost = jid:nameprep(Server),
1✔
1181
    DocRoot = mod_http_upload_opt:docroot(ServerHost),
1✔
1182
    JIDinURL = mod_http_upload_opt:jid_in_url(ServerHost),
1✔
1183
    DocRoot1 = expand_host(expand_home(DocRoot), ServerHost),
1✔
1184
    UserStr = make_user_string(jid:make(User, Server), JIDinURL),
1✔
1185
    UserDir = str:join([DocRoot1, UserStr], <<$/>>),
1✔
1186
    case misc:delete_dir(UserDir) of
1✔
1187
        ok ->
1188
            ?INFO_MSG("Removed HTTP upload directory of ~ts@~ts", [User, Server]);
×
1189
        {error, enoent} ->
1190
            ?DEBUG("Found no HTTP upload directory of ~ts@~ts", [User, Server]);
1✔
1191
        {error, Error} ->
1192
            ?ERROR_MSG("Cannot remove HTTP upload directory of ~ts@~ts: ~ts",
×
1193
                       [User, Server, format_error(Error)])
×
1194
    end,
1195
    ok.
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc