aboutsummaryrefslogtreecommitdiff
path: root/src/mod_register.erl
blob: 43499d2e50d29f839fed9c64b25deb7b2e92ee4a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
%%%----------------------------------------------------------------------
%%% File    : mod_register.erl
%%% Author  : Alexey Shchepin <alexey@process-one.net>
%%% Purpose : Inband registration support
%%% Created :  8 Dec 2002 by Alexey Shchepin <alexey@process-one.net>
%%%
%%%
%%% ejabberd, Copyright (C) 2002-2016   ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
%%% modify it under the terms of the GNU General Public License as
%%% published by the Free Software Foundation; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%%% General Public License for more details.
%%%
%%% You should have received a copy of the GNU General Public License along
%%% with this program; if not, write to the Free Software Foundation, Inc.,
%%% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
%%%
%%%----------------------------------------------------------------------

-module(mod_register).

-behaviour(ejabberd_config).

-author('alexey@process-one.net').

-protocol({xep, 77, '2.4'}).

-behaviour(gen_mod).

-export([start/2, stop/1, stream_feature_register/2,
	 unauthenticated_iq_register/4, try_register/5,
	 process_iq/3, send_registration_notifications/3,
	 transform_options/1, transform_module_options/1,
	 mod_opt_type/1, opt_type/1]).

-include("ejabberd.hrl").
-include("logger.hrl").

-include("jlib.hrl").

start(Host, Opts) ->
    IQDisc = gen_mod:get_opt(iqdisc, Opts, fun gen_iq_handler:check_type/1,
                             one_queue),
    gen_iq_handler:add_iq_handler(ejabberd_local, Host,
				  ?NS_REGISTER, ?MODULE, process_iq, IQDisc),
    gen_iq_handler:add_iq_handler(ejabberd_sm, Host,
				  ?NS_REGISTER, ?MODULE, process_iq, IQDisc),
    ejabberd_hooks:add(c2s_stream_features, Host, ?MODULE,
		       stream_feature_register, 50),
    ejabberd_hooks:add(c2s_unauthenticated_iq, Host,
		       ?MODULE, unauthenticated_iq_register, 50),
    mnesia:create_table(mod_register_ip,
			[{ram_copies, [node()]}, {local_content, true},
			 {attributes, [key, value]}]),
    mnesia:add_table_copy(mod_register_ip, node(),
			  ram_copies),
    ok.

stop(Host) ->
    ejabberd_hooks:delete(c2s_stream_features, Host,
			  ?MODULE, stream_feature_register, 50),
    ejabberd_hooks:delete(c2s_unauthenticated_iq, Host,
			  ?MODULE, unauthenticated_iq_register, 50),
    gen_iq_handler:remove_iq_handler(ejabberd_local, Host,
				     ?NS_REGISTER),
    gen_iq_handler:remove_iq_handler(ejabberd_sm, Host,
				     ?NS_REGISTER).

stream_feature_register(Acc, Host) ->
    AF = gen_mod:get_module_opt(Host, ?MODULE, access_from,
                                          fun(A) -> A end,
					  all),
    case (AF /= none) and lists:keymember(<<"mechanisms">>, 2, Acc) of
	true ->
	    [#xmlel{name = <<"register">>,
		    attrs = [{<<"xmlns">>, ?NS_FEATURE_IQREGISTER}],
		    children = []}
	     | Acc];
	false ->
	    Acc
    end.

