File: DICTClient.cc

package info (click to toggle)
gaspell 0.29.1-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 124 kB
  • ctags: 210
  • sloc: cpp: 1,142; makefile: 68
file content (277 lines) | stat: -rw-r--r-- 7,178 bytes parent folder | download
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
/*
 * File:		DICTClient.cc
 * Version:		0.9
 * History:
 * 01/01/99		First revision.  Created skeleton.
 * 01/04/99		Added methods setHost(), getNumOfMatches()
 * 01/05/99		Added methods getHost(), getPort(), getBook(), getDefinition()
 *				Also rewrote lookup() to use string [] for books and definitions
 * 09/26/99 (kevin)     Name changed to DICTClinet.cc.
 *                      Added utilty for spliting up wordnet definitions
 *                      Added ability to only query for a specific book
 *                      Fixed memory problems, made more C++ish.  
 *                      Will now throw exceptions. And a lot more.
 *
 * Description:	A library to provide dict interface to various programs
 * 
 * Legalese
 * Copyright (C) 1999  Sudhakar Chandrasekharan (thaths@netscape.com)
 * Copyright (C) 1999  Kevin Atkinson (kevinatk@home.com)
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <iostream.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <string>

#include "DICTClient.hh"

// Constructor
DICTClient::DICTClient(const char * h, int p) {
  connected = 0;
  host = h;
  port = p;
}

// Method to reset the server to something else
void DICTClient::setHost(const char * h, int p) {
  if (connected == 1) {
    hangup();	/* Disconnect if already connected */
  }
  host = h;
  port = p;
}

// Method to return the server name
const char * DICTClient::getHost() {
  return host.c_str();
}

// Method to return the server port
int DICTClient::getPort() {
  if (port> 0) {
    return port;
  } else {
    return 0;
  }
}

// Method to connect to the dict server
void DICTClient::dial() {
  struct hostent *ptrh;  /* pointer to a host table entry     */
  struct protoent *ptrp; /* pointer to a protocol table entry */
  struct sockaddr_in sad;/* structure to hold server's address*/
  int    option_value;   /* GPI: needed for setsockopt        */
  
  memset((char *)&sad, 0, sizeof(sad)); /* clear sockaddr structure */
  sad.sin_family = AF_INET;  /* set family to Internet */
  
  /* Test for legal value */
  if (port > 0) {
    sad.sin_port = htons((u_short)port);
  } else {
    /* Print error message and exit */
    throw BadPort(port);
  }
  
  /* Convert host name to equivalent IP address and copy sad */
  ptrh = gethostbyname(host.c_str());
  if (((char *)ptrh) == NULL) {
    throw InvalidHost(getHost());
  }
  memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);
  
  /* Map TCP tranbsport protocol name to protocol number */
  if (((int)(ptrp = getprotobyname("tcp"))) == 0) {
    throw CannotMapTcpToProtocolNumber();
  }
  
  /* Create a socket */
  sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
  if (sd < 0) {
    throw SocketCreationFailed();
  }
  
  /* GPI: Make sure that port used will be immediately reusable */
  option_value = 1;
  if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, 
		 (char *)&option_value, sizeof(option_value)) < 0) {
    throw SetsockoptFailed();
  }
  
  /* Connect the socket to the specified server */
  if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
    throw ConnectFailed();
  }
  connected = 1;
}

// Method to disconnect from the dict server
void DICTClient::hangup() {
  if(connected == 1) {
    close(sd);
    connected = 0;
  }
}

// Method to lookup a word.
DICTClient::Definitions 
DICTClient::lookup(const char * word, const char * book) {
  Definitions definitions;
  char	buf[1024];
  int n=0;
  int count=0;
  
  if(connected != 1) {
    throw NotConnected();
  }
  
  /* Construct the query to send to the server */
  string query = string("DEFINE ") + book + " " + word + "\n\r";
  
  send(sd,query.c_str(),query.size(),0); 
  definitions.clear();
  
  while ((n=readline(sd,buf,sizeof(buf))) > 0) {
    if (strncmp(buf,"42",2) == 0) {
      throw ServerDisconnected();
    }
    
    if (strncmp(buf,"220",3) == 0)
      continue;	/* Ignore successful connection message */
    
    if (strncmp(buf,"250",3) == 0)
      break;		/* break out if completed successfully */
    
    if (strncmp(buf,"150",3) == 0) {
      /* How many matches */
      /* numOfMatches = atoi(buf+3); */
      continue;
    }

    /* Ignore EO each entry from server */
    if (strncmp(buf,".",1) == 0) {
      count++;
      continue;
    }
    
    /* Definition found */
    if (strncmp(buf,"151",3) == 0) {
      definitions.push_back(find_book(buf));
      continue;
    }
    
    /* break out if no matches found */
    if(strncmp(buf,"552",3) == 0) {
      break;
    }
    
    definitions[count].definition.append(buf);
  }
  return definitions;
}

string DICTClient::BadPort::message() const {
  return "Bad port number";
}

string DICTClient::InvalidHost::message() const {
  return "The host " + host_name + " is invalid";
}

/* Function to read one line at a time from socket */
int DICTClient::readline(int sdesc, char *cptr, int maxlen) {
  int i, nc;
  char c;

  for (i=0; i<maxlen; i++) {
    if ((nc = read(sdesc,&c,1)) == 1) {
      *cptr++ = c;
      if (c == '\n') {
	break;
      }
    } else if (nc == 0) {
      if (i == 1)
	return 0;
      else
	break;
    }
  }
  *cptr = '\0';
  return i;
}

string DICTClient::find_book(const char * str) {
  int i=0;
  int j=0;
  string bk;
  bk.resize(strlen(str));
  for (i=0, j=0; i<strlen(str); i++) {
    if (str[i] == '"') {
      if (str[i-1] == ' ') {
	j=0;
      }
      continue;
    } else {
      bk[j] = str[i];
      j++;
    }
  }
  return bk;
}

vector<WordNetDefinition> wordnet_split(const string & in) {
  vector<WordNetDefinition> defs;
  string def_str;
  int n1 = in.find('\n');
  int n2 = in.find('\n', n1+1);
  int n = 0;
  def_str = in.substr(n1+6,n2-1-6-n1);
  for (;;) {
    if (n2 == string::npos) break;
    n1 = n2;
    n2 = in.find('\n', n2 + 1);
    if (in[n1 + 6] != ' ') {
      // split def_str into its parts and add to the list
      WordNetDefinition def;
      n = def_str.find(':');
      def.definition = def_str.substr(n+2);
      int m = def_str.find(' ');
      if (m > n) {
	def.number = def_str.substr(0,n);
      } else {
	def.part_of_speech = def_str.substr(0,m);
	def.number = def_str.substr(m+1, n - m - 1);
      }
      defs.push_back(def);
      def_str = "";
    }
    n = in.find_first_not_of(' ', n1+1);
    if (n == string::npos) break;
    if (def_str.size()) def_str += ' ';
    def_str += in.substr(n,n2-1-n);
  }
  return defs;
}