]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modmanager_dynamic.cpp
Fix compilation due to dirent header
[user/henk/code/inspircd.git] / src / modmanager_dynamic.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "xline.h"
16 #include "socket.h"
17 #include "socketengine.h"
18 #include "command_parse.h"
19 #include "dns.h"
20 #include "exitcodes.h"
21
22 #ifndef WIN32
23 #include <dirent.h>
24 #endif
25
26 #ifndef PURE_STATIC
27
28 bool ModuleManager::Load(const char* filename)
29 {
30         /* Don't allow people to specify paths for modules, it doesn't work as expected */
31         if (strchr(filename, '/'))
32                 return false;
33         /* Do we have a glob pattern in the filename?
34          * The user wants to load multiple modules which
35          * match the pattern.
36          */
37         if (strchr(filename,'*') || (strchr(filename,'?')))
38         {
39                 int n_match = 0;
40                 DIR* library = opendir(ServerInstance->Config->ModPath.c_str());
41                 if (library)
42                 {
43                         /* Try and locate and load all modules matching the pattern */
44                         dirent* entry = NULL;
45                         while (0 != (entry = readdir(library)))
46                         {
47                                 if (InspIRCd::Match(entry->d_name, filename, ascii_case_insensitive_map))
48                                 {
49                                         if (!this->Load(entry->d_name))
50                                                 n_match++;
51                                 }
52                         }
53                         closedir(library);
54                 }
55                 /* Loadmodule will now return false if any one of the modules failed
56                  * to load (but wont abort when it encounters a bad one) and when 1 or
57                  * more modules were actually loaded.
58                  */
59                 return (n_match > 0 ? false : true);
60         }
61
62         char modfile[MAXBUF];
63         snprintf(modfile,MAXBUF,"%s/%s",ServerInstance->Config->ModPath.c_str(),filename);
64         std::string filename_str = filename;
65
66         if (!ServerConfig::FileExists(modfile))
67         {
68                 LastModuleError = "Module file could not be found: " + filename_str;
69                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
70                 return false;
71         }
72
73         if (Modules.find(filename_str) != Modules.end())
74         {
75                 LastModuleError = "Module " + filename_str + " is already loaded, cannot load a module twice!";
76                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
77                 return false;
78         }
79
80         Module* newmod = NULL;
81         DLLManager* newhandle = new DLLManager(modfile);
82
83         try
84         {
85                 newmod = newhandle->callInit();
86
87                 if (newmod)
88                 {
89                         newmod->ModuleSourceFile = filename_str;
90                         newmod->ModuleDLLManager = newhandle;
91                         Version v = newmod->GetVersion();
92
93                         ServerInstance->Logs->Log("MODULE", DEFAULT,"New module introduced: %s (Module version %s)%s",
94                                 filename, v.version.c_str(), (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
95
96                         Modules[filename_str] = newmod;
97                 }
98                 else
99                 {
100                         LastModuleError = "Unable to load " + filename_str + ": " + newhandle->LastError();
101                         ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
102                         delete newhandle;
103                         return false;
104                 }
105         }
106         catch (CoreException& modexcept)
107         {
108                 // failure in module constructor
109                 delete newmod;
110                 delete newhandle;
111                 LastModuleError = "Unable to load " + filename_str + ": " + modexcept.GetReason();
112                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
113                 return false;
114         }
115
116         this->ModCount++;
117         FOREACH_MOD(I_OnLoadModule,OnLoadModule(newmod));
118
119         /* We give every module a chance to re-prioritize when we introduce a new one,
120          * not just the one thats loading, as the new module could affect the preference
121          * of others
122          */
123         for(int tries = 0; tries < 20; tries++)
124         {
125                 prioritizationState = tries > 0 ? PRIO_STATE_LAST : PRIO_STATE_FIRST;
126                 for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
127                         n->second->Prioritize();
128
129                 if (prioritizationState == PRIO_STATE_LAST)
130                         break;
131                 if (tries == 19)
132                         ServerInstance->Logs->Log("MODULE", DEFAULT, "Hook priority dependency loop detected while loading " + filename_str);
133         }
134
135         ServerInstance->BuildISupport();
136         return true;
137 }
138
139 bool ModuleManager::CanUnload(Module* mod)
140 {
141         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
142
143         if (modfind == Modules.end() || modfind->second != mod)
144         {
145                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
146                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
147                 return false;
148         }
149         if (mod->GetVersion().Flags & VF_STATIC)
150         {
151                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
152                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
153                 return false;
154         }
155         std::pair<int,std::string> intercount = GetInterfaceInstanceCount(mod);
156         if (intercount.first > 0)
157         {
158                 LastModuleError = "Failed to unload module " + mod->ModuleSourceFile + ", being used by " + ConvToStr(intercount.first) + " other(s) via interface '" + intercount.second + "'";
159                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
160                 return false;
161         }
162         return true;
163 }
164
165 void ModuleManager::DoSafeUnload(Module* mod)
166 {
167         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
168
169         std::vector<reference<ExtensionItem> > items;
170         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
171         /* Give the module a chance to tidy out all its metadata */
172         for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++)
173         {
174                 mod->OnCleanup(TYPE_CHANNEL,c->second);
175                 c->second->doUnhookExtensions(items);
176                 const UserMembList* users = c->second->GetUsers();
177                 for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
178                         mi->second->doUnhookExtensions(items);
179         }
180         for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++)
181         {
182                 mod->OnCleanup(TYPE_USER,u->second);
183                 u->second->doUnhookExtensions(items);
184         }
185         for(char m='A'; m <= 'z'; m++)
186         {
187                 ModeHandler* mh;
188                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
189                 if (mh && mh->creator == mod)
190                         ServerInstance->Modes->DelMode(mh);
191                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_CHANNEL);
192                 if (mh && mh->creator == mod)
193                         ServerInstance->Modes->DelMode(mh);
194         }
195
196         /* Tidy up any dangling resolvers */
197         ServerInstance->Res->CleanResolvers(mod);
198
199         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(mod));
200
201         DetachAll(mod);
202
203         Modules.erase(modfind);
204         ServerInstance->GlobalCulls.AddItem(mod);
205
206         ServerInstance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",mod->ModuleSourceFile.c_str());
207         this->ModCount--;
208         ServerInstance->BuildISupport();
209 }
210
211 namespace {
212         struct UnloadAction : public HandlerBase0<void>
213         {
214                 Module* const mod;
215                 UnloadAction(Module* m) : mod(m) {}
216                 void Call()
217                 {
218                         DLLManager* dll = mod->ModuleDLLManager;
219                         ServerInstance->Modules->DoSafeUnload(mod);
220                         ServerInstance->GlobalCulls.Apply();
221                         delete dll;
222                         ServerInstance->GlobalCulls.AddItem(this);
223                 }
224         };
225
226         struct ReloadAction : public HandlerBase0<void>
227         {
228                 Module* const mod;
229                 HandlerBase1<void, bool>* const callback;
230                 ReloadAction(Module* m, HandlerBase1<void, bool>* c)
231                         : mod(m), callback(c) {}
232                 void Call()
233                 {
234                         DLLManager* dll = mod->ModuleDLLManager;
235                         std::string name = mod->ModuleSourceFile;
236                         ServerInstance->Modules->DoSafeUnload(mod);
237                         ServerInstance->GlobalCulls.Apply();
238                         delete dll;
239                         bool rv = ServerInstance->Modules->Load(name.c_str());
240                         callback->Call(rv);
241                         ServerInstance->GlobalCulls.AddItem(this);
242                 }
243         };
244 }
245
246 bool ModuleManager::Unload(Module* mod)
247 {
248         if (!CanUnload(mod))
249                 return false;
250         ServerInstance->AtomicActions.AddAction(new UnloadAction(mod));
251         return true;
252 }
253
254 void ModuleManager::Reload(Module* mod, HandlerBase1<void, bool>* callback)
255 {
256         if (CanUnload(mod))
257                 ServerInstance->AtomicActions.AddAction(new ReloadAction(mod, callback));
258         else
259                 callback->Call(false);
260 }
261
262 /* We must load the modules AFTER initializing the socket engine, now */
263 void ModuleManager::LoadAll()
264 {
265         ModCount = 0;
266
267         printf("\nLoading core commands");
268         fflush(stdout);
269
270         DIR* library = opendir(ServerInstance->Config->ModPath.c_str());
271         if (library)
272         {
273                 dirent* entry = NULL;
274                 while (0 != (entry = readdir(library)))
275                 {
276                         if (InspIRCd::Match(entry->d_name, "cmd_*.so", ascii_case_insensitive_map))
277                         {
278                                 printf(".");
279                                 fflush(stdout);
280
281                                 if (!Load(entry->d_name))
282                                 {
283                                         ServerInstance->Logs->Log("MODULE", DEFAULT, this->LastError());
284                                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
285                                         ServerInstance->Exit(EXIT_STATUS_MODULE);
286                                 }
287                         }
288                 }
289                 closedir(library);
290                 printf("\n");
291         }
292
293         ConfigTagList tags = ServerInstance->Config->ConfTags("module");
294         for(ConfigIter i = tags.first; i != tags.second; ++i)
295         {
296                 ConfigTag* tag = i->second;
297                 std::string name = tag->getString("name");
298                 printf_c("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",name.c_str());
299
300                 if (!this->Load(name.c_str()))
301                 {
302                         ServerInstance->Logs->Log("MODULE", DEFAULT, this->LastError());
303                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
304                         ServerInstance->Exit(EXIT_STATUS_MODULE);
305                 }
306         }
307 }
308
309 void ModuleManager::UnloadAll()
310 {
311         /* We do this more than once, so that any service providers get a
312          * chance to be unhooked by the modules using them, but then get
313          * a chance to be removed themsleves.
314          *
315          * Note: this deliberately does NOT delete the DLLManager objects
316          */
317         for (int tries = 0; tries < 4; tries++)
318         {
319                 std::map<std::string, Module*>::iterator i = Modules.begin();
320                 while (i != Modules.end())
321                 {
322                         std::map<std::string, Module*>::iterator me = i++;
323                         if (CanUnload(me->second))
324                         {
325                                 DoSafeUnload(me->second);
326                         }
327                 }
328                 ServerInstance->GlobalCulls.Apply();
329         }
330 }
331
332 #endif