unauthenticated_iq_register(_Acc, Server,
			    #iq{xmlns = ?NS_REGISTER} = IQ, IP) ->
    Address = case IP of
		{A, _Port} -> A;
		_ -> undefined
	      end,
    ResIQ = process_iq(jid:make(<<"">>, <<"">>,
				     <<"">>),
		       jid:make(<<"">>, Server, <<"">>), IQ, Address),
    Res1 = jlib:replace_from_to(jid:make(<<"">>,
					      Server, <<"">>),
				jid:make(<<"">>, <<"">>, <<"">>),
				jlib:iq_to_xml(ResIQ)),
    jlib:remove_attr(<<"to">>, Res1);
unauthenticated_iq_register(Acc, _Server, _IQ, _IP) ->
    Acc.

process_iq(From, To, IQ) ->
    process_iq(From, To, IQ, jid:tolower(From)).

process_iq(From, To,
	   #iq{type = Type, lang = Lang, sub_el = SubEl, id = ID} =
	       IQ,
	   Source) ->
    IsCaptchaEnabled = case
			 gen_mod:get_module_opt(To#jid.lserver, ?MODULE,
						captcha_protected,
                                                fun(B) when is_boolean(B) -> B end,
                                                false)
			   of
			 true -> true;
			 _ -> false
		       end,
    case Type of
      set ->
	  UTag = fxml:get_subtag(SubEl, <<"username">>),
	  PTag = fxml:get_subtag(SubEl, <<"password">>),
	  RTag = fxml:get_subtag(SubEl, <<"remove">>),
	  Server = To#jid.lserver,
	  Access = gen_mod:get_module_opt(Server, ?MODULE, access,
                                          fun(A) -> A end,
					  all),
	  AllowRemove = allow ==
			  acl:match_rule(Server, Access, From),
	  if (UTag /= false) and (RTag /= false) and
	       AllowRemove ->
		 User = fxml:get_tag_cdata(UTag),
		 case From of
		   #jid{user = User, lserver = Server} ->
		       ejabberd_auth:remove_user(User, Server),
		       IQ#iq{type = result, sub_el = []};
		   _ ->
		       if PTag /= false ->
			      Password = fxml:get_tag_cdata(PTag),
			      case ejabberd_auth:remove_user(User, Server,
							     Password)
				  of
				ok -> IQ#iq{type = result, sub_el = []};
				%% TODO FIXME: This piece of
				%% code does not work since
				%% the code have been changed
				%% to allow several auth
				%% modules.  lists:foreach can
				%% only return ok:
				not_allowed ->
				    Txt = <<"Removal is not allowed">>,
				    IQ#iq{type = error,
					  sub_el = [SubEl,
						    ?ERRT_NOT_ALLOWED(Lang, Txt)]};
				not_exists ->
				    Txt = <<"No such user">>,
				    IQ#iq{type = error,
					  sub_el =
					      [SubEl,
					       ?ERRT_ITEM_NOT_FOUND(Lang, Txt)]};
				Err ->
				    ?ERROR_MSG("failed to remove user ~s@~s: ~p",
					       [User, Server, Err]),
				    IQ#iq{type = error,
					  sub_el =
					      [SubEl,
					       ?ERR_INTERNAL_SERVER_ERROR]}
			      end;
			  true ->
			      Txt = <<"No password in this query">>,
			      IQ#iq{type = error,
				    sub_el = [SubEl, ?ERRT_BAD_REQUEST(Lang, Txt)]}
		       end
		 end;
	     (UTag == false) and (RTag /= false) and AllowRemove ->
		 case From of
		   #jid{user = User, lserver = Server,
			resource = Resource} ->
		       ResIQ = #iq{type = result, xmlns = ?NS_REGISTER,
				   id = ID, sub_el = []},
		       ejabberd_router:route(jid:make(User, Server,
							   Resource),
					     jid:make(User, Server,
							   Resource),
					     jlib:iq_to_xml(ResIQ)),
		       ejabberd_auth:remove_user(User, Server),
		       ignore;
		   _ ->
		       Txt = <<"The query is only allowed from local users">>,
		       IQ#iq{type = error,
			     sub_el = [SubEl, ?ERRT_NOT_ALLOWED(Lang, Txt)]}
		 end;
	     (UTag /= false) and (PTag /= false) ->
		 User = fxml:get_tag_cdata(UTag),
		 Password = fxml:get_tag_cdata(PTag),
		 try_register_or_set_password(User, Server, Password,
					      From, IQ, SubEl, Source, Lang,
					      not IsCaptchaEnabled);
	     IsCaptchaEnabled ->
		 case ejabberd_captcha:process_reply(SubEl) of
		   ok ->
		       case process_xdata_submit(SubEl) of
			 {ok, User, Password} ->
			     try_register_or_set_password(User, Server,
							  Password, From, IQ,
							  SubEl, Source, Lang,
							  true);
			 _ ->
			     Txt = <<"Incorrect data form">>,
			     IQ#iq{type = error,
				   sub_el = [SubEl, ?ERRT_BAD_REQUEST(Lang, Txt)]}
		       end;
		   {error, malformed} ->
		       Txt = <<"Incorrect CAPTCHA submit">>,
		       IQ#iq{type = error,
			     sub_el = [SubEl, ?ERRT_BAD_REQUEST(Lang, Txt)]};
		   _ ->
		       ErrText = <<"The CAPTCHA verification has failed">>,
		       IQ#iq{type = error,
			     sub_el = [SubEl, ?ERRT_NOT_ALLOWED(Lang, ErrText)]}
		 end;
	     true ->
		 IQ#iq{type = error, sub_el = [SubEl, ?ERR_BAD_REQUEST]}
	  end;
      get ->
	  {IsRegistered, UsernameSubels, QuerySubels} = case From
							    of
							  #jid{user = User,
							       lserver =
								   Server} ->
							      case
								ejabberd_auth:is_user_exists(User,
											     Server)
								  of
								true ->
								    {true,
								     [{xmlcdata,
								       User}],
								     [#xmlel{name
										 =
										 <<"registered">>,
									     attrs
										 =
										 [],
									     children
										 =
										 []}]};
								false ->
								    {false,
								     [{xmlcdata,
								       User}],
								     []}
							      end;
							  _ -> {false, [], []}
							end,
	  if IsCaptchaEnabled and not IsRegistered ->
		 TopInstrEl = #xmlel{name = <<"instructions">>,
				     attrs = [],
				     children =
					 [{xmlcdata,
					   translate:translate(Lang,
							       <<"You need a client that supports x:data "
								 "and CAPTCHA to register">>)}]},
		 InstrEl = #xmlel{name = <<"instructions">>, attrs = [],
				  children =
				      [{xmlcdata,
					translate:translate(Lang,
							    <<"Choose a username and password to register "
							      "with this server">>)}]},
		 UField = #xmlel{name = <<"field">>,
				 attrs =
				     [{<<"type">>, <<"text-single">>},
				      {<<"label">>,
				       translate:translate(Lang, <<"User">>)},
				      {<<"var">>, <<"username">>}],
				 children =
				     [#xmlel{name = <<"required">>, attrs = [],
					     children = []}]},
		 PField = #xmlel{name = <<"field">>,
				 attrs =
				     [{<<"type">>, <<"text-private">>},
				      {<<"label">>,
				       translate:translate(Lang,
							   <<"Password">>)},
				      {<<"var">>, <<"password">>}],
				 children =
				     [#xmlel{name = <<"required">>, attrs = [],
					     children = []}]},
		 case ejabberd_captcha:create_captcha_x(ID, To, Lang,
							Source,
							[InstrEl, UField,
							 PField])
		     of
		   {ok, CaptchaEls} ->
		       IQ#iq{type = result,
			     sub_el =
				 [#xmlel{name = <<"query">>,
					 attrs =
					     [{<<"xmlns">>,
					       ?NS_REGISTER}],
					 children =
					     [TopInstrEl | CaptchaEls]}]};
		   {error, limit} ->
		       ErrText = <<"Too many CAPTCHA requests">>,
		       IQ#iq{type = error,
			     sub_el =
				 [SubEl,
				  ?ERRT_RESOURCE_CONSTRAINT(Lang, ErrText)]};
		   _Err ->
		       ErrText = <<"Unable to generate a CAPTCHA">>,
		       IQ#iq{type = error,
			     sub_el =
				 [SubEl,
				  ?ERRT_INTERNAL_SERVER_ERROR(Lang, ErrText)]}
		 end;
	     true ->
		 IQ#iq{type = result,
		       sub_el =
			   [#xmlel{name = <<"query">>,
				   attrs =
				       [{<<"xmlns">>,
					 ?NS_REGISTER}],
				   children =
				       [#xmlel{name = <<"instructions">>,
					       attrs = [],
					       children =
						   [{xmlcdata,
						     translate:translate(Lang,
									 <<"Choose a username and password to register "
									   "with this server">>)}]},
					#xmlel{name = <<"username">>,
					       attrs = [],
					       children = UsernameSubels},
					#xmlel{name = <<"password">>,
					       attrs = [], children = []}
					| QuerySubels]}]}
	  end
    end.

