MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
common.cpp
1 /*
2  Copyright (C) 2003-2006 MySQL AB, 2009 Sun Microsystems, Inc.
3  All rights reserved. Use is subject to license terms.
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; version 2 of the License.
8 
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with this program; if not, write to the Free Software
16  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18 
19 #include <ndb_global.h>
20 
21 #include "common.hpp"
22 #include <logger/Logger.hpp>
23 
24 #ifndef _WIN32
25 #include <pwd.h>
26 #endif
27 
28 #include <Properties.hpp>
29 #include <BaseString.hpp>
30 
31 int debug = 0;
32 
33 Logger logger;
34 
35 #ifndef _WIN32
36 int
37 runas(const char * user){
38  if(user == 0 || strlen(user) == 0){
39  return 0;
40  }
41  struct passwd * pw = getpwnam(user);
42  if(pw == 0){
43  logger.error("Can't find user to %s", user);
44  return -1;
45  }
46  uid_t uid = pw->pw_uid;
47  gid_t gid = pw->pw_gid;
48  int res = setgid(gid);
49  if(res != 0){
50  logger.error("Can't change group to %s(%d)", user, gid);
51  return res;
52  }
53 
54  res = setuid(uid);
55  if(res != 0){
56  logger.error("Can't change user to %s(%d)", user, uid);
57  }
58  return res;
59 }
60 #endif
61 
62 int
63 insert(const char * pair, Properties & p){
64  BaseString tmp(pair);
65 
66  tmp.trim(" \t\n\r");
67 
68  Vector<BaseString> split;
69  tmp.split(split, ":=", 2);
70 
71  if(split.size() != 2)
72  return -1;
73 
74  p.put(split[0].trim().c_str(), split[1].trim().c_str());
75 
76  return 0;
77 }
78 
79 int
80 insert_file(FILE * f, class Properties& p, bool break_on_empty){
81  if(f == 0)
82  return -1;
83 
84  while(!feof(f)){
85  char buf[1024];
86  fgets(buf, 1024, f);
87  BaseString tmp = buf;
88 
89  if(tmp.length() > 0 && tmp.c_str()[0] == '#')
90  continue;
91 
92  if(insert(tmp.c_str(), p) != 0 && break_on_empty)
93  break;
94  }
95 
96  return 0;
97 }
98 
99 int
100 insert_file(const char * filename, class Properties& p){
101  FILE * f = fopen(filename, "r");
102  int res = insert_file(f, p);
103  if(f) fclose(f);
104  return res;
105 }