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

processone / ejabberd / 747

27 Jun 2024 01:43PM UTC coverage: 32.123% (+0.8%) from 31.276%
747

push

github

badlop
Set version to 24.06

14119 of 43953 relevant lines covered (32.12%)

614.73 hits per line

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

45.95
/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-2024   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.2', '15.10', "", ""}).
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),
3✔
130
    case gen_mod:start_child(?MODULE, ServerHost, Opts, Proc) of
3✔
131
        {ok, _} = Ret -> Ret;
3✔
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),
3✔
143
    gen_mod:stop_child(Proc).
3✔
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();
3✔
161
mod_opt_type(access) ->
162
    econf:acl();
3✔
163
mod_opt_type(max_size) ->
164
    econf:pos_int(infinity);
3✔
165
mod_opt_type(secret_length) ->
166
    econf:int(8, 1000);
3✔
167
mod_opt_type(jid_in_url) ->
168
    econf:enum([sha1, node]);
3✔
169
mod_opt_type(file_mode) ->
170
    econf:octal();
3✔
171
mod_opt_type(dir_mode) ->
172
    econf:octal();
3✔
173
mod_opt_type(docroot) ->
174
    econf:binary();
3✔
175
mod_opt_type(put_url) ->
176
    econf:url();
3✔
177
mod_opt_type(get_url) ->
178
    econf:url();
3✔
179
mod_opt_type(service_url) ->
180
    econf:url();
3✔
181
mod_opt_type(custom_headers) ->
182
    econf:map(econf:binary(), econf:binary());
3✔
183
mod_opt_type(rm_on_unregister) ->
184
    econf:bool();
3✔
185
mod_opt_type(thumbnail) ->
186
    econf:and_then(
3✔
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();
3✔
198
mod_opt_type(host) ->
199
    econf:host();
3✔
200
mod_opt_type(hosts) ->
201
    econf:hosts();
3✔
202
mod_opt_type(vcard) ->
203
    econf:vcard_temp().
3✔
204

205
-spec mod_options(binary()) -> [{thumbnail, boolean()} |
206
                                {atom(), any()}].
207
mod_options(Host) ->
208
    [{host, <<"upload.", Host/binary>>},
3✔
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
                     "This will only be displayed by special XMPP clients. "
253
                     "The default value is \"HTTP File Upload\".")}},
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. NOTE: different virtual "
323
                     "hosts cannot use the same PUT URL. "
324
                     "The default value is \"https://@HOST@:5443/upload\".")}},
325
           {get_url,
326
            #{value => ?T("URL"),
327
              desc =>
328
                  ?T("This option specifies the initial part of the GET URLs "
329
                     "used for downloading the files. The default value is 'undefined'. "
330
                     "When this option is 'undefined', this option is set "
331
                     "to the same value as 'put_url'. The keyword @HOST@ is "
332
                     "replaced with the virtual host name. NOTE: if GET requests "
333
                     "are handled by 'mod_http_upload', the 'get_url' must match the "
334
                     "'put_url'. Setting it to a different value only makes "
335
                     "sense if an external web server or _`mod_http_fileserver`_ "
336
                     "is used to serve the uploaded files.")}},
337
           {service_url,
338
            #{desc => ?T("Deprecated.")}},
339
           {custom_headers,
340
            #{value => "{Name: Value}",
341
              desc =>
342
                  ?T("This option specifies additional header fields to be "
343
                     "included in all HTTP responses. By default no custom "
344
                     "headers are included.")}},
345
           {external_secret,
346
            #{value => ?T("Text"),
347
              desc =>
348
                  ?T("This option makes it possible to offload all HTTP "
349
                     "Upload processing to a separate HTTP server. "
350
                     "Both ejabberd and the HTTP server should share this "
351
                     "secret and behave exactly as described at "
352
                     "https://modules.prosody.im/mod_http_upload_external.html"
353
                     "[Prosody's mod_http_upload_external] in the "
354
                     "'Implementation' section. There is no default value.")}},
355
           {rm_on_unregister,
356
            #{value => "true | false",
357
              desc =>
358
                  ?T("This option specifies whether files uploaded by a user "
359
                     "should be removed when that user is unregistered. "
360
                     "The default value is 'true'.")}},
361
           {vcard,
362
            #{value => ?T("vCard"),
363
              desc =>
364
                  ?T("A custom vCard of the service that will be displayed "
365
                     "by some XMPP clients in Service Discovery. The value of "
366
                     "'vCard' is a YAML map constructed from an XML representation "
367
                     "of vCard. Since the representation has no attributes, "
368
                     "the mapping is straightforward."),
369
              example =>
370
                  ["# This XML representation of vCard:",
371
                   "#   <vCard xmlns='vcard-temp'>",
372
                   "#     <FN>Conferences</FN>",
373
                   "#     <ADR>",
374
                   "#       <WORK/>",
375
                   "#       <STREET>Elm Street</STREET>",
376
                   "#     </ADR>",
377
                   "#   </vCard>",
378
                   "# ",
379
                   "# is translated to:",
380
                   "vcard:",
381
                   "  fn: Conferences",
382
                   "  adr:",
383
                   "    -",
384
                   "      work: true",
385
                   "      street: Elm Street"]}}],
386
      example =>
