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

processone / ejabberd / 1258

12 Dec 2025 03:57PM UTC coverage: 33.638% (-0.006%) from 33.644%
1258

push

github

badlop
Container: Apply commit a22c88a

ejabberdctl.template: Show meaningful error when ERL_DIST_PORT is in use

15554 of 46240 relevant lines covered (33.64%)

1078.28 hits per line

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

47.24
/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-2025   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
-define(CONTENT_TYPES,
37
        [{<<".avi">>, <<"video/avi">>},
38
         {<<".bmp">>, <<"image/bmp">>},
39
         {<<".bz2">>, <<"application/x-bzip2">>},
40
         {<<".gif">>, <<"image/gif">>},
41
         {<<".gz">>, <<"application/x-gzip">>},
42
         {<<".jpeg">>, <<"image/jpeg">>},
43
         {<<".jpg">>, <<"image/jpeg">>},
44
         {<<".m4a">>, <<"audio/mp4">>},
45
         {<<".mp3">>, <<"audio/mpeg">>},
46
         {<<".mp4">>, <<"video/mp4">>},
47
         {<<".mpeg">>, <<"video/mpeg">>},
48
         {<<".mpg">>, <<"video/mpeg">>},
49
         {<<".ogg">>, <<"application/ogg">>},
50
         {<<".pdf">>, <<"application/pdf">>},
51
         {<<".png">>, <<"image/png">>},
52
         {<<".rtf">>, <<"application/rtf">>},
53
         {<<".svg">>, <<"image/svg+xml">>},
54
         {<<".tiff">>, <<"image/tiff">>},
55
         {<<".txt">>, <<"text/plain">>},
56
         {<<".wav">>, <<"audio/wav">>},
57
         {<<".webp">>, <<"image/webp">>},
58
         {<<".xz">>, <<"application/x-xz">>},
59
         {<<".zip">>, <<"application/zip">>}]).
60

61
%% gen_mod/supervisor callbacks.
62
-export([start/2,
63
         stop/1,
64
         reload/3,
65
         depends/2,
66
         mod_doc/0,
67
         mod_opt_type/1,
68
         mod_options/1]).
69

70
%% gen_server callbacks.
71
-export([init/1,
72
         handle_call/3,
73
         handle_cast/2,
74
         handle_info/2,
75
         terminate/2,
76
         code_change/3]).
77

78
%% ejabberd_http callback.
79
-export([process/2]).
80

81
%% ejabberd_hooks callback.
82
-export([remove_user/2]).
83

84
%% Utility functions.
85
-export([get_proc_name/2,
86
         expand_home/1,
87
         expand_host/2]).
88

89
-include("ejabberd_http.hrl").
90
-include_lib("xmpp/include/xmpp.hrl").
91
-include("logger.hrl").
92
-include("translate.hrl").
93

94
-record(state,
95
        {server_host = <<>>     :: binary(),
96
         hosts = []             :: [binary()],
97
         name = <<>>            :: binary(),
98
         access = none          :: atom(),
99
         max_size = infinity    :: pos_integer() | infinity,
100
         secret_length = 40     :: pos_integer(),
101
         jid_in_url = sha1      :: sha1 | node,
102
         file_mode              :: integer() | undefined,
103
         dir_mode               :: integer() | undefined,
104
         docroot = <<>>         :: binary(),
105
         put_url = <<>>         :: binary(),
106
         get_url = <<>>         :: binary(),
107
         service_url            :: binary() | undefined,
108
         thumbnail = false      :: boolean(),
109
         custom_headers = []    :: [{binary(), binary()}],
110
         slots = #{}            :: slots(),
111
         external_secret = <<>> :: binary()}).
112

113
-record(media_info,
114
        {path   :: binary(),
115
         type   :: atom(),
116
         height :: integer(),
117
         width  :: integer()}).
118

119
-type state() :: #state{}.
120
-type slot() :: [binary(), ...].
121
-type slots() :: #{slot() => {pos_integer(), reference()}}.
122
-type media_info() :: #media_info{}.
123