try_register_or_set_password(User, Server, Password,
			     From, IQ, SubEl, Source, Lang, CaptchaSucceed) ->
    case From of
      #jid{user = User, lserver = Server} ->
	  try_set_password(User, Server, Password, IQ, SubEl,
			   Lang);
      _ when CaptchaSucceed ->
	  case check_from(From, Server) of
	    allow ->
		case try_register(User, Server, Password, Source, Lang)
		    of
		  ok -> IQ#iq{type = result, sub_el = []};
		  {error, Error} ->
		      IQ#iq{type = error, sub_el = [SubEl, Error]}
		end;
	    deny ->
		Txt = <<"Denied by ACL">>,
		IQ#iq{type = error, sub_el = [SubEl, ?ERRT_FORBIDDEN(Lang, Txt)]}
	  end;
      _ ->
	  IQ#iq{type = error, sub_el = [SubEl, ?ERR_NOT_ALLOWED]}
    end.

%% @doc Try to change password and return IQ response
try_set_password(User, Server, Password, IQ, SubEl,
		 Lang) ->
    case is_strong_password(Server, Password) of
      true ->
	  case ejabberd_auth:set_password(User, Server, Password)
	      of
	    ok -> IQ#iq{type = result, sub_el = []};
	    {error, empty_password} ->
		Txt = <<"Empty password">>,
		IQ#iq{type = error, sub_el = [SubEl, ?ERRT_BAD_REQUEST(Lang, Txt)]};
	    {error, not_allowed} ->
		Txt = <<"Changing password is not allowed">>,
		IQ#iq{type = error, sub_el = [SubEl, ?ERRT_NOT_ALLOWED(Lang, Txt)]};
	    {error, invalid_jid} ->
		IQ#iq{type = error,
		      sub_el = [SubEl, ?ERR_JID_MALFORMED]};
	    Err ->
		?ERROR_MSG("failed to register user ~s@~s: ~p",
			   [User, Server, Err]),
		IQ#iq{type = error,
		      sub_el = [SubEl, ?ERR_INTERNAL_SERVER_ERROR]}
	  end;
      error_preparing_password ->
	  ErrText = <<"The password contains unacceptable characters">>,
	  IQ#iq{type = error,
		sub_el = [SubEl, ?ERRT_NOT_ACCEPTABLE(Lang, ErrText)]};
      false ->
	  ErrText = <<"The password is too weak">>,
	  IQ#iq{type = error,
		sub_el = [SubEl, ?ERRT_NOT_ACCEPTABLE(Lang, ErrText)]}
    end.