387
          ["listen:",
388
           "  -",
389
           "    port: 5443",
390
           "    module: ejabberd_http",
391
           "    tls: true",
392
           "    request_handlers:",
393
           "      /upload: mod_http_upload",
394
           "",
395
           "modules:",
396
           "  mod_http_upload:",
397
           "    docroot: /ejabberd/upload",
398
           "    put_url: \"https://@HOST@:5443/upload\""]}.
399

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

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

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

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

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

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

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

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

650
%%--------------------------------------------------------------------
651
%% State initialization
652
%%--------------------------------------------------------------------
653
-spec init_state(binary(), [binary()], gen_mod:opts()) -> state().
654
init_state(ServerHost, Hosts, Opts) ->
655
    init_state(#state{server_host = ServerHost, hosts = Hosts}, Opts).
3✔
656

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

700
%%--------------------------------------------------------------------
701
%% Exported utility functions.
702
%%--------------------------------------------------------------------
703
-spec get_proc_name(binary(), atom()) -> atom().
704
get_proc_name(ServerHost, ModuleName) ->
705
    PutURL = mod_http_upload_opt:put_url(ServerHost),
6✔
706
    get_proc_name(ServerHost, ModuleName, PutURL).
6✔
707

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

718
-spec expand_home(binary()) -> binary().
719
expand_home(Input) ->
720
    {ok, [[Home]]} = init:get_argument(home),
4✔
721
    misc:expand_keyword(<<"@HOME@">>, Input, Home).
4✔
722

723
-spec expand_host(binary(), binary()) -> binary().
724
expand_host(Input, Host) ->
725
    misc:expand_keyword(<<"@HOST@">>, Input, Host).
16✔
726

727
%%--------------------------------------------------------------------
728
%% Internal functions.
729
%%--------------------------------------------------------------------
730

731
%% XMPP request handling.
732

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

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

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

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

894
-spec get_slot(slot(), state()) -> {ok, {pos_integer(), reference()}} | error.
895
get_slot(Slot, #state{slots = Slots}) ->
896
    maps:find(Slot, Slots).
3✔
897

898
-spec del_slot(slot(), state()) -> state().
899
del_slot(Slot, #state{slots = Slots} = State) ->
900
    NewSlots = maps:remove(Slot, Slots),
3✔
901
    State#state{slots = NewSlots}.
3✔
902

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

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

925
-spec make_file_string(binary()) -> binary().
926
make_file_string(File) ->
927
    replace_special_chars(File).
6✔
928

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

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

944
-spec yield_content_type(binary()) -> binary().
945
yield_content_type(<<"">>) -> ?DEFAULT_CONTENT_TYPE;
×
946
yield_content_type(Type) -> Type.
9✔
947

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

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

977
%% HTTP request handling.
978

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

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

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

1051
-spec guess_content_type(binary()) -> binary().
1052
guess_content_type(FileName) ->
1053
    mod_http_fileserver:content_type(FileName,
3✔
1054
                                     ?DEFAULT_CONTENT_TYPE,
1055
                                     ?CONTENT_TYPES).
1056

1057
-spec http_response(100..599)
1058
      -> {pos_integer(), [{binary(), binary()}], binary()}.
1059
http_response(Code) ->
1060
    http_response(Code, []).
×
1061

1062
-spec http_response(100..599, [{binary(), binary()}])
1063
      -> {pos_integer(), [{binary(), binary()}], binary()}.
1064
http_response(Code, ExtraHeaders) ->
1065
    Message = <<(code_to_message(Code))/binary, $\n>>,
3✔
1066
    http_response(Code, ExtraHeaders, Message).
3✔
1067

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

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

1089
-spec format_error(atom()) -> string().
1090
format_error(Reason) ->
1091
    case file:format_error(Reason) of
×
1092
        "unknown POSIX error" ->
1093
            case inet:format_error(Reason) of
×
1094
                "unknown POSIX error" ->
1095
                    atom_to_list(Reason);
×
1096
                Txt ->
1097
                    Txt
×
1098
            end;
1099
        Txt ->
1100
            Txt
×
1101
    end.
1102

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

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

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

1170
%%--------------------------------------------------------------------
1171
%% Remove user.
1172
%%--------------------------------------------------------------------
1173
-spec remove_user(binary(), binary()) -> ok.
1174
remove_user(User, Server) ->
1175
    ServerHost = jid:nameprep(Server),
1✔
1176
    DocRoot = mod_http_upload_opt:docroot(ServerHost),
1✔
1177
    JIDinURL = mod_http_upload_opt:jid_in_url(ServerHost),
1✔
1178
    DocRoot1 = expand_host(expand_home(DocRoot), ServerHost),
1✔
1179
    UserStr = make_user_string(jid:make(User, Server), JIDinURL),
1✔
1180
    UserDir = str:join([DocRoot1, UserStr], <<$/>>),
1✔
1181
    case misc:delete_dir(UserDir) of
1✔
1182
        ok ->
1183
            ?INFO_MSG("Removed HTTP upload directory of ~ts@~ts", [User, Server]);
×
1184
        {error, enoent} ->
1185
            ?DEBUG("Found no HTTP upload directory of ~ts@~ts", [User, Server]);
1✔
1186
        {error, Error} ->
1187
            ?ERROR_MSG("Cannot remove HTTP upload directory of ~ts@~ts: ~ts",
×
1188
                       [User, Server, format_error(Error)])
×
1189
    end,
1190
    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