124
%%--------------------------------------------------------------------
125
%% gen_mod/supervisor callbacks.
126
%%--------------------------------------------------------------------
127
-spec start(binary(), gen_mod:opts()) -> {ok, pid()} | {error, term()}.
128
start(ServerHost, Opts) ->
129
    Proc = get_proc_name(ServerHost, ?MODULE),
90✔
130
    case gen_mod:start_child(?MODULE, ServerHost, Opts, Proc) of
90✔
131
        {ok, _} = Ret -> Ret;
90✔
132
        {error, {already_started, _}} = Err ->
133
            ?ERROR_MSG("Multiple virtual hosts can't use a single 'put_url' "
×
134
                       "without the @HOST@ keyword", []),
×
135
            Err;
×
136
        Err ->
137
            Err
×
138
    end.
139

140
-spec stop(binary()) -> ok | {error, any()}.
141
stop(ServerHost) ->
142
    Proc = get_proc_name(ServerHost, ?MODULE),
90✔
143
    gen_mod:stop_child(Proc).
90✔
144

145
-spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok | {ok, pid()} | {error, term()}.
146
reload(ServerHost, NewOpts, OldOpts) ->
147
    NewURL = mod_http_upload_opt:put_url(NewOpts),
×
148
    OldURL = mod_http_upload_opt:put_url(OldOpts),
×
149
    OldProc = get_proc_name(ServerHost, ?MODULE, OldURL),
×
150
    NewProc = get_proc_name(ServerHost, ?MODULE, NewURL),
×
151
    if OldProc /= NewProc ->
×
152
            gen_mod:stop_child(OldProc),
×
153
            start(ServerHost, NewOpts);
×
154
       true ->
155
            gen_server:cast(NewProc, {reload, NewOpts, OldOpts})
×
156
    end.
157

158
-spec mod_opt_type(atom()) -> econf:validator().
159
mod_opt_type(name) ->
160
    econf:binary();
108✔
161
mod_opt_type(access) ->
162
    econf:acl();
108✔
163
mod_opt_type(max_size) ->
164
    econf:pos_int(infinity);
108✔
165
mod_opt_type(secret_length) ->
166
    econf:int(8, 1000);
108✔
167
mod_opt_type(jid_in_url) ->
168
    econf:enum([sha1, node]);
108✔
169
mod_opt_type(file_mode) ->
170
    econf:octal();
108✔
171
mod_opt_type(dir_mode) ->
172
    econf:octal();
108✔
173
mod_opt_type(docroot) ->
174
    econf:binary();
108✔
175
mod_opt_type(put_url) ->
176
    econf:url();
108✔
177
mod_opt_type(get_url) ->
178
    econf:url();
108✔
179
mod_opt_type(service_url) ->
180
    econf:url();
108✔
181
mod_opt_type(custom_headers) ->
182
    econf:map(econf:binary(), econf:binary());
108✔
183
mod_opt_type(rm_on_unregister) ->
184
    econf:bool();
108✔
185
mod_opt_type(thumbnail) ->
186
    econf:and_then(
108✔
187
      econf:bool(),
188
      fun(true) ->
189
              case eimp:supported_formats() of
×
190
                  [] -> econf:fail(eimp_error);
×
191
                  [_|_] -> true
×
192
              end;
193
         (false) ->
194
              false
×
195
      end);
196
mod_opt_type(external_secret) ->
197
    econf:binary();
108✔
198
mod_opt_type(host) ->
199
    econf:host();
108✔
200
mod_opt_type(hosts) ->
201
    econf:hosts();
108✔
202
mod_opt_type(vcard) ->
203
    econf:vcard_temp().
108✔
204

205
-spec mod_options(binary()) -> [{thumbnail, boolean()} |
206
                                {atom(), any()}].
207
mod_options(Host) ->
208
    [{host, <<"upload.", Host/binary>>},
108✔
209
     {hosts, []},
210
     {name, ?T("HTTP File Upload")},
211
     {vcard, undefined},
212
     {access, local},
213
     {max_size, 104857600},
214
     {secret_length, 40},
215
     {jid_in_url, sha1},
216
     {file_mode, undefined},
217
     {dir_mode, undefined},
218
     {docroot, <<"@HOME@/upload">>},
219
     {put_url, <<"https://", Host/binary, ":5443/upload">>},
220
     {get_url, undefined},
221
     {service_url, undefined},
222
     {external_secret, <<"">>},
223
     {custom_headers, []},
224
     {rm_on_unregister, true},
225
     {thumbnail, false}].