try_register(User, Server, Password, SourceRaw, Lang) ->
    case jid:is_nodename(User) of
      false -> {error, ?ERRT_BAD_REQUEST(Lang, <<"Malformed username">>)};
      _ ->
	  JID = jid:make(User, Server, <<"">>),
	  Access = gen_mod:get_module_opt(Server, ?MODULE, access,
                                          fun(A) -> A end,
					  all),
	  IPAccess = get_ip_access(Server),
	  case {acl:match_rule(Server, Access, JID),
		check_ip_access(SourceRaw, IPAccess)}
	      of
	    {deny, _} -> {error, ?ERRT_FORBIDDEN(Lang, <<"Denied by ACL">>)};
	    {_, deny} -> {error, ?ERRT_FORBIDDEN(Lang, <<"Denied by ACL">>)};
	    {allow, allow} ->
		Source = may_remove_resource(SourceRaw),
		case check_timeout(Source) of
		  true ->
		      case is_strong_password(Server, Password) of
			true ->
			    case ejabberd_auth:try_register(User, Server,
							    Password)
				of
			      {atomic, ok} ->
				  send_welcome_message(JID),
				  send_registration_notifications(
                                    ?MODULE, JID, Source),
				  ok;
			      Error ->
				  remove_timeout(Source),
				  case Error of
				    {atomic, exists} ->
					Txt = <<"User already exists">>,
					{error, ?ERRT_CONFLICT(Lang, Txt)};
				    {error, invalid_jid} ->
					{error, ?ERR_JID_MALFORMED};
				    {error, not_allowed} ->
					{error, ?ERR_NOT_ALLOWED};
				    {error, too_many_users} ->
					Txt = <<"Too many users registered">>,
					{error, ?ERRT_RESOURCE_CONSTRAINT(Lang, Txt)};
				    {error, _} ->
					?ERROR_MSG("failed to register user "
						   "~s@~s: ~p",
						   [User, Server, Error]),
					{error, ?ERR_INTERNAL_SERVER_ERROR}
				  end
			    end;
			error_preparing_password ->
			    remove_timeout(Source),
			    ErrText = <<"The password contains unacceptable characters">>,
			    {error, ?ERRT_NOT_ACCEPTABLE(Lang, ErrText)};
			false ->
			    remove_timeout(Source),
			    ErrText = <<"The password is too weak">>,
			    {error, ?ERRT_NOT_ACCEPTABLE(Lang, ErrText)}
		      end;
		  false ->
		      ErrText =
			  <<"Users are not allowed to register accounts "
			    "so quickly">>,
		      {error, ?ERRT_RESOURCE_CONSTRAINT(Lang, ErrText)}
		end
	  end
    end.

