001/** 002 * 003 * Copyright © 2014-2023 Florian Schmaus 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jxmpp.stringprep.libidn; 018 019import org.jxmpp.JxmppContext; 020import org.jxmpp.stringprep.XmppStringprep; 021import org.jxmpp.stringprep.XmppStringprepException; 022 023import gnu.inet.encoding.Stringprep; 024import gnu.inet.encoding.StringprepException; 025 026/** 027 * XMPP string preparation using libidn. 028 */ 029public class LibIdnXmppStringprep implements XmppStringprep { 030 031 private static LibIdnXmppStringprep instance; 032 033 /** 034 * The name of the stringprep implementation. 035 */ 036 public static final String NAME = "libidn"; 037 038 /** 039 * Setup the libidn Stringprep implementation as active Stringprep implementation. 040 */ 041 public static void setup() { 042 JxmppContext.setDefaultXmppStringprep(getInstance()); 043 } 044 045 /** 046 * Get the libidn Stringprep implementation singleton. 047 * @return the libidn Stringprep implementation. 048 */ 049 public static LibIdnXmppStringprep getInstance() { 050 if (instance == null) { 051 instance = new LibIdnXmppStringprep(); 052 } 053 return instance; 054 } 055 056 private LibIdnXmppStringprep() { 057 } 058 059 @Override 060 public String localprep(String string) throws XmppStringprepException { 061 try { 062 // Allow unassigned codepoints as of RFC6122 A.2 063 return Stringprep.nodeprep(string, true); 064 } catch (StringprepException e) { 065 throw new XmppStringprepException(string, e); 066 } 067 } 068 069 @Override 070 public String domainprep(String string) throws XmppStringprepException { 071 try { 072 // Don't allow unassigned because this is a "stored string". See 073 // RFC3453 7, RFC3490 4 1) and RFC6122 2.2 074 return Stringprep.nameprep(string); 075 } catch (StringprepException e) { 076 throw new XmppStringprepException(string, e); 077 } 078 } 079 080 @Override 081 public String resourceprep(String string) throws XmppStringprepException { 082 try { 083 // Allow unassigned codepoints as of RFC6122 B.2 084 return Stringprep.resourceprep(string, true); 085 } catch (StringprepException e) { 086 throw new XmppStringprepException(string, e); 087 } 088 } 089}