226

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

402
-spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}].
403
depends(_Host, _Opts) ->
404
    [].
108✔
405

406
%%--------------------------------------------------------------------
407
%% gen_server callbacks.
408
%%--------------------------------------------------------------------
409
-spec init(list()) -> {ok, state()}.
410
init([ServerHost|_]) ->
411
    process_flag(trap_exit, true),
90✔
412
    Opts = gen_mod:get_module_opts(ServerHost, ?MODULE),
90✔
413
    Hosts = gen_mod:get_opt_hosts(Opts),
90✔
414
    case mod_http_upload_opt:rm_on_unregister(Opts) of
90✔
415
        true ->
416
            ejabberd_hooks:add(remove_user, ServerHost, ?MODULE,
90✔
417
                               remove_user, 50);
418
        false ->
419
            ok
×
420
    end,
421
    State = init_state(ServerHost, Hosts, Opts),
90✔
422
    {ok, State}.
90✔
423

424
-spec handle_call(_, {pid(), _}, state())
425
      -> {reply, {ok, pos_integer(), binary(),
426
                      pos_integer() | undefined,
427
                      pos_integer() | undefined}, state()} |
428
         {reply, {error, atom()}, state()} | {noreply, state()}.
429
handle_call({use_slot, Slot, Size}, _From,
430
            #state{file_mode = FileMode,
431
                   dir_mode = DirMode,
432
                   get_url = GetPrefix,
433
                   thumbnail = Thumbnail,
434
                   custom_headers = CustomHeaders,
435
                   docroot = DocRoot} = State) ->
436
    case get_slot(Slot, State) of
3✔
437
        {ok, {Size, TRef}} ->
438
            misc:cancel_timer(TRef),
3✔
439
            NewState = del_slot(Slot, State),
3✔
440
            Path = str:join([DocRoot | Slot], <<$/>>),
3✔
441
            {reply,
3✔
442
             {ok, Path, FileMode, DirMode, GetPrefix, Thumbnail, CustomHeaders},
443
             NewState};
444
        {ok, {_WrongSize, _TRef}} ->
445
            {reply, {error, size_mismatch}, State};
×
446
        error ->
447
            {reply, {error, invalid_slot}, State}
×
448
    end;
449
handle_call(get_conf, _From,
450
            #state{docroot = DocRoot,
451
                   custom_headers = CustomHeaders} = State) ->
452
    {reply, {ok, DocRoot, CustomHeaders}, State};
3✔
453
handle_call(Request, From, State) ->
454
    ?WARNING_MSG("Unexpected call from ~p: ~p", [From, Request]),
×
455
    {noreply, State}.
×
456