send_welcome_message(JID) ->
    Host = JID#jid.lserver,
    case gen_mod:get_module_opt(Host, ?MODULE, welcome_message,
                                fun(Opts) ->
                                        S = proplists:get_value(
                                              subject, Opts, <<>>),
                                        B = proplists:get_value(
                                              body, Opts, <<>>),
                                        {iolist_to_binary(S),
                                         iolist_to_binary(B)}
                                end, {<<"">>, <<"">>})
	of
      {<<"">>, <<"">>} -> ok;
      {Subj, Body} ->
	  ejabberd_router:route(jid:make(<<"">>, Host,
					      <<"">>),
				JID,
				#xmlel{name = <<"message">>,
				       attrs = [{<<"type">>, <<"normal">>}],
				       children =
					   [#xmlel{name = <<"subject">>,
						   attrs = [],
						   children =
						       [{xmlcdata, Subj}]},
					    #xmlel{name = <<"body">>,
						   attrs = [],
						   children =
						       [{xmlcdata, Body}]}]});
      _ -> ok
    end.

send_registration_notifications(Mod, UJID, Source) ->
    Host = UJID#jid.lserver,
    case gen_mod:get_module_opt(
           Host, Mod, registration_watchers,
           fun(Ss) ->
                   [#jid{} = jid:from_string(iolist_to_binary(S))
                    || S <- Ss]
           end, []) of
        [] -> ok;
        JIDs when is_list(JIDs) ->
            Body =
                iolist_to_binary(io_lib:format("[~s] The account ~s was registered from "
                                               "IP address ~s on node ~w using ~p.",
                                               [get_time_string(),
                                                jid:to_string(UJID),
                                                ip_to_string(Source), node(),
                                                Mod])),
            lists:foreach(
              fun(JID) ->
                      ejabberd_router:route(
                        jid:make(<<"">>, Host, <<"">>),
                        JID,
                        #xmlel{name = <<"message">>,
                               attrs = [{<<"type">>, <<"chat">>}],
                               children = [#xmlel{name = <<"body">>,
                                                  attrs = [],
                                                  children = [{xmlcdata,Body}]}]})
              end, JIDs)
    end.

check_from(#jid{user = <<"">>, server = <<"">>},
	   _Server) ->
    allow;
check_from(JID, Server) ->
    Access = gen_mod:get_module_opt(Server, ?MODULE, access_from,
                                    fun(A) -> A end,
                                    none),
    acl:match_rule(Server, Access, JID).

