gloox  0.9.9.12
prep.cpp
1 /*
2  Copyright (c) 2004-2008 by Jakob Schroeter <js@camaya.net>
3  This file is part of the gloox library. http://camaya.net/gloox
4 
5  This software is distributed under a license. The full license
6  agreement can be found in the file LICENSE in this distribution.
7  This software may not be copied, modified, sold or distributed
8  other than expressed in the named license agreement.
9 
10  This software is distributed without any warranty.
11 */
12 
13 #include "prep.h"
14 
15 #include <cstdlib>
16 #include <string>
17 #include <string.h>
18 
19 #ifdef _WIN32
20 # include "../config.h.win"
21 #elif defined( _WIN32_WCE )
22 # include "../config.h.win"
23 #else
24 # include "config.h"
25 #endif
26 
27 #ifdef HAVE_LIBIDN
28 # include <stringprep.h>
29 # include <idna.h>
30 #endif
31 
32 #define JID_PORTION_SIZE 1023
33 
34 namespace gloox
35 {
36 
37  namespace prep
38  {
39 
40 #ifdef HAVE_LIBIDN
41 
49  static std::string prepare( const std::string& s, const Stringprep_profile* profile )
50  {
51  if( s.empty() || s.length() > JID_PORTION_SIZE )
52  return std::string();
53 
54  std::string preppedString;
55  char* p = static_cast<char*>( calloc( JID_PORTION_SIZE, sizeof( char ) ) );
56  strncpy( p, s.c_str(), s.length() );
57  if( stringprep( p, JID_PORTION_SIZE, (Stringprep_profile_flags)0, profile ) == STRINGPREP_OK )
58  preppedString = p;
59  free( p );
60  return preppedString;
61  }
62 #endif
63 
64  std::string nodeprep( const std::string& node )
65  {
66 #ifdef HAVE_LIBIDN
67  return prepare( node, stringprep_xmpp_nodeprep );
68 #else
69  return node;
70 #endif
71  }
72 
73  std::string nameprep( const std::string& domain )
74  {
75 #ifdef HAVE_LIBIDN
76  return prepare( domain, stringprep_nameprep );
77 #else
78  return domain;
79 #endif
80  }
81 
82  std::string resourceprep( const std::string& resource )
83  {
84 #ifdef HAVE_LIBIDN
85  return prepare( resource, stringprep_xmpp_resourceprep );
86 #else
87  return resource;
88 #endif
89  }
90 
91  std::string idna( const std::string& domain )
92  {
93 #ifdef HAVE_LIBIDN
94  if( domain.empty() || domain.length() > JID_PORTION_SIZE )
95  return std::string();
96 
97  std::string preppedString;
98  char* prepped;
99  int rc = idna_to_ascii_8z( domain.c_str(), &prepped, (Idna_flags)0 );
100  if( rc == IDNA_SUCCESS )
101  preppedString = prepped;
102  if( rc != IDNA_MALLOC_ERROR )
103  free( prepped );
104  return preppedString;
105 #else
106  return domain;
107 #endif
108  }
109  }
110 }