457
-spec handle_cast(_, state()) -> {noreply, state()}.
458
handle_cast({reload, NewOpts, OldOpts},
459
            #state{server_host = ServerHost} = State) ->
460
    case {mod_http_upload_opt:rm_on_unregister(NewOpts),
×
461
          mod_http_upload_opt:rm_on_unregister(OldOpts)} of
462
        {true, false} ->
463
            ejabberd_hooks:add(remove_user, ServerHost, ?MODULE,
×
464
                               remove_user, 50);
465
        {false, true} ->
466
            ejabberd_hooks:delete(remove_user, ServerHost, ?MODULE,
×
467
                                  remove_user, 50);
468
        _ ->
469
            ok
×
470
    end,
471
    NewHosts = gen_mod:get_opt_hosts(NewOpts),
×
472
    OldHosts = gen_mod:get_opt_hosts(OldOpts),
×
473
    lists:foreach(fun ejabberd_router:unregister_route/1, OldHosts -- NewHosts),
×
474
    NewState = init_state(State#state{hosts = NewHosts -- OldHosts}, NewOpts),
×
475
    {noreply, NewState};
×
476
handle_cast(Request, State) ->
477
    ?WARNING_MSG("Unexpected cast: ~p", [Request]),
×
478
    {noreply, State}.
×
479

480
-spec handle_info(timeout | _, state()) -> {noreply, state()}.
481
handle_info({route, #iq{lang = Lang} = Packet}, State) ->
482
    try xmpp:decode_els(Packet) of
17✔
483
        IQ ->
484
            {Reply, NewState} = case process_iq(IQ, State) of
17✔
485
                                    R when is_record(R, iq) ->
486
                                        {R, State};
11✔
487
                                    {R, S} ->
488
                                        {R, S};
6✔
489
                                    not_request ->
490
                                        {none, State}
×
491
                                end,
492
            if Reply /= none ->
17✔
493
                    ejabberd_router:route(Reply);
17✔
494
               true ->
495
                    ok
×
496
            end,
497
            {noreply, NewState}
17✔
498
    catch _:{xmpp_codec, Why} ->
499
            Txt = xmpp:io_format_error(Why),
×
500
            Err = xmpp:err_bad_request(Txt, Lang),
×
501
            ejabberd_router:route_error(Packet, Err),
×
502
            {noreply, State}
×
503
    end;
504
handle_info({timeout, _TRef, Slot}, State) ->
505
    NewState = del_slot(Slot, State),
×
506
    {noreply, NewState};
×
507
handle_info(Info, State) ->
508
    ?WARNING_MSG("Unexpected info: ~p", [Info]),
×
509
    {noreply, State}.
×
510

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

517
-spec code_change({down, _} | _, state(), _) -> {ok, state()}.
518
code_change(_OldVsn, #state{server_host = ServerHost} = State, _Extra) ->
519
    ?DEBUG("Updating HTTP upload process for ~ts", [ServerHost]),
×
520
    {ok, State}.
×
521

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

654
%%--------------------------------------------------------------------
655
%% State initialization
656
%%--------------------------------------------------------------------
657
-spec init_state(binary(), [binary()], gen_mod:opts()) -> state().
658
init_state(ServerHost, Hosts, Opts) ->
659
    init_state(#state{server_host = ServerHost, hosts = Hosts}, Opts).
90✔
660

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

704
%%--------------------------------------------------------------------
705
%% Exported utility functions.
706
%%--------------------------------------------------------------------
707
-spec get_proc_name(binary(), atom()) -> atom().
708
get_proc_name(ServerHost, ModuleName) ->
709
    PutURL = mod_http_upload_opt:put_url(ServerHost),
180✔
710
    get_proc_name(ServerHost, ModuleName, PutURL).
180✔
711

712
-spec get_proc_name(binary(), atom(), binary()) -> atom().
713
get_proc_name(ServerHost, ModuleName, PutURL) ->
714
    %% Once we depend on OTP >= 20.0, we can use binaries with http_uri.
715
    {ok, _Scheme, _UserInfo, Host0, _Port, Path0, _Query} =
180✔
716
        misc:uri_parse(expand_host(PutURL, ServerHost)),
717
    Host = jid:nameprep(iolist_to_binary(Host0)),
180✔
718
    Path = str:strip(iolist_to_binary(Path0), right, $/),
180✔
719
    ProcPrefix = <<Host/binary, Path/binary>>,
180✔
720
    gen_mod:get_module_proc(ProcPrefix, ModuleName).
180✔
721

722
-spec expand_home(binary()) -> binary().
723
expand_home(Input) ->
724
    Home = misc:get_home(),
91✔
725
    misc:expand_keyword(<<"@HOME@">>, Input, Home).
91✔
726

727
-spec expand_host(binary(), binary()) -> binary().
728
expand_host(Input, Host) ->
729
    misc:expand_keyword(<<"@HOST@">>, Input, Host).
451✔
730

731
%%--------------------------------------------------------------------
732
%% Internal functions.
733
%%--------------------------------------------------------------------
734

735
%% XMPP request handling.
736

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

775
-spec process_slot_request(iq(), binary(), pos_integer(), binary(), binary(),
776
                           state()) -> {iq(), state()} | iq().
777
process_slot_request(#iq{lang = Lang, from = From} = IQ,
778
                     File, Size, CType, XMLNS,
779
                     #state{server_host = ServerHost,
780
                            access = Access} = State) ->
781
    case acl:match_rule(ServerHost, Access, From) of
9✔
782
        allow ->
783
            ContentType = yield_content_type(CType),
9✔
784
            case create_slot(State, From, File, Size, ContentType, XMLNS,
9✔
785
                             Lang) of
786
                {ok, Slot} ->
787
                    Query = make_query_string(Slot, Size, State),
6✔
788
                    NewState = add_slot(Slot, Size, State),
6✔
789
                    NewSlot = mk_slot(Slot, State, XMLNS, Query),
6✔
790
                    {xmpp:make_iq_result(IQ, NewSlot), NewState};
6✔
791
                {ok, PutURL, GetURL} ->
792
                    Slot = mk_slot(PutURL, GetURL, XMLNS, <<"">>),
×
793
                    xmpp:make_iq_result(IQ, Slot);
×
794
                {error, Error} ->
795
                    xmpp:make_error(IQ, Error)
3✔
796
            end;
797
        deny ->
798
            ?DEBUG("Denying HTTP upload slot request from ~ts",
×
799
                   [jid:encode(From)]),
×
800
            Txt = ?T("Access denied by service policy"),
×
801
            xmpp:make_error(IQ, xmpp:err_forbidden(Txt, Lang))
×
802
    end.
803

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

890
-spec add_slot(slot(), pos_integer(), state()) -> state().
891
add_slot(Slot, Size, #state{external_secret = <<>>, slots = Slots} = State) ->
892
    TRef = erlang:start_timer(?SLOT_TIMEOUT, self(), Slot),
6✔
893
    NewSlots = maps:put(Slot, {Size, TRef}, Slots),
6✔
894
    State#state{slots = NewSlots};
6✔
895
add_slot(_Slot, _Size, State) ->
896
    State.
×
897

898
-spec get_slot(slot(), state()) -> {ok, {pos_integer(), reference()}} | error.
899
get_slot(Slot, #state{slots = Slots}) ->
900
    maps:find(Slot, Slots).
3✔
901

902
-spec del_slot(slot(), state()) -> state().
903
del_slot(Slot, #state{slots = Slots} = State) ->
904
    NewSlots = maps:remove(Slot, Slots),
3✔
905
    State#state{slots = NewSlots}.
3✔
906

907
-spec mk_slot(slot(), state(), binary(), binary()) -> upload_slot();
908
             (binary(), binary(), binary(), binary()) -> upload_slot().
909
mk_slot(Slot, #state{put_url = PutPrefix, get_url = GetPrefix}, XMLNS, Query) ->
910
    PutURL = str:join([PutPrefix | Slot], <<$/>>),
6✔
911
    GetURL = str:join([GetPrefix | Slot], <<$/>>),
6✔
912
    mk_slot(PutURL, GetURL, XMLNS, Query);
6✔
913
mk_slot(PutURL, GetURL, XMLNS, Query) ->
914
    PutURL1 = <<(reencode_url(PutURL))/binary, Query/binary>>,
6✔
915
    GetURL1 = reencode_url(GetURL),
6✔
916
    case XMLNS of
6✔
917
        ?NS_HTTP_UPLOAD_0 ->
918
            #upload_slot_0{get = GetURL1, put = PutURL1, xmlns = XMLNS};
2✔
919
        _ ->
920
            #upload_slot{get = GetURL1, put = PutURL1, xmlns = XMLNS}
4✔
921
    end.
922

923
reencode_url(UrlString) ->
924
    {ok, _, _, Host, _, _, _} = yconf:parse_uri(misc:url_encode(UrlString)),
12✔
925
    HostDecoded = uri_string:percent_decode(Host),
12✔
926
    HostIdna = idna:encode(uri_string:percent_decode(HostDecoded)),
12✔
927
    re:replace(UrlString, HostDecoded, HostIdna, [{return, binary}]).
12✔
928

929
redecode_url(UrlString) ->
930
    {ok, _, _, HostIdna, _, _, _} = yconf:parse_uri(<<"http://", UrlString/binary>>),
6✔
931
    HostDecoded = idna:decode(HostIdna),
6✔
932
    Host = uri_string:quote(HostDecoded),
6✔
933
    re:replace(UrlString, HostIdna, Host, [{return, binary}]).
6✔
934

935
-spec make_user_string(jid(), sha1 | node) -> binary().
936
make_user_string(#jid{luser = U, lserver = S}, sha1) ->
937
    str:sha(<<U/binary, $@, S/binary>>);
7✔
938
make_user_string(#jid{luser = U}, node) ->
939
    replace_special_chars(U).
×
940

941
-spec make_file_string(binary()) -> binary().
942
make_file_string(File) ->
943
    replace_special_chars(File).
6✔
944

945
-spec make_query_string(slot(), non_neg_integer(), state()) -> binary().
946
make_query_string(Slot, Size, #state{external_secret = Key}) when Key /= <<>> ->
947
    UrlPath = str:join(Slot, <<$/>>),
×
948
    SizeStr = integer_to_binary(Size),
×
949
    Data = <<UrlPath/binary, " ", SizeStr/binary>>,
×
950
    HMAC = str:to_hexlist(crypto:mac(hmac, sha256, Key, Data)),
×
951
    <<"?v=", HMAC/binary>>;
×
952
make_query_string(_Slot, _Size, _State) ->
953
    <<>>.
6✔
954

955
-spec replace_special_chars(binary()) -> binary().
956
replace_special_chars(S) ->
957
    re:replace(S, <<"[^\\p{Xan}_.-]">>, <<$_>>,
6✔
958
               [unicode, global, {return, binary}]).
959

960
-spec yield_content_type(binary()) -> binary().
961
yield_content_type(<<"">>) -> ?DEFAULT_CONTENT_TYPE;
×
962
yield_content_type(Type) -> Type.
9✔
963

964
-spec encode_addr(inet:ip_address() | {inet:ip_address(), inet:port_number()} |
965
                  undefined) -> binary().
966
encode_addr(IP) ->
967
    ejabberd_config:may_hide_data(misc:ip_to_list(IP)).
3✔
968

969
-spec iq_disco_info(binary(), binary(), binary(), [xdata()]) -> disco_info().
970
iq_disco_info(Host, Lang, Name, AddInfo) ->
971
    Form = case mod_http_upload_opt:max_size(Host) of
7✔
972
               infinity ->
973
                   AddInfo;
×
974
               MaxSize ->
975
                   lists:foldl(
7✔
976
                     fun(NS, Acc) ->
977
                             Fs = http_upload:encode(
14✔
978
                                    [{'max-file-size', MaxSize}], NS, Lang),
979
                             [#xdata{type = result, fields = Fs}|Acc]
14✔
980
                     end, AddInfo, [?NS_HTTP_UPLOAD_0, ?NS_HTTP_UPLOAD])
981
           end,
982
    #disco_info{identities = [#identity{category = <<"store">>,
7✔
983
                                        type = <<"file">>,
984
                                        name = translate:translate(Lang, Name)}],
985
                features = [?NS_HTTP_UPLOAD,
986
                            ?NS_HTTP_UPLOAD_0,
987
                            ?NS_HTTP_UPLOAD_OLD,
988
                            ?NS_VCARD,
989
                            ?NS_DISCO_INFO,
990
                            ?NS_DISCO_ITEMS],
991
                xdata = Form}.
992

993
%% HTTP request handling.
994

995
-spec parse_http_request(#request{}) -> {atom(), slot()}.
996
parse_http_request(#request{host = Host0, path = Path}) ->
997
    Host = jid:nameprep(Host0),
6✔
998
    PrefixLength = length(Path) - 3,
6✔
999
    {ProcURL, Slot} = if PrefixLength > 0 ->
6✔
1000
                              Prefix = lists:sublist(Path, PrefixLength),
6✔
1001
                              {str:join([Host | Prefix], $/),
6✔
1002
                               lists:nthtail(PrefixLength, Path)};
1003
                         true ->
1004
                              {Host, Path}
×
1005
                      end,
1006
    {gen_mod:get_module_proc(ProcURL, ?MODULE), Slot}.
6✔
1007

1008
-spec store_file(binary(), http_request(),
1009
                 integer() | undefined,
1010
                 integer() | undefined,
1011
                 binary(), slot(), boolean())
1012
      -> ok | {ok, [{binary(), binary()}], binary()} | {error, term()}.
1013
store_file(Path, Request, FileMode, DirMode, GetPrefix, Slot, Thumbnail) ->
1014
    case do_store_file(Path, Request, FileMode, DirMode) of
3✔
1015
        ok when Thumbnail ->
1016
            case read_image(Path) of
×
1017
                {ok, Data, MediaInfo} ->
1018
                    case convert(Data, MediaInfo) of
×
1019
                        {ok, #media_info{path = OutPath} = OutMediaInfo} ->
1020
                            [UserDir, RandDir | _] = Slot,
×
1021
                            FileName = filename:basename(OutPath),
×
1022
                            URL = str:join([GetPrefix, UserDir,
×
1023
                                            RandDir, FileName], <<$/>>),
1024
                            ThumbEl = thumb_el(OutMediaInfo, URL),
×
1025
                            {ok,
×
1026
                             [{<<"Content-Type">>,
1027
                               <<"text/xml; charset=utf-8">>}],
1028
                             fxml:element_to_binary(ThumbEl)};
1029
                        pass ->
1030
                            ok
×
1031
                    end;
1032
                pass ->
1033
                    ok
×
1034
            end;
1035
        ok ->
1036
            ok;
3✔
1037
        Err ->
1038
            Err
×
1039
    end.
1040

1041
-spec do_store_file(file:filename_all(), http_request(),
1042
                    integer() | undefined,
1043
                    integer() | undefined)
1044
      -> ok | {error, term()}.
1045
do_store_file(Path, Request, FileMode, DirMode) ->
1046
    try
3✔
1047
        ok = filelib:ensure_dir(Path),
3✔
1048
        ok = ejabberd_http:recv_file(Request, Path),
3✔
1049
        if is_integer(FileMode) ->
3✔
1050
                ok = file:change_mode(Path, FileMode);
×
1051
           FileMode == undefined ->
1052
                ok
3✔
1053
        end,
1054
        if is_integer(DirMode) ->
3✔
1055
                RandDir = filename:dirname(Path),
×
1056
                UserDir = filename:dirname(RandDir),
×
1057
                ok = file:change_mode(RandDir, DirMode),
×
1058
                ok = file:change_mode(UserDir, DirMode);
×
1059
           DirMode == undefined ->
1060
                ok
3✔
1061
        end
1062
    catch
1063
        _:{badmatch, {error, Error}} ->
1064
            {error, Error}
×
1065
    end.
1066

1067
-spec guess_content_type(binary()) -> binary().
1068
guess_content_type(FileName) ->
1069
    mod_http_fileserver:content_type(FileName,
3✔
1070
                                     ?DEFAULT_CONTENT_TYPE,
1071
                                     ?CONTENT_TYPES).
1072

1073
-spec http_response(100..599)
1074
      -> {pos_integer(), [{binary(), binary()}], binary()}.
1075
http_response(Code) ->
1076
    http_response(Code, []).
×
1077

1078
-spec http_response(100..599, [{binary(), binary()}])
1079
      -> {pos_integer(), [{binary(), binary()}], binary()}.
1080
http_response(Code, ExtraHeaders) ->
1081
    Message = <<(code_to_message(Code))/binary, $\n>>,
3✔
1082
    http_response(Code, ExtraHeaders, Message).
3✔
1083

1084
-type http_body() :: binary() | {file, file:filename_all()}.
1085
-spec http_response(100..599, [{binary(), binary()}], http_body())
1086
      -> {pos_integer(), [{binary(), binary()}], http_body()}.
1087
http_response(Code, ExtraHeaders, Body) ->
1088
    Headers = case proplists:is_defined(<<"Content-Type">>, ExtraHeaders) of
6✔
1089
                  true ->
1090
                      ExtraHeaders;
3✔
1091
                  false ->
1092
                      [{<<"Content-Type">>, <<"text/plain">>} | ExtraHeaders]
3✔
1093
              end,
1094
    {Code, Headers, Body}.
6✔
1095

1096
-spec code_to_message(100..599) -> binary().
1097
code_to_message(201) -> <<"Upload successful.">>;
3✔
1098
code_to_message(403) -> <<"Forbidden.">>;
×
1099
code_to_message(404) -> <<"Not found.">>;
×
1100
code_to_message(405) -> <<"Method not allowed.">>;
×
1101
code_to_message(413) -> <<"File size doesn't match requested size.">>;
×
1102
code_to_message(500) -> <<"Internal server error.">>;
×
1103
code_to_message(_Code) -> <<"">>.
×
1104

1105
-spec format_error(atom()) -> string().
1106
format_error(Reason) ->
1107
    case file:format_error(Reason) of
×
1108
        "unknown POSIX error" ->
1109
            case inet:format_error(Reason) of
×
1110
                "unknown POSIX error" ->
1111
                    atom_to_list(Reason);
×
1112
                Txt ->
1113
                    Txt
×
1114
            end;
1115
        Txt ->
1116
            Txt
×
1117
    end.
1118

1119
%%--------------------------------------------------------------------
1120
%% Image manipulation stuff.
1121
%%--------------------------------------------------------------------
1122
-spec read_image(binary()) -> {ok, binary(), media_info()} | pass.
1123
read_image(Path) ->
1124
    case file:read_file(Path) of
×
1125
        {ok, Data} ->
1126
            case eimp:identify(Data) of
×
1127
                {ok, Info} ->
1128
                    {ok, Data,
×
1129
                     #media_info{
1130
                        path = Path,
1131
                        type = proplists:get_value(type, Info),
1132
                        width = proplists:get_value(width, Info),
1133
                        height = proplists:get_value(height, Info)}};
1134
                {error, Why} ->
1135
                    ?DEBUG("Cannot identify type of ~ts: ~ts",
×
1136
                           [Path, eimp:format_error(Why)]),
×
1137
                    pass
×
1138
            end;
1139
        {error, Reason} ->
1140
            ?DEBUG("Failed to read file ~ts: ~ts",
×
1141
                   [Path, format_error(Reason)]),
×
1142
            pass
×
1143
    end.
1144

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

1179
-spec thumb_el(media_info(), binary()) -> xmlel().
1180
thumb_el(#media_info{type = T, height = H, width = W}, URI) ->
1181
    MimeType = <<"image/", (atom_to_binary(T, latin1))/binary>>,
×
1182
    Thumb = #thumbnail{'media-type' = MimeType, uri = URI,
×
1183
                       height = H, width = W},
1184
    xmpp:encode(Thumb).
×
1185

1186
%%--------------------------------------------------------------------
1187
%% Remove user.
1188
%%--------------------------------------------------------------------
1189
-spec remove_user(binary(), binary()) -> ok.
1190
remove_user(User, Server) ->
1191
    ServerHost = jid:nameprep(Server),
1✔
1192
    DocRoot = mod_http_upload_opt:docroot(ServerHost),
1✔
1193
    JIDinURL = mod_http_upload_opt:jid_in_url(ServerHost),
1✔
1194
    DocRoot1 = expand_host(expand_home(DocRoot), ServerHost),
1✔
1195
    UserStr = make_user_string(jid:make(User, Server), JIDinURL),
1✔
1196
    UserDir = str:join([DocRoot1, UserStr], <<$/>>),
1✔
1197
    case misc:delete_dir(UserDir) of
1✔
1198
        ok ->
1199
            ?INFO_MSG("Removed HTTP upload directory of ~ts@~ts", [User, Server]);
×
1200
        {error, enoent} ->
1201
            ?DEBUG("Found no HTTP upload directory of ~ts@~ts", [User, Server]);
1✔
1202
        {error, Error} ->
1203
            ?ERROR_MSG("Cannot remove HTTP upload directory of ~ts@~ts: ~ts",
×
1204
                       [User, Server, format_error(Error)])
×
1205
    end,
1206
    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

© 2025 Coveralls, Inc