check_timeout(undefined) -> true;
check_timeout(Source) ->
    Timeout = ejabberd_config:get_option(
                registration_timeout,
                fun(TO) when is_integer(TO), TO > 0 ->
                        TO;
                   (infinity) ->
                        infinity;
                   (unlimited) ->
                        infinity
                end, 600),
    if is_integer(Timeout) ->
	   Priority = -p1_time_compat:system_time(seconds),
	   CleanPriority = Priority + Timeout,
	   F = fun () ->
		       Treap = case mnesia:read(mod_register_ip, treap, write)
				   of
				 [] -> treap:empty();
				 [{mod_register_ip, treap, T}] -> T
			       end,
		       Treap1 = clean_treap(Treap, CleanPriority),
		       case treap:lookup(Source, Treap1) of
			 error ->
			     Treap2 = treap:insert(Source, Priority, [],
						   Treap1),
			     mnesia:write({mod_register_ip, treap, Treap2}),
			     true;
			 {ok, _, _} ->
			     mnesia:write({mod_register_ip, treap, Treap1}),
			     false
		       end
	       end,
	   case mnesia:transaction(F) of
	     {atomic, Res} -> Res;
	     {aborted, Reason} ->
		 ?ERROR_MSG("mod_register: timeout check error: ~p~n",
			    [Reason]),
		 true
	   end;
       true -> true
    end.

clean_treap(Treap, CleanPriority) ->
    case treap:is_empty(Treap) of
      true -> Treap;
      false ->
	  {_Key, Priority, _Value} = treap:get_root(Treap),
	  if Priority > CleanPriority ->
		 clean_treap(treap:delete_root(Treap), CleanPriority);
	     true -> Treap
	  end
    end.

remove_timeout(undefined) -> true;
remove_timeout(Source) ->
    Timeout = ejabberd_config:get_option(
                registration_timeout,
                fun(TO) when is_integer(TO), TO > 0 ->
                        TO;
                   (infinity) ->
                        infinity;
                   (unlimited) ->
                        infinity
                end, 600),
    if is_integer(Timeout) ->
	   F = fun () ->
		       Treap = case mnesia:read(mod_register_ip, treap, write)
				   of
				 [] -> treap:empty();
				 [{mod_register_ip, treap, T}] -> T
			       end,
		       Treap1 = treap:delete(Source, Treap),
		       mnesia:write({mod_register_ip, treap, Treap1}),
		       ok
	       end,
	   case mnesia:transaction(F) of
	     {atomic, ok} -> ok;
	     {aborted, Reason} ->
		 ?ERROR_MSG("mod_register: timeout remove error: "
			    "~p~n",
			    [Reason]),
		 ok
	   end;
       true -> ok
    end.

ip_to_string(Source) when is_tuple(Source) ->
    jlib:ip_to_list(Source);
ip_to_string(undefined) -> <<"undefined">>;
ip_to_string(_) -> <<"unknown">>.

get_time_string() -> write_time(erlang:localtime()).
%% Function copied from ejabberd_logger_h.erl and customized

write_time({{Y, Mo, D}, {H, Mi, S}}) ->
    io_lib:format("~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w",
		  [Y, Mo, D, H, Mi, S]).

process_xdata_submit(El) ->
    case fxml:get_subtag(El, <<"x">>) of
      false -> error;
      Xdata ->
	  Fields = jlib:parse_xdata_submit(Xdata),
	  case catch {proplists:get_value(<<"username">>, Fields),
		      proplists:get_value(<<"password">>, Fields)}
	      of
	    {[User | _], [Pass | _]} -> {ok, User, Pass};
	    _ -> error
	  end
    end.

is_strong_password(Server, Password) ->
    case jid:resourceprep(Password) of
	PP when is_binary(PP) ->
	    is_strong_password2(Server, Password);
	error ->
	    error_preparing_password
    end.

is_strong_password2(Server, Password) ->
    LServer = jid:nameprep(Server),
    case gen_mod:get_module_opt(LServer, ?MODULE, password_strength,
                                fun(N) when is_number(N), N>=0 -> N end,
                                0) of
        0 ->
            true;
        Entropy ->
            ejabberd_auth:entropy(Password) >= Entropy
    end.

transform_options(Opts) ->
    Opts1 = transform_ip_access(Opts),
    transform_module_options(Opts1).

transform_ip_access(Opts) ->
    try
        {value, {modules, ModOpts}, Opts1} = lists:keytake(modules, 1, Opts),
        {value, {?MODULE, RegOpts}, ModOpts1} = lists:keytake(?MODULE, 1, ModOpts),
        {value, {ip_access, L}, RegOpts1} = lists:keytake(ip_access, 1, RegOpts),
        true = is_list(L),
        ?WARNING_MSG("Old 'ip_access' format detected. "
                     "The old format is still supported "
                     "but it is better to fix your config: "
                     "use access rules instead.", []),
        ACLs = lists:flatmap(
                 fun({Action, S}) ->
                         ACLName = jlib:binary_to_atom(
                                     iolist_to_binary(
                                       ["ip_", S])),
                         [{Action, ACLName},
                          {acl, ACLName, {ip, S}}]
                 end, L),
        Access = {access, mod_register_networks,
                  [{Action, ACLName} || {Action, ACLName} <- ACLs]},
        [ACL || {acl, _, _} = ACL <- ACLs] ++
            [Access,
             {modules,
              [{mod_register,
                [{ip_access, mod_register_networks}|RegOpts1]}
               | ModOpts1]}|Opts1]
    catch error:{badmatch, false} ->
            Opts
    end.

transform_module_options(Opts) ->
    lists:flatmap(
      fun({welcome_message, {Subj, Body}}) ->
              ?WARNING_MSG("Old 'welcome_message' format detected. "
                           "The old format is still supported "
                           "but it is better to fix your config: "
                           "change it to {welcome_message, "
                           "[{subject, Subject}, {body, Body}]}",
                           []),
              [{welcome_message, [{subject, Subj}, {body, Body}]}];
         (Opt) ->
              [Opt]
      end, Opts).

%%%
%%% ip_access management
%%%

may_remove_resource({_, _, _} = From) ->
    jid:remove_resource(From);
may_remove_resource(From) -> From.

get_ip_access(Host) ->
    gen_mod:get_module_opt(Host, ?MODULE, ip_access,
                           fun(A) when is_atom(A) -> A end,
                           all).

check_ip_access({User, Server, Resource}, IPAccess) ->
    case ejabberd_sm:get_user_ip(User, Server, Resource) of
        {IPAddress, _PortNumber} ->
            check_ip_access(IPAddress, IPAccess);
        _ ->
            deny
    end;
check_ip_access(undefined, _IPAccess) ->
    deny;
check_ip_access(IPAddress, IPAccess) ->
    acl:match_rule(global, IPAccess, IPAddress).

mod_opt_type(access) ->
    fun acl:access_rules_validator/1;
mod_opt_type(access_from) ->
    fun (A) when is_atom(A) -> A end;
mod_opt_type(captcha_protected) ->
    fun (B) when is_boolean(B) -> B end;
mod_opt_type(ip_access) ->
    fun acl:access_rules_validator/1;
mod_opt_type(iqdisc) -> fun gen_iq_handler:check_type/1;
mod_opt_type(password_strength) ->
    fun (N) when is_number(N), N >= 0 -> N end;
mod_opt_type(registration_watchers) ->
    fun (Ss) ->
	    [#jid{} = jid:from_string(iolist_to_binary(S))
	     || S <- Ss]
    end;
mod_opt_type(welcome_message) ->
    fun (Opts) ->
	    S = proplists:get_value(subject, Opts, <<>>),
	    B = proplists:get_value(body, Opts, <<>>),
	    {iolist_to_binary(S), iolist_to_binary(B)}
    end;
mod_opt_type(_) ->
    [access, access_from, captcha_protected, ip_access,
     iqdisc, password_strength, registration_watchers,
     welcome_message].

opt_type(registration_timeout) ->
    fun (TO) when is_integer(TO), TO > 0 -> TO;
	(infinity) -> infinity;
	(unlimited) -> infinity
    end;
opt_type(_) -> [registration_timeout].