~ubuntu-branches/ubuntu/trusty/arc-gui-clients/trusty

« back to all changes in this revision

Viewing changes to src/common/arcproxy-utils.cpp

  • Committer: Package Import Robot
  • Author(s): Mattias Ellert
  • Date: 2013-05-08 22:45:38 UTC
  • mfrom: (1.1.1)
  • Revision ID: package-import@ubuntu.com-20130508224538-7kfhy97fg7ncfck0
Tags: 0.4.3-1
New release

Show diffs side-by-side

added added

removed removed

Lines of Context:
4
4
#include <fstream>
5
5
#include <string>
6
6
#include <map>
 
7
#include <algorithm>
7
8
#include <stdexcept>
8
9
#include <unistd.h>
9
10
#include <stdlib.h>
15
16
#include <glibmm.h>
16
17
#include <unistd.h>
17
18
 
 
19
#include "arc-gui-config.h"
 
20
 
18
21
#include <arc/ArcLocation.h>
19
22
#include <arc/DateTime.h>
20
23
#include <arc/delegation/DelegationInterface.h>
23
26
#include <arc/User.h>
24
27
#include <arc/Utils.h>
25
28
#include <arc/UserConfig.h>
 
29
#if ARC_VERSION_MAJOR >= 3
 
30
#include <arc/communication/ClientInterface.h>
 
31
#else
26
32
#include <arc/client/ClientInterface.h>
 
33
#endif
27
34
#include <arc/credential/VOMSAttribute.h>
28
35
#include <arc/credential/VOMSUtil.h>
29
36
#include <arc/credential/Credential.h>
42
49
#include <QStyle>
43
50
#include <QDesktopWidget>
44
51
 
45
 
 
46
52
#include "proxywindow.h"
47
53
 
48
54
#undef HAVE_NSS
51
57
#include <arc/credential/NSSUtil.h>
52
58
#endif
53
59
 
 
60
#include "arcproxy-utils-functions.h"
 
61
 
54
62
VomsListEntry::VomsListEntry()
55
63
{
56
64
    m_alias = "";
132
140
    QStringList vomsPaths;
133
141
 
134
142
    vomsPaths << QDir::homePath() + "/.arc/vomses";
135
 
    vomsPaths << QDir::homePath() + "/.voms/vomses";
136
 
    vomsPaths << "/etc/vomses";
137
 
    vomsPaths << "/etc/grid-security/vomses";
 
143
//    vomsPaths << QDir::homePath() + "/.voms/vomses";
 
144
//    vomsPaths << "/etc/vomses";
 
145
//    vomsPaths << "/etc/grid-security/vomses";
138
146
 
139
147
    this->clear();
140
148
 
162
170
                    strippedFields.append(fields[j].replace("\"", ""));
163
171
                }
164
172
 
165
 
                qDebug() << strippedFields;
166
 
 
167
173
                VomsListEntry* entry = new VomsListEntry();
168
174
                entry->setAlias(strippedFields[0]);
169
175
                entry->setMachine(strippedFields[1]);
176
182
            vomsFile.close();
177
183
        }
178
184
    }
 
185
 
 
186
    return true;
179
187
}
180
188
 
181
189
VomsListEntry* VomsList::at(int idx)
191
199
    return m_vomsList.count();
192
200
}
193
201
 
 
202
bool VomsList::write()
 
203
{
 
204
    QString vomsFilename = QDir::homePath() + "/.arc/vomses";
 
205
    QFile vomsFile(vomsFilename);
 
206
    vomsFile.open(QFile::WriteOnly|QFile::Truncate);
 
207
 
 
208
    QTextStream out(&vomsFile);
 
209
 
 
210
    for (int i=0; i<m_vomsList.count(); i++)
 
211
    {
 
212
        out << "\"" << m_vomsList.at(i)->alias() << "\" ";
 
213
        out << "\"" << m_vomsList.at(i)->machine() << "\" ";
 
214
        out << "\"" << m_vomsList.at(i)->port() << "\" ";
 
215
        out << "\"" << m_vomsList.at(i)->hostDN() << "\" ";
 
216
        out << "\"" << m_vomsList.at(i)->officialName() << "\" " << endl;
 
217
    }
 
218
 
 
219
    //out.flush();
 
220
 
 
221
    vomsFile.close();
 
222
 
 
223
    m_vomsList.clear();
 
224
 
 
225
    return true;
 
226
}
 
227
 
194
228
 
195
229
using namespace ArcCredential;
196
230
 
197
 
static int create_proxy_file(const std::string& path) {
198
 
    int f = -1;
199
 
 
200
 
    if((::unlink(path.c_str()) != 0) && (errno != ENOENT)) {
201
 
        throw std::runtime_error("Failed to remove proxy file " + path);
202
 
    }
203
 
    f = ::open(path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR);
204
 
    if (f == -1) {
205
 
        throw std::runtime_error("Failed to create proxy file " + path);
206
 
    }
207
 
    if(::chmod(path.c_str(), S_IRUSR | S_IWUSR) != 0) {
208
 
        ::unlink(path.c_str());
209
 
        ::close(f);
210
 
        throw std::runtime_error("Failed to change permissions of proxy file " + path);
211
 
    }
212
 
    return f;
213
 
}
214
 
 
215
 
static void write_proxy_file(const std::string& path, const std::string& content) {
216
 
    std::string::size_type off = 0;
217
 
    int f = create_proxy_file(path);
218
 
    while(off < content.length()) {
219
 
        ssize_t l = ::write(f, content.c_str(), content.length()-off);
220
 
        if(l < 0) {
221
 
            ::unlink(path.c_str());
222
 
            ::close(f);
223
 
            throw std::runtime_error("Failed to write into proxy file " + path);
224
 
        }
225
 
        off += (std::string::size_type)l;
226
 
    }
227
 
    ::close(f);
228
 
}
229
 
 
230
 
static void remove_proxy_file(const std::string& path) {
231
 
    if((::unlink(path.c_str()) != 0) && (errno != ENOENT)) {
232
 
        throw std::runtime_error("Failed to remove proxy file " + path);
233
 
    }
234
 
}
235
 
 
236
 
static void tls_process_error(Arc::Logger& logger) {
237
 
    unsigned long err;
238
 
    err = ERR_get_error();
239
 
    if (err != 0) {
240
 
        logger.msg(Arc::ERROR, "OpenSSL error -- %s", ERR_error_string(err, NULL));
241
 
        logger.msg(Arc::ERROR, "Library  : %s", ERR_lib_error_string(err));
242
 
        logger.msg(Arc::ERROR, "Function : %s", ERR_func_error_string(err));
243
 
        logger.msg(Arc::ERROR, "Reason   : %s", ERR_reason_error_string(err));
244
 
    }
245
 
    return;
246
 
}
247
 
 
248
 
#define PASS_MIN_LENGTH (0)
249
 
static int input_password(char *password, int passwdsz, bool verify,
250
 
                          const std::string& prompt_m_info,
251
 
                          const std::string& prompt_verify_m_info,
252
 
                          Arc::Logger& logger) {
253
 
    UI *ui = NULL;
254
 
    int res = 0;
255
 
    ui = UI_new();
256
 
    if (ui) {
257
 
        int ok = 0;
258
 
        char* buf = new char[passwdsz];
259
 
        memset(buf, 0, passwdsz);
260
 
        int ui_flags = 0;
261
 
        char *prompt1 = NULL;
262
 
        char *prompt2 = NULL;
263
 
        prompt1 = UI_construct_prompt(ui, "passphrase", prompt_m_info.c_str());
264
 
        prompt2 = UI_construct_prompt(ui, "passphrase", prompt_verify_m_info.c_str());
265
 
        ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
266
 
        UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
267
 
        ok = UI_add_input_string(ui, prompt1, ui_flags, password,
268
 
                                 PASS_MIN_LENGTH, passwdsz - 1);
269
 
        if (ok >= 0 && verify) {
270
 
            ok = UI_add_verify_string(ui, prompt2, ui_flags, buf,
271
 
                                      PASS_MIN_LENGTH, passwdsz - 1, password);
272
 
        }
273
 
        if (ok >= 0) {
274
 
            do {
275
 
                ok = UI_process(ui);
276
 
            } while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
277
 
        }
278
 
 
279
 
        if (ok >= 0) res = strlen(password);
280
 
        if (ok == -1) {
281
 
            logger.msg(Arc::ERROR, "User interface error");
282
 
            tls_process_error(logger);
283
 
            memset(password, 0, (unsigned int)passwdsz);
284
 
            res = 0;
285
 
        }
286
 
        if (ok == -2) {
287
 
            logger.msg(Arc::ERROR, "Aborted!");
288
 
            memset(password, 0, (unsigned int)passwdsz);
289
 
            res = 0;
290
 
        }
291
 
        UI_free(ui);
292
 
        delete[] buf;
293
 
        OPENSSL_free(prompt1);
294
 
        OPENSSL_free(prompt2);
295
 
    }
296
 
    return res;
297
 
}
298
 
 
299
 
static bool is_file(std::string path) {
300
 
    if (Glib::file_test(path, Glib::FILE_TEST_IS_REGULAR))
301
 
        return true;
302
 
    return false;
303
 
}
304
 
 
305
 
static bool is_dir(std::string path) {
306
 
    if (Glib::file_test(path, Glib::FILE_TEST_IS_DIR))
307
 
        return true;
308
 
    return false;
309
 
}
310
 
 
311
 
static std::vector<std::string> search_vomses(std::string path) {
312
 
    std::vector<std::string> vomses_files;
313
 
    if(is_file(path)) vomses_files.push_back(path);
314
 
    else if(is_dir(path)) {
315
 
        //if the path 'vomses' is a directory, search all of the files under this directory,
316
 
        //i.e.,  'vomses/voA'  'vomses/voB'
317
 
        std::string path_header = path;
318
 
        std::string fullpath;
319
 
        Glib::Dir dir(path);
320
 
        for(Glib::Dir::iterator i = dir.begin(); i != dir.end(); i++ ) {
321
 
            fullpath = path_header + G_DIR_SEPARATOR_S + *i;
322
 
            if(is_file(fullpath)) vomses_files.push_back(fullpath);
323
 
            else if(is_dir(fullpath)) {
324
 
                std::string sub_path = fullpath;
325
 
                //if the path is a directory, search the all of the files under this directory,
326
 
                //i.e., 'vomses/extra/myprivatevo'
327
 
                Glib::Dir subdir(sub_path);
328
 
                for(Glib::Dir::iterator j = subdir.begin(); j != subdir.end(); j++ ) {
329
 
                    fullpath = sub_path + G_DIR_SEPARATOR_S + *j;
330
 
                    if(is_file(fullpath)) vomses_files.push_back(fullpath);
331
 
                    //else if(is_dir(fullpath)) { //if it is again a directory, the files under it will be ignored }
332
 
                }
333
 
            }
334
 
        }
335
 
    }
336
 
    return vomses_files;
337
 
}
338
 
 
339
 
static std::string tokens_to_string(std::vector<std::string> tokens) {
340
 
    std::string s;
341
 
    for(int n = 0; n<tokens.size(); ++n) {
342
 
        s += "\""+tokens[n]+"\" ";
343
 
    };
344
 
    return s;
345
 
}
346
 
 
347
231
ArcProxyController::ArcProxyController()
348
232
    :logger(Arc::Logger::getRootLogger(), "arcproxy"), logCerr(std::cerr)
349
233
{
350
234
    setlocale(LC_ALL, "");
351
235
 
352
 
    m_use_gsi_comm = false;
353
 
    m_use_gsi_proxy = false;
354
 
    m_info = false;
355
 
    m_remove_proxy = false;
356
 
    m_use_empty_passphrase = false; //if use empty passphrase to myproxy server
357
 
    m_timeout = -1;
358
 
    m_version = false;
359
 
    m_use_http_comm = false;
 
236
    use_gsi_comm = false;
 
237
    use_gsi_proxy = false;
 
238
    info = false;
 
239
    remove_proxy = false;
 
240
    use_empty_passphrase = false; //if use empty passphrase to myproxy server
 
241
    timeout = -1;
 
242
    version = false;
 
243
    use_http_comm = false;
360
244
 
361
 
    m_debug = "WARNING";
 
245
    debug = "WARNING";
362
246
 
363
247
    // This ensure command line args overwrite all other options
364
 
    if(!m_cert_path.empty())Arc::SetEnv("X509_USER_CERT", m_cert_path);
365
 
    if(!m_key_path.empty())Arc::SetEnv("X509_USER_KEY", m_key_path);
366
 
    if(!m_proxy_path.empty())Arc::SetEnv("X509_USER_PROXY", m_proxy_path);
367
 
    if(!m_ca_dir.empty())Arc::SetEnv("X509_CERT_DIR", m_ca_dir);
 
248
    if(!cert_path.empty())Arc::SetEnv("X509_USER_CERT", cert_path);
 
249
    if(!key_path.empty())Arc::SetEnv("X509_USER_KEY", key_path);
 
250
    if(!proxy_path.empty())Arc::SetEnv("X509_USER_PROXY", proxy_path);
 
251
    if(!ca_dir.empty())Arc::SetEnv("X509_CERT_DIR", ca_dir);
368
252
 
369
253
    m_proxyWindow = 0;
370
254
    m_application = 0;
407
291
 
408
292
void ArcProxyController::setUseGSIProxy(bool flag)
409
293
{
410
 
    m_use_gsi_proxy = flag;
 
294
    use_gsi_proxy = flag;
411
295
}
412
296
 
413
297
bool ArcProxyController::getUseGSIProxy()
414
298
{
415
 
    return m_use_gsi_proxy;
416
 
}
 
299
    return use_gsi_proxy;
 
300
}
 
301
 
 
302
void ArcProxyController::addVomsServerAndRole(const QString& serverAndRole)
 
303
{
 
304
    std::string serverLine = serverAndRole.toStdString();
 
305
    vomslist.push_back(serverLine);
 
306
}
 
307
 
 
308
void ArcProxyController::addVomsServer(const QString& server, const QString& role)
 
309
{
 
310
    std::string serverLine;
 
311
 
 
312
    if (role.length()!=0)
 
313
        serverLine = server.toStdString() + ":/" + role.toStdString();
 
314
    else
 
315
        serverLine = server.toStdString();
 
316
 
 
317
    vomslist.push_back(serverLine);
 
318
}
 
319
 
 
320
void ArcProxyController::removeVomsServer(const QString& server, const QString& role)
 
321
{
 
322
    std::string serverLine;
 
323
 
 
324
    if (role.length()!=0)
 
325
        serverLine = server.toStdString() + ":/" + role.toStdString();
 
326
    else
 
327
        serverLine = server.toStdString();
 
328
 
 
329
    std::vector<std::string>::iterator it;
 
330
 
 
331
    it = find(vomslist.begin(), vomslist.end(), serverLine);
 
332
 
 
333
    if (it!=vomslist.end())
 
334
        vomslist.erase(it);
 
335
}
 
336
 
 
337
QString ArcProxyController::getVomsServer(int idx)
 
338
{
 
339
    QString returnString = vomslist[idx].c_str();
 
340
    return returnString;
 
341
}
 
342
 
 
343
int ArcProxyController::vomsServerCount()
 
344
{
 
345
    return vomslist.size();
 
346
}
 
347
 
417
348
 
418
349
ArcProxyController::TCertStatus ArcProxyController::checkCert()
419
350
{
420
351
    Arc::ArcLocation::Init("");
421
352
 
422
 
    Arc::UserConfig usercfg(m_conffile,
 
353
    Arc::UserConfig usercfg(conffile,
423
354
                            Arc::initializeCredentialsType(Arc::initializeCredentialsType::TryCredentials));
424
355
    if (!usercfg) {
425
356
        return CS_INVALID_CONFIG;
427
358
    // Check for needed credentials objects
428
359
    // Can proxy be used for? Could not find it in documentation.
429
360
    // Key and certificate not needed if only printing proxy information
430
 
    if((usercfg.CertificatePath().empty() || (usercfg.KeyPath().empty() && (usercfg.CertificatePath().find(".p12") == std::string::npos))) && !m_info) {
 
361
    if((usercfg.CertificatePath().empty() || (usercfg.KeyPath().empty() && (usercfg.CertificatePath().find(".p12") == std::string::npos))) && !info) {
431
362
        return CS_NOT_FOUND;
432
363
    }
433
 
    if(!m_vomslist.empty() || !m_myproxy_command.empty()) {
 
364
    if(!vomslist.empty() || !myproxy_command.empty()) {
434
365
        // For external communication CAs are needed
435
366
        if(usercfg.CACertificatesDirectory().empty()) {
436
367
            logger.msg(Arc::ERROR, "Failed to find CA certificates");
454
385
    return m_uiReturnStatus;
455
386
}
456
387
 
457
 
void ArcProxyController::showProxyUIAppLoop()
 
388
void ArcProxyController::showProxyUIAppLoop(int& argc, char** argv)
458
389
{
459
 
    m_application = new QApplication(0,0,0);
 
390
    m_application = new QApplication(argc, argv);
460
391
    this->showProxyUI();
461
 
    m_application->exec();
462
392
}
463
393
 
464
394
 
465
395
int ArcProxyController::initialize()
466
396
{
467
 
    /*
468
 
    Arc::Logger::getRootLogger().removeDestinations();
469
 
    Arc::Logger::getRootLogger().addDestination(logCerr);
470
 
    Arc::Logger::getRootLogger().setThreshold(Arc::WARNING);
471
 
    */
472
397
    logCerr.setFormat(Arc::ShortFormat);
473
398
 
474
399
    Arc::ArcLocation::Init("");
475
400
 
476
401
#ifdef HAVE_NSS
477
402
    //Using nss db dominate other option
478
 
    if(m_use_nssdb) {
 
403
    if(use_nssdb) {
479
404
        std::string nssdb_path = get_nssdb_path();
480
405
        if(nssdb_path.empty()) {
481
406
            std::cout << Arc::IString("The nss db can not be detected under firefox profile") << std::endl;
486
411
        res = AuthN::nssInit(configdir);
487
412
        std::cout<< Arc::IString("nss db to be accesses: %s\n", configdir.c_str());
488
413
 
489
 
        char* slotpw = NULL; //"secretpw";  //TODO: Input passphrase to nss db
 
414
        char* slotpw = NULL; //"secretpw";
490
415
        //The nss db under firefox profile seems to not be protected by any passphrase by default
491
416
        bool ascii = true;
492
417
        const char* trusts = "p,p,p";
536
461
        proxy_cred_str.append(proxy_privk_str).append(eec_cert_str);
537
462
        write_proxy_file(proxy_path, proxy_cred_str);
538
463
 
539
 
        Arc::Credential proxy_cred(proxy_path, proxy_path, "", "");
540
 
        Arc::Time left = proxy_cred.GetEndTime();
541
 
        std::cout << Arc::IString("Proxy generation succeeded") << std::endl;
542
 
        std::cout << Arc::IString("Your proxy is valid until: %s", left.str(Arc::UserTime)) << std::endl;
543
 
 
544
464
        return EXIT_SUCCESS;
545
465
    }
546
466
#endif
547
467
 
548
468
    // If debug is specified as argument, it should be set before loading the configuration.
 
469
    if (!debug.empty())
 
470
        Arc::Logger::getRootLogger().setThreshold(Arc::string_to_level(debug));
549
471
 
550
 
    if (!m_debug.empty())
551
 
        Arc::Logger::getRootLogger().setThreshold(Arc::string_to_level(m_debug));
 
472
    // This ensure command line args overwrite all other options
 
473
    if(!cert_path.empty())Arc::SetEnv("X509_USER_CERT", cert_path);
 
474
    if(!key_path.empty())Arc::SetEnv("X509_USER_KEY", key_path);
 
475
    if(!proxy_path.empty())Arc::SetEnv("X509_USER_PROXY", proxy_path);
 
476
    if(!ca_dir.empty())Arc::SetEnv("X509_CERT_DIR", ca_dir);
552
477
 
553
478
    // Set default, predefined or guessed credentials. Also check if they exist.
554
 
 
555
 
    Arc::UserConfig usercfg(m_conffile,
 
479
    Arc::UserConfig usercfg(conffile,
556
480
                            Arc::initializeCredentialsType(Arc::initializeCredentialsType::TryCredentials));
557
481
    if (!usercfg) {
558
482
        logger.msg(Arc::ERROR, "Failed configuration initialization.");
561
485
    // Check for needed credentials objects
562
486
    // Can proxy be used for? Could not find it in documentation.
563
487
    // Key and certificate not needed if only printing proxy information
564
 
    if((usercfg.CertificatePath().empty() || (usercfg.KeyPath().empty() && (usercfg.CertificatePath().find(".p12") == std::string::npos))) && !m_info) {
 
488
    if((usercfg.CertificatePath().empty() || (usercfg.KeyPath().empty() && (usercfg.CertificatePath().find(".p12") == std::string::npos))) && !info) {
565
489
        logger.msg(Arc::ERROR, "Failed to find certificate and/or private key or files have improper permissions or ownership.");
566
490
        logger.msg(Arc::ERROR, "You may try to increase verbosity to get more information.");
567
491
        return EXIT_FAILURE;
568
492
    }
569
 
    if(!m_vomslist.empty() || !m_myproxy_command.empty()) {
 
493
    if(!vomslist.empty() || !myproxy_command.empty()) {
570
494
        // For external communication CAs are needed
571
495
        if(usercfg.CACertificatesDirectory().empty()) {
572
496
            logger.msg(Arc::ERROR, "Failed to find CA certificates");
584
508
    // By running credentials initialization once more all set values
585
509
    // won't change. But proxy will get default value if not set.
586
510
    {
587
 
        Arc::UserConfig tmpcfg(m_conffile,
 
511
        Arc::UserConfig tmpcfg(conffile,
588
512
                               Arc::initializeCredentialsType(Arc::initializeCredentialsType::NotTryCredentials));
589
 
        if(m_proxy_path.empty()) m_proxy_path = tmpcfg.ProxyPath();
590
 
        usercfg.ProxyPath(m_proxy_path);
 
513
        if(proxy_path.empty()) proxy_path = tmpcfg.ProxyPath();
 
514
        usercfg.ProxyPath(proxy_path);
591
515
    }
592
516
    // Get back all paths
593
 
    if(m_key_path.empty()) m_key_path = usercfg.KeyPath();
594
 
    if(m_cert_path.empty()) m_cert_path = usercfg.CertificatePath();
595
 
    if(m_ca_dir.empty()) m_ca_dir = usercfg.CACertificatesDirectory();
596
 
    if(m_voms_dir.empty()) m_voms_dir = Arc::GetEnv("X509_VOMS_DIR");
 
517
    if(key_path.empty()) key_path = usercfg.KeyPath();
 
518
    if(cert_path.empty()) cert_path = usercfg.CertificatePath();
 
519
    if(ca_dir.empty()) ca_dir = usercfg.CACertificatesDirectory();
 
520
    if(voms_dir.empty()) voms_dir = Arc::GetEnv("X509_VOMS_DIR");
597
521
 
598
 
    if (m_debug.empty() && !usercfg.Verbosity().empty())
 
522
    if (debug.empty() && !usercfg.Verbosity().empty())
599
523
        Arc::Logger::getRootLogger().setThreshold(Arc::string_to_level(usercfg.Verbosity()));
600
524
 
601
 
    if (m_timeout > 0) usercfg.Timeout(m_timeout);
 
525
    if (timeout > 0) usercfg.Timeout(timeout);
 
526
 
 
527
    return EXIT_SUCCESS;
602
528
}
603
529
 
604
530
QString ArcProxyController::getIdentity()
605
531
{
606
532
    QString identity;
607
533
 
608
 
    Arc::Credential cred(m_cert_path, "", "", "");
 
534
    Arc::Credential cred(cert_path, "", "", "");
609
535
 
610
536
    identity = cred.GetDN().c_str();
611
537
    return identity;
618
544
    out << "validityPeriod=" << seconds;
619
545
    constraintString = out.str();
620
546
 
621
 
    m_constraintlist.clear();
622
 
    m_constraintlist.push_back(constraintString);
 
547
    constraintlist.clear();
 
548
    constraintlist.push_back(constraintString);
623
549
}
624
550
 
625
551
ArcProxyController::TProxyStatus ArcProxyController::checkProxy()
626
552
{
627
553
    const Arc::Time now;
628
554
 
629
 
    if (m_proxy_path.empty()) {
 
555
    if (proxy_path.empty()) {
630
556
        return PS_PATH_EMPTY;
631
557
    }
632
 
    else if (!(Glib::file_test(m_proxy_path, Glib::FILE_TEST_EXISTS))) {
 
558
    else if (!(Glib::file_test(proxy_path, Glib::FILE_TEST_EXISTS))) {
633
559
        return PS_NOT_FOUND;
634
560
    }
635
561
 
636
 
    Arc::Credential holder(m_proxy_path, "", "", "");
 
562
    Arc::Credential holder(proxy_path, "", "", "");
637
563
 
638
564
    if (holder.GetEndTime() < now)
639
565
    {
653
579
int ArcProxyController::printInformation()
654
580
{
655
581
    const Arc::Time now;
 
582
 
656
583
    std::vector<Arc::VOMSACInfo> voms_attributes;
657
584
    bool res = false;
658
585
 
659
 
    if (m_proxy_path.empty()) {
 
586
    if (proxy_path.empty()) {
660
587
        logger.msg(Arc::ERROR, "Cannot find the path of the proxy file, "
661
588
                   "please setup environment X509_USER_PROXY, "
662
589
                   "or proxypath in a configuration file");
663
590
        return EXIT_FAILURE;
664
591
    }
665
 
    else if (!(Glib::file_test(m_proxy_path, Glib::FILE_TEST_EXISTS))) {
 
592
    else if (!(Glib::file_test(proxy_path, Glib::FILE_TEST_EXISTS))) {
666
593
        logger.msg(Arc::ERROR, "Cannot find file at %s for getting the proxy. "
667
 
                   "Please make sure this file exists.", m_proxy_path);
 
594
                   "Please make sure this file exists.", proxy_path);
668
595
        return EXIT_FAILURE;
669
596
    }
670
597
 
671
 
    Arc::Credential holder(m_proxy_path, "", "", "");
 
598
    Arc::Credential holder(proxy_path, "", "", "");
672
599
    std::cout << Arc::IString("Subject: %s", holder.GetDN()) << std::endl;
673
600
    std::cout << Arc::IString("Issuer: %s", holder.GetIssuerName()) << std::endl;
674
601
    std::cout << Arc::IString("Identity: %s", holder.GetIdentityName()) << std::endl;
678
605
        std::cout << Arc::IString("Time left for proxy: Proxy not valid yet") << std::endl;
679
606
    else
680
607
        std::cout << Arc::IString("Time left for proxy: %s", (holder.GetEndTime() - now).istr()) << std::endl;
681
 
    std::cout << Arc::IString("Proxy path: %s", m_proxy_path) << std::endl;
 
608
    std::cout << Arc::IString("Proxy path: %s", proxy_path) << std::endl;
682
609
    std::cout << Arc::IString("Proxy type: %s", certTypeToString(holder.GetType())) << std::endl;
683
610
 
684
611
    Arc::VOMSTrustList voms_trust_dn;
685
612
    voms_trust_dn.AddRegex(".*");
686
 
    res = parseVOMSAC(holder, m_ca_dir, "", m_voms_dir, voms_trust_dn, voms_attributes, true, true);
 
613
    res = parseVOMSAC(holder, ca_dir, "", voms_dir, voms_trust_dn, voms_attributes, true, true);
687
614
    // Not printing error message because parseVOMSAC will print everything itself
688
615
    //if (!res) logger.msg(Arc::ERROR, "VOMS attribute parsing failed");
689
616
    for(int n = 0; n<voms_attributes.size(); ++n) {
766
693
 
767
694
int ArcProxyController::removeProxy()
768
695
{
769
 
    if (m_proxy_path.empty()) {
 
696
    if (proxy_path.empty()) {
770
697
        logger.msg(Arc::ERROR, "Cannot find the path of the proxy file, "
771
698
                   "please setup environment X509_USER_PROXY, "
772
699
                   "or proxypath in a configuration file");
773
700
        return EXIT_FAILURE;
774
 
    } else if (!(Glib::file_test(m_proxy_path, Glib::FILE_TEST_EXISTS))) {
775
 
        logger.msg(Arc::ERROR, "Cannot remove proxy file at %s, because it's not there", m_proxy_path);
 
701
    } else if (!(Glib::file_test(proxy_path, Glib::FILE_TEST_EXISTS))) {
 
702
        logger.msg(Arc::ERROR, "Cannot remove proxy file at %s, because it's not there", proxy_path);
776
703
        return EXIT_FAILURE;
777
704
    }
778
 
    if((unlink(m_proxy_path.c_str()) != 0) && (errno != ENOENT)) {
779
 
        logger.msg(Arc::ERROR, "Cannot remove proxy file at %s", m_proxy_path);
 
705
    if((unlink(proxy_path.c_str()) != 0) && (errno != ENOENT)) {
 
706
        logger.msg(Arc::ERROR, "Cannot remove proxy file at %s", proxy_path);
780
707
        return EXIT_FAILURE;
781
708
    }
782
709
    return EXIT_SUCCESS;
784
711
 
785
712
int ArcProxyController::generateProxy()
786
713
{
787
 
    Arc::UserConfig usercfg("", Arc::initializeCredentialsType( Arc::initializeCredentialsType::TryCredentials));
788
 
 
789
 
    if (!usercfg) {
790
 
        logger.msg(Arc::ERROR, "Failed configuration initialization");
791
 
        return EXIT_FAILURE;
792
 
    }
793
714
 
794
715
    const Arc::Time now;
795
 
    Arc::User user;
796
716
 
797
 
    if ((m_cert_path.empty() || m_key_path.empty()) &&
798
 
            ((m_myproxy_command == "PUT") || (m_myproxy_command == "put") || (m_myproxy_command == "Put"))) {
799
 
        if (m_cert_path.empty())
 
717
    if ((cert_path.empty() || key_path.empty()) &&
 
718
            ((myproxy_command == "PUT") || (myproxy_command == "put") || (myproxy_command == "Put"))) {
 
719
        if (cert_path.empty())
800
720
            logger.msg(Arc::ERROR, "Cannot find the user certificate path, "
801
721
                       "please setup environment X509_USER_CERT, "
802
722
                       "or certificatepath in a configuration file");
803
 
        if (m_key_path.empty())
 
723
        if (key_path.empty())
804
724
            logger.msg(Arc::ERROR, "Cannot find the user private key path, "
805
725
                       "please setup environment X509_USER_KEY, "
806
726
                       "or keypath in a configuration file");
807
727
        return EXIT_FAILURE;
808
728
    }
809
729
 
 
730
    Arc::UserConfig usercfg(conffile,
 
731
          Arc::initializeCredentialsType(Arc::initializeCredentialsType::SkipCredentials));
 
732
    if (!usercfg) {
 
733
      logger.msg(Arc::ERROR, "Failed configuration initialization.");
 
734
      return EXIT_FAILURE;
 
735
    }
 
736
 
810
737
    std::map<std::string, std::string> constraints;
811
 
    for (std::list<std::string>::iterator it = m_constraintlist.begin();
812
 
         it != m_constraintlist.end(); it++) {
 
738
    for (std::list<std::string>::iterator it = constraintlist.begin();
 
739
         it != constraintlist.end(); it++) {
813
740
        std::string::size_type pos = it->find('=');
814
741
        if (pos != std::string::npos)
815
742
            constraints[it->substr(0, pos)] = it->substr(pos + 1);
824
751
    // TODO: Is default validityPeriod since now or since validityStart?
825
752
    Arc::Time validityStart = now; // now by default
826
753
    Arc::Period validityPeriod(12*60*60);
827
 
    if (m_myproxy_command == "put" || m_myproxy_command == "PUT" || m_myproxy_command == "Put") {
 
754
    if (myproxy_command == "put" || myproxy_command == "PUT" || myproxy_command == "Put") {
828
755
        //For myproxy PUT operation, the proxy should be 7 days according to the default
829
756
        //definition in myproxy implementation.
830
757
        validityPeriod = 7*24*60*60;
920
847
    //information about the existence of stored credentials
921
848
    //on the myproxy server.
922
849
    try {
923
 
        if (m_myproxy_command == "info" || m_myproxy_command == "INFO" || m_myproxy_command == "Info") {
924
 
            if (m_myproxy_server.empty())
 
850
        if (myproxy_command == "info" || myproxy_command == "INFO" || myproxy_command == "Info") {
 
851
            if (myproxy_server.empty())
925
852
                throw std::invalid_argument("URL of MyProxy server is missing");
926
853
 
927
 
            if(m_user_name.empty()) {
928
 
                Arc::Credential proxy_cred(m_proxy_path, "", "", "");
 
854
            if(user_name.empty()) {
 
855
                Arc::Credential proxy_cred(proxy_path, "", "", "");
929
856
                std::string cert_dn = proxy_cred.GetIdentityName();
930
 
                m_user_name = cert_dn;
 
857
                user_name = cert_dn;
931
858
            }
932
 
            if (m_user_name.empty())
 
859
            if (user_name.empty())
933
860
                throw std::invalid_argument("Username to MyProxy server is missing");
934
861
 
935
862
            std::string respinfo;
936
863
 
937
864
            //if(usercfg.CertificatePath().empty()) usercfg.CertificatePath(cert_path);
938
865
            //if(usercfg.KeyPath().empty()) usercfg.KeyPath(key_path);
939
 
            if(usercfg.ProxyPath().empty() && !m_proxy_path.empty()) usercfg.ProxyPath(m_proxy_path);
 
866
            if(usercfg.ProxyPath().empty() && !proxy_path.empty()) usercfg.ProxyPath(proxy_path);
940
867
            else {
941
 
                if(usercfg.CertificatePath().empty() && !m_cert_path.empty()) usercfg.CertificatePath(m_cert_path);
942
 
                if(usercfg.KeyPath().empty() && !m_key_path.empty()) usercfg.KeyPath(m_key_path);
 
868
                if(usercfg.CertificatePath().empty() && !cert_path.empty()) usercfg.CertificatePath(cert_path);
 
869
                if(usercfg.KeyPath().empty() && !key_path.empty()) usercfg.KeyPath(key_path);
943
870
            }
944
 
            if(usercfg.CACertificatesDirectory().empty()) usercfg.CACertificatesDirectory(m_ca_dir);
 
871
            if(usercfg.CACertificatesDirectory().empty()) usercfg.CACertificatesDirectory(ca_dir);
945
872
 
946
 
            Arc::CredentialStore cstore(usercfg,Arc::URL("myproxy://"+m_myproxy_server));
 
873
            Arc::CredentialStore cstore(usercfg,Arc::URL("myproxy://"+myproxy_server));
947
874
            std::map<std::string,std::string> myproxyopt;
948
 
            myproxyopt["username"] = m_user_name;
 
875
            myproxyopt["username"] = user_name;
949
876
            if(!cstore.Info(myproxyopt,respinfo))
950
877
                throw std::invalid_argument("Failed to get info from MyProxy service");
951
878
 
964
891
    //information about the existence of stored credentials
965
892
    //on the myproxy server.
966
893
    try {
967
 
        if (m_myproxy_command == "newpass" || m_myproxy_command == "NEWPASS" || m_myproxy_command == "Newpass" || m_myproxy_command == "NewPass") {
968
 
            if (m_myproxy_server.empty())
 
894
        if (myproxy_command == "newpass" || myproxy_command == "NEWPASS" || myproxy_command == "Newpass" || myproxy_command == "NewPass") {
 
895
            if (myproxy_server.empty())
969
896
                throw std::invalid_argument("URL of MyProxy server is missing");
970
897
 
971
 
            if(m_user_name.empty()) {
972
 
                Arc::Credential proxy_cred(m_proxy_path, "", "", "");
 
898
            if(user_name.empty()) {
 
899
                Arc::Credential proxy_cred(proxy_path, "", "", "");
973
900
                std::string cert_dn = proxy_cred.GetIdentityName();
974
 
                m_user_name = cert_dn;
 
901
                user_name = cert_dn;
975
902
            }
976
 
            if (m_user_name.empty())
 
903
            if (user_name.empty())
977
904
                throw std::invalid_argument("Username to MyProxy server is missing");
978
905
 
979
906
            std::string prompt1 = "MyProxy server";
992
919
                throw std::invalid_argument("Error entering passphrase");
993
920
            newpassphrase = newpassword;
994
921
 
995
 
            if(usercfg.ProxyPath().empty() && !m_proxy_path.empty()) usercfg.ProxyPath(m_proxy_path);
 
922
            if(usercfg.ProxyPath().empty() && !proxy_path.empty()) usercfg.ProxyPath(proxy_path);
996
923
            else {
997
 
                if(usercfg.CertificatePath().empty() && !m_cert_path.empty()) usercfg.CertificatePath(m_cert_path);
998
 
                if(usercfg.KeyPath().empty() && !m_key_path.empty()) usercfg.KeyPath(m_key_path);
 
924
                if(usercfg.CertificatePath().empty() && !cert_path.empty()) usercfg.CertificatePath(cert_path);
 
925
                if(usercfg.KeyPath().empty() && !key_path.empty()) usercfg.KeyPath(key_path);
999
926
            }
1000
 
            if(usercfg.CACertificatesDirectory().empty()) usercfg.CACertificatesDirectory(m_ca_dir);
 
927
            if(usercfg.CACertificatesDirectory().empty()) usercfg.CACertificatesDirectory(ca_dir);
1001
928
 
1002
 
            Arc::CredentialStore cstore(usercfg,Arc::URL("myproxy://"+m_myproxy_server));
 
929
            Arc::CredentialStore cstore(usercfg,Arc::URL("myproxy://"+myproxy_server));
1003
930
            std::map<std::string,std::string> myproxyopt;
1004
 
            myproxyopt["username"] = m_user_name;
 
931
            myproxyopt["username"] = user_name;
1005
932
            myproxyopt["password"] = passphrase;
1006
933
            myproxyopt["newpassword"] = newpassphrase;
1007
934
            if(!cstore.ChangePassword(myproxyopt))
1022
949
    //information about the existence of stored credentials
1023
950
    //on the myproxy server.
1024
951
    try {
1025
 
        if (m_myproxy_command == "destroy" || m_myproxy_command == "DESTROY" || m_myproxy_command == "Destroy") {
1026
 
            if (m_myproxy_server.empty())
 
952
        if (myproxy_command == "destroy" || myproxy_command == "DESTROY" || myproxy_command == "Destroy") {
 
953
            if (myproxy_server.empty())
1027
954
                throw std::invalid_argument("URL of MyProxy server is missing");
1028
955
 
1029
 
            if(m_user_name.empty()) {
1030
 
                Arc::Credential proxy_cred(m_proxy_path, "", "", "");
 
956
            if(user_name.empty()) {
 
957
                Arc::Credential proxy_cred(proxy_path, "", "", "");
1031
958
                std::string cert_dn = proxy_cred.GetIdentityName();
1032
 
                m_user_name = cert_dn;
 
959
                user_name = cert_dn;
1033
960
            }
1034
 
            if (m_user_name.empty())
 
961
            if (user_name.empty())
1035
962
                throw std::invalid_argument("Username to MyProxy server is missing");
1036
963
 
1037
964
            std::string prompt1 = "MyProxy server";
1044
971
 
1045
972
            std::string respinfo;
1046
973
 
1047
 
            if(usercfg.ProxyPath().empty() && !m_proxy_path.empty()) usercfg.ProxyPath(m_proxy_path);
 
974
            if(usercfg.ProxyPath().empty() && !proxy_path.empty()) usercfg.ProxyPath(proxy_path);
1048
975
            else {
1049
 
                if(usercfg.CertificatePath().empty() && !m_cert_path.empty()) usercfg.CertificatePath(m_cert_path);
1050
 
                if(usercfg.KeyPath().empty() && !m_key_path.empty()) usercfg.KeyPath(m_key_path);
 
976
                if(usercfg.CertificatePath().empty() && !cert_path.empty()) usercfg.CertificatePath(cert_path);
 
977
                if(usercfg.KeyPath().empty() && !key_path.empty()) usercfg.KeyPath(key_path);
1051
978
            }
1052
 
            if(usercfg.CACertificatesDirectory().empty()) usercfg.CACertificatesDirectory(m_ca_dir);
 
979
            if(usercfg.CACertificatesDirectory().empty()) usercfg.CACertificatesDirectory(ca_dir);
1053
980
 
1054
 
            Arc::CredentialStore cstore(usercfg,Arc::URL("myproxy://"+m_myproxy_server));
 
981
            Arc::CredentialStore cstore(usercfg,Arc::URL("myproxy://"+myproxy_server));
1055
982
            std::map<std::string,std::string> myproxyopt;
1056
 
            myproxyopt["username"] = m_user_name;
 
983
            myproxyopt["username"] = user_name;
1057
984
            myproxyopt["password"] = passphrase;
1058
985
            if(!cstore.Destroy(myproxyopt))
1059
986
                throw std::invalid_argument("Failed to destroy credential on MyProxy service");
1073
1000
    //For "GET" command, certificate and key are not needed, and
1074
1001
    //anonymous GSSAPI is used (GSS_C_ANON_FLAG)
1075
1002
    try {
1076
 
        if (m_myproxy_command == "get" || m_myproxy_command == "GET" || m_myproxy_command == "Get") {
1077
 
            if (m_myproxy_server.empty())
 
1003
        if (myproxy_command == "get" || myproxy_command == "GET" || myproxy_command == "Get") {
 
1004
            if (myproxy_server.empty())
1078
1005
                throw std::invalid_argument("URL of MyProxy server is missing");
1079
1006
 
1080
 
            if(m_user_name.empty()) {
1081
 
                Arc::Credential proxy_cred(m_proxy_path, "", "", "");
 
1007
            if(user_name.empty()) {
 
1008
                Arc::Credential proxy_cred(proxy_path, "", "", "");
1082
1009
                std::string cert_dn = proxy_cred.GetIdentityName();
1083
 
                m_user_name = cert_dn;
 
1010
                user_name = cert_dn;
1084
1011
            }
1085
 
            if (m_user_name.empty())
 
1012
            if (user_name.empty())
1086
1013
                throw std::invalid_argument("Username to MyProxy server is missing");
1087
1014
 
1088
1015
            std::string prompt1 = "MyProxy server";
1089
1016
            char password[256];
1090
1017
 
1091
1018
            std::string passphrase = password;
1092
 
            if(!m_use_empty_passphrase) {
 
1019
            if(!use_empty_passphrase) {
1093
1020
                int res = input_password(password, 256, false, prompt1, "", logger);
1094
1021
                if (!res)
1095
1022
                    throw std::invalid_argument("Error entering passphrase");
1098
1025
 
1099
1026
            std::string proxy_cred_str_pem;
1100
1027
 
1101
 
            Arc::initializeCredentialsType cred_type(Arc::initializeCredentialsType::SkipCredentials);
1102
 
            Arc::UserConfig usercfg_tmp(cred_type);
 
1028
            Arc::UserConfig usercfg_tmp( (Arc::initializeCredentialsType(Arc::initializeCredentialsType::SkipCredentials)) );
1103
1029
            usercfg_tmp.CACertificatesDirectory(usercfg.CACertificatesDirectory());
1104
1030
 
1105
 
            Arc::CredentialStore cstore(usercfg_tmp,Arc::URL("myproxy://"+m_myproxy_server));
 
1031
            Arc::CredentialStore cstore( (usercfg_tmp,Arc::URL("myproxy://"+myproxy_server)) );
1106
1032
            std::map<std::string,std::string> myproxyopt;
1107
 
            myproxyopt["username"] = m_user_name;
 
1033
            myproxyopt["username"] = user_name;
1108
1034
            myproxyopt["password"] = passphrase;
1109
1035
            myproxyopt["lifetime"] = myproxy_period;
1110
1036
            if(!cstore.Retrieve(myproxyopt,proxy_cred_str_pem))
1111
1037
                throw std::invalid_argument("Failed to retrieve proxy from MyProxy service");
1112
 
            write_proxy_file(m_proxy_path,proxy_cred_str_pem);
 
1038
            write_proxy_file(proxy_path,proxy_cred_str_pem);
1113
1039
 
1114
1040
            //Assign proxy_path to cert_path and key_path,
1115
1041
            //so the later voms functionality can use the proxy_path
1116
1042
            //to create proxy with voms AC extension. In this
1117
1043
            //case, "--cert" and "--key" is not needed.
1118
 
            m_cert_path = m_proxy_path;
1119
 
            m_key_path = m_proxy_path;
1120
 
            std::cout << Arc::IString("Succeeded to get a proxy in %s from MyProxy server %s", m_proxy_path, m_myproxy_server) << std::endl;
 
1044
            cert_path = proxy_path;
 
1045
            key_path = proxy_path;
 
1046
            std::cout << Arc::IString("Succeeded to get a proxy in %s from MyProxy server %s", proxy_path, myproxy_server) << std::endl;
1121
1047
 
1122
1048
            return EXIT_SUCCESS;
1123
1049
        }
1136
1062
        proxy_period.SetPeriod(proxy_period.GetPeriod() + 300);
1137
1063
    }
1138
1064
 
 
1065
    /*
 
1066
    Credential(const std::string& cert, const std::string& key, const std::string& cadir,
 
1067
               const std::string& cafile, const std::string& passphrase4key = "",
 
1068
               const bool is_file = true);*/
 
1069
 
1139
1070
    //Create proxy or voms proxy
1140
1071
    try {
1141
 
        Arc::Credential signer(m_cert_path, m_key_path, "", "", this->m_passphrase.toStdString());
 
1072
        Arc::Credential signer(cert_path, key_path, "", "", m_passphrase.toStdString());
 
1073
 
 
1074
        std::cout << signer.GetIdentityName() << std::endl;
 
1075
 
1142
1076
        if (signer.GetIdentityName().empty()) {
1143
1077
            std::cerr << Arc::IString("Proxy generation failed: No valid certificate found.") << std::endl;
1144
1078
            return EXIT_FAILURE;
1145
1079
        }
 
1080
#ifndef WIN32
 
1081
#ifndef __APPLE__
 
1082
        /*
1146
1083
        EVP_PKEY* pkey = signer.GetPrivKey();
1147
1084
        if(!pkey) {
1148
1085
            std::cerr << Arc::IString("Proxy generation failed: No valid private key found.") << std::endl;
1149
1086
            return EXIT_FAILURE;
1150
1087
        }
1151
1088
        if(pkey) EVP_PKEY_free(pkey);
 
1089
        */
 
1090
#endif
 
1091
#endif
1152
1092
        std::cout << Arc::IString("Your identity: %s", signer.GetIdentityName()) << std::endl;
1153
1093
        if (now > signer.GetEndTime()) {
1154
1094
            std::cerr << Arc::IString("Proxy generation failed: Certificate has expired.") << std::endl;
1171
1111
        signer.OutputCertificate(signing_cert);
1172
1112
        signer.OutputCertificateChain(signing_cert_chain);
1173
1113
 
1174
 
        if (!m_vomslist.empty()) { //If we need to generate voms proxy
 
1114
        if (!vomslist.empty()) { //If we need to generate voms proxy
1175
1115
 
1176
1116
            //Generate a temporary self-signed proxy certificate
1177
1117
            //to contact the voms server
1179
1119
            if (!signer.SignRequest(&cred_request, proxy_cert))
1180
1120
                throw std::runtime_error("Failed to sign proxy");
1181
1121
            proxy_cert.append(private_key).append(signing_cert).append(signing_cert_chain);
1182
 
            write_proxy_file(m_proxy_path,proxy_cert);
 
1122
            write_proxy_file(proxy_path,proxy_cert);
1183
1123
 
1184
1124
            //Parse the voms server and command from command line
1185
1125
            std::multimap<std::string, std::string> server_command_map;
1186
 
            for (std::list<std::string>::iterator it = m_vomslist.begin();
1187
 
                 it != m_vomslist.end(); it++) {
 
1126
            for (std::vector<std::string>::iterator it = vomslist.begin();
 
1127
                 it != vomslist.end(); it++) {
1188
1128
                size_t p;
1189
1129
                std::string voms_server;
1190
1130
                std::string command;
1197
1137
 
1198
1138
            //Parse the 'vomses' file to find configure lines corresponding to
1199
1139
            //the information from the command line
1200
 
            if (m_vomses_path.empty())
1201
 
                m_vomses_path = usercfg.VOMSESPath();
1202
 
            if (m_vomses_path.empty()) {
 
1140
            if (vomses_path.empty())
 
1141
                vomses_path = usercfg.VOMSESPath();
 
1142
            if (vomses_path.empty()) {
1203
1143
                logger.msg(Arc::ERROR, "$X509_VOMS_FILE, and $X509_VOMSES are not set;\nUser has not specify the location for vomses information;\nThere is also not vomses location information in user's configuration file;\nCannot find vomses in default locations: ~/.arc/vomses, ~/.voms/vomses, $ARC_LOCATION/etc/vomses, $ARC_LOCATION/etc/grid-security/vomses, $PWD/vomses, /etc/vomses, /etc/grid-security/vomses, and the location at the corresponding sub-directory");
1204
1144
                return EXIT_FAILURE;
1205
1145
            }
1211
1151
            //'vomses/extra/myprivatevo', 'vomses/mypublicvo'
1212
1152
            std::vector<std::string> vomses_files;
1213
1153
            //If the location is a file
1214
 
            if(is_file(m_vomses_path)) vomses_files.push_back(m_vomses_path);
 
1154
            if(is_file(vomses_path)) vomses_files.push_back(vomses_path);
1215
1155
            //If the locaton is a directory, all the files and directories will be scanned
1216
1156
            //to find the vomses information. The scanning will not stop until all of the
1217
1157
            //files and directories are all scanned.
1218
1158
            else {
1219
1159
                std::vector<std::string> files;
1220
 
                files = search_vomses(m_vomses_path);
 
1160
                files = search_vomses(vomses_path);
1221
1161
                if(!files.empty())vomses_files.insert(vomses_files.end(), files.begin(), files.end());
1222
1162
                files.clear();
1223
1163
            }
1295
1235
            ArcCredential::AC **aclist = NULL;
1296
1236
            std::string acorder;
1297
1237
            Arc::MCCConfig cfg;
1298
 
            cfg.AddProxy(m_proxy_path);
1299
 
            cfg.AddCADir(m_ca_dir);
 
1238
            cfg.AddProxy(proxy_path);
 
1239
            cfg.AddCADir(ca_dir);
1300
1240
 
1301
1241
            for (std::map<std::string, std::vector<std::vector<std::string> > >::iterator it = matched_voms_line.begin();
1302
1242
                 it != matched_voms_line.end(); it++) {
1359
1299
                    }
1360
1300
 
1361
1301
                    std::string ordering;
1362
 
                    for(std::list<std::string>::iterator o_it = m_orderlist.begin(); o_it != m_orderlist.end(); o_it++) {
1363
 
                        ordering.append(o_it == m_orderlist.begin() ? "" : ",").append(*o_it);
 
1302
                    for(std::list<std::string>::iterator o_it = orderlist.begin(); o_it != orderlist.end(); o_it++) {
 
1303
                        ordering.append(o_it == orderlist.begin() ? "" : ",").append(*o_it);
1364
1304
                    }
1365
1305
                    logger.msg(Arc::VERBOSE, "Try to get attribute from VOMS server with order: %s", ordering);
1366
1306
                    send_msg.append("<order>").append(ordering).append("</order>");
1367
1307
                    send_msg.append("<lifetime>").append(voms_period).append("</lifetime></voms>");
1368
1308
                    logger.msg(Arc::VERBOSE, "Message sent to VOMS server %s is: %s", voms_name, send_msg);
1369
1309
 
 
1310
                    Arc::ClientTCP client(cfg, address, atoi(port.c_str()), use_gsi_comm ? Arc::GSISec : Arc::SSL3Sec, usercfg.Timeout());
 
1311
                    Arc::PayloadRaw request;
 
1312
                    request.Insert(send_msg.c_str(), 0, send_msg.length());
 
1313
                    Arc::PayloadStreamInterface *response = NULL;
 
1314
                    Arc::MCC_Status status = client.process(&request, &response, true);
 
1315
                    if (!status) {
 
1316
                        //logger.msg(Arc::ERROR, (std::string)status);
 
1317
                        if (response) delete response;
 
1318
                        std::cout << Arc::IString("The VOMS server with the information:\n\t%s\"\ncan not be reached, please make sure it is available", tokens_to_string(voms_line)) << std::endl;
 
1319
                        continue; //There could be another voms replicated server with the same name exists
 
1320
                    }
 
1321
                    if (!response) {
 
1322
                        logger.msg(Arc::ERROR, "No stream response from VOMS server");
 
1323
                        continue;
 
1324
                    }
 
1325
                    Arc::XMLNode node;
1370
1326
                    std::string ret_str;
1371
 
                    if(m_use_http_comm) {
1372
 
                        // Use http to contact voms server, for the RESRful interface provided by voms server
1373
 
                        // The format of the URL: https://moldyngrid.org:15112/generate-ac?fqans=/testbed.univ.kiev.ua/blabla/Role=test-role&lifetime=86400
1374
 
                        // fqans is composed of the voname, group name and role, i.e., the "command" for voms.
1375
 
                        std::string url_str;
1376
 
                        if(!command.empty()) url_str = "https://" + address + ":" + port + "/generate-ac?" + "fqans=" + command + "&lifetime=" + voms_period;
1377
 
                        else url_str = "https://" + address + ":" + port + "/generate-ac?" + "lifetime=" + voms_period;
1378
 
                        Arc::URL voms_url(url_str);
1379
 
                        Arc::ClientHTTP client(cfg, voms_url, usercfg.Timeout());
1380
 
                        client.RelativeURI(true);
1381
 
                        Arc::PayloadRaw request;
1382
 
                        Arc::PayloadRawInterface* response;
1383
 
                        Arc::HTTPClientInfo info;
1384
 
                        Arc::MCC_Status status = client.process("GET", &request, &info, &response);
1385
 
                        if (!status) {
1386
 
                            if (response) delete response;
1387
 
                            std::cout << Arc::IString("The VOMS server with the information:\n\t%s\"\ncan not be reached, please make sure it is available", tokens_to_string(voms_line)) << std::endl;
1388
 
                            continue; //There could be another voms replicated server with the same name exists
1389
 
                        }
1390
 
                        if (!response) {
1391
 
                            logger.msg(Arc::ERROR, "No http response from VOMS server");
1392
 
                            continue;
1393
 
                        }
1394
 
                        if(response->Content() != NULL) ret_str.append(response->Content());
1395
 
                        if (response) delete response;
1396
 
                        logger.msg(Arc::VERBOSE, "Returned message from VOMS server: %s", ret_str);
1397
 
                    }
1398
 
                    else {
1399
 
                        // Use GSI or TLS to contact voms server
1400
 
                        Arc::ClientTCP client(cfg, address, atoi(port.c_str()), m_use_gsi_comm ? Arc::GSISec : Arc::SSL3Sec, usercfg.Timeout());
1401
 
                        Arc::PayloadRaw request;
1402
 
                        request.Insert(send_msg.c_str(), 0, send_msg.length());
1403
 
                        Arc::PayloadStreamInterface *response = NULL;
1404
 
                        Arc::MCC_Status status = client.process(&request, &response, true);
1405
 
                        if (!status) {
1406
 
                            //logger.msg(Arc::ERROR, (std::string)status);
1407
 
                            if (response) delete response;
1408
 
                            std::cout << Arc::IString("The VOMS server with the information:\n\t%s\"\ncan not be reached, please make sure it is available", tokens_to_string(voms_line)) << std::endl;
1409
 
                            continue; //There could be another voms replicated server with the same name exists
1410
 
                        }
1411
 
                        if (!response) {
1412
 
                            logger.msg(Arc::ERROR, "No stream response from VOMS server");
1413
 
                            continue;
1414
 
                        }
1415
 
                        char ret_buf[1024];
1416
 
                        int len = sizeof(ret_buf);
1417
 
                        while(response->Get(ret_buf, len)) {
1418
 
                            ret_str.append(ret_buf, len);
1419
 
                            len = sizeof(ret_buf);
1420
 
                        };
1421
 
                        if (response) delete response;
1422
 
                        logger.msg(Arc::VERBOSE, "Returned message from VOMS server: %s", ret_str);
1423
 
                    }
1424
 
 
1425
 
                    Arc::XMLNode node;
 
1327
                    char ret_buf[1024];
 
1328
                    int len = sizeof(ret_buf);
 
1329
                    while(response->Get(ret_buf, len)) {
 
1330
                        ret_str.append(ret_buf, len);
 
1331
                        len = sizeof(ret_buf);
 
1332
                    };
 
1333
                    logger.msg(Arc::VERBOSE, "Returned message from VOMS server: %s", ret_str);
1426
1334
                    Arc::XMLNode(ret_str).Exchange(node);
1427
1335
                    if((!node) || ((bool)(node["error"]))) {
1428
1336
                        if((bool)(node["error"])) {
1462
1370
                        //logger.msg(Arc::INFO, "The attribute information from voms server: %s is list as following:\n%s",
1463
1371
                        //           voms_server, decodedac);
1464
1372
                        std::cout << Arc::IString("The attribute information from VOMS server: %s is list as following:", voms_server) << std::endl << decodedac << std::endl;
 
1373
                        if (response)
 
1374
                            delete response;
1465
1375
                        return EXIT_SUCCESS;
1466
1376
                    }
1467
1377
 
 
1378
                    if (response)
 
1379
                        delete response;
 
1380
 
1468
1381
                    Arc::addVOMSAC(aclist, acorder, decodedac);
1469
1382
                    succeeded = true; break;
1470
1383
                }//end of the scanning of multiple vomses lines with the same name
1482
1395
                cred_request.AddExtension("order", acorder);
1483
1396
        }
1484
1397
 
1485
 
        if (!m_use_gsi_proxy) {
 
1398
        if (!use_gsi_proxy) {
1486
1399
            if(!policy.empty()) {
1487
1400
                cred_request.SetProxyPolicy("rfc", "anylanguage", policy, -1);
1488
1401
            } else if(CERT_IS_LIMITED_PROXY(signer.GetType())) {
1506
1419
        proxy_cert.append(private_key).append(signing_cert).append(signing_cert_chain);
1507
1420
 
1508
1421
        //If myproxy command is "Put", then the proxy path is set to /tmp/myproxy-proxy.uid.pid
1509
 
        if (m_myproxy_command == "put" || m_myproxy_command == "PUT" || m_myproxy_command == "Put")
1510
 
            m_proxy_path = Glib::build_filename(Glib::get_tmp_dir(), "myproxy-proxy."
 
1422
        if (myproxy_command == "put" || myproxy_command == "PUT" || myproxy_command == "Put")
 
1423
            proxy_path = Glib::build_filename(Glib::get_tmp_dir(), "myproxy-proxy."
1511
1424
                                              + Arc::tostring(user.get_uid()) + Arc::tostring((int)(getpid())));
1512
 
        write_proxy_file(m_proxy_path,proxy_cert);
 
1425
        write_proxy_file(proxy_path,proxy_cert);
1513
1426
 
1514
 
        Arc::Credential proxy_cred(m_proxy_path, m_proxy_path, "", "");
 
1427
        Arc::Credential proxy_cred(proxy_path, proxy_path, "", "");
1515
1428
        Arc::Time left = proxy_cred.GetEndTime();
1516
1429
        std::cout << Arc::IString("Proxy generation succeeded") << std::endl;
1517
1430
        std::cout << Arc::IString("Your proxy is valid until: %s", left.str(Arc::UserTime)) << std::endl;
1526
1439
    //Delegate the former self-delegated credential to
1527
1440
    //myproxy server
1528
1441
    try {
1529
 
        if (m_myproxy_command == "put" || m_myproxy_command == "PUT" || m_myproxy_command == "Put") {
1530
 
            if (m_myproxy_server.empty())
 
1442
        if (myproxy_command == "put" || myproxy_command == "PUT" || myproxy_command == "Put") {
 
1443
            if (myproxy_server.empty())
1531
1444
                throw std::invalid_argument("URL of MyProxy server is missing");
1532
 
            if(m_user_name.empty()) {
1533
 
                Arc::Credential proxy_cred(m_proxy_path, "", "", "");
 
1445
            if(user_name.empty()) {
 
1446
                Arc::Credential proxy_cred(proxy_path, "", "", "");
1534
1447
                std::string cert_dn = proxy_cred.GetIdentityName();
1535
 
                m_user_name = cert_dn;
 
1448
                user_name = cert_dn;
1536
1449
            }
1537
 
            if (m_user_name.empty())
 
1450
            if (user_name.empty())
1538
1451
                throw std::invalid_argument("Username to MyProxy server is missing");
1539
1452
 
1540
1453
            std::string prompt1 = "MyProxy server";
1541
1454
            std::string prompt2 = "MyProxy server";
1542
1455
            char password[256];
1543
1456
            std::string passphrase;
1544
 
            if(m_retrievable_by_cert.empty()) {
 
1457
            if(retrievable_by_cert.empty()) {
1545
1458
                int res = input_password(password, 256, true, prompt1, prompt2, logger);
1546
1459
                if (!res)
1547
1460
                    throw std::invalid_argument("Error entering passphrase");
1549
1462
            }
1550
1463
 
1551
1464
            std::string proxy_cred_str_pem;
1552
 
            std::ifstream proxy_cred_file(m_proxy_path.c_str());
 
1465
            std::ifstream proxy_cred_file(proxy_path.c_str());
1553
1466
            if(!proxy_cred_file)
1554
 
                throw std::invalid_argument("Failed to read proxy file "+m_proxy_path);
 
1467
                throw std::invalid_argument("Failed to read proxy file "+proxy_path);
1555
1468
            std::getline(proxy_cred_file,proxy_cred_str_pem,'\0');
1556
1469
            if(proxy_cred_str_pem.empty())
1557
 
                throw std::invalid_argument("Failed to read proxy file "+m_proxy_path);
 
1470
                throw std::invalid_argument("Failed to read proxy file "+proxy_path);
1558
1471
            proxy_cred_file.close();
1559
1472
 
1560
 
            usercfg.ProxyPath(m_proxy_path);
1561
 
            if(usercfg.CACertificatesDirectory().empty()) { usercfg.CACertificatesDirectory(m_ca_dir); }
 
1473
            usercfg.ProxyPath(proxy_path);
 
1474
            if(usercfg.CACertificatesDirectory().empty()) { usercfg.CACertificatesDirectory(ca_dir); }
1562
1475
 
1563
 
            Arc::CredentialStore cstore(usercfg,Arc::URL("myproxy://"+m_myproxy_server));
 
1476
            Arc::CredentialStore cstore(usercfg,Arc::URL("myproxy://"+myproxy_server));
1564
1477
            std::map<std::string,std::string> myproxyopt;
1565
 
            myproxyopt["username"] = m_user_name;
 
1478
            myproxyopt["username"] = user_name;
1566
1479
            myproxyopt["password"] = passphrase;
1567
1480
            myproxyopt["lifetime"] = myproxy_period;
1568
 
            if(!m_retrievable_by_cert.empty()) {
1569
 
                myproxyopt["retriever_trusted"] = m_retrievable_by_cert;
 
1481
            if(!retrievable_by_cert.empty()) {
 
1482
                myproxyopt["retriever_trusted"] = retrievable_by_cert;
1570
1483
            }
1571
1484
            if(!cstore.Store(myproxyopt,proxy_cred_str_pem,true,proxy_start,proxy_period))
1572
1485
                throw std::invalid_argument("Failed to delegate proxy to MyProxy service");
1573
1486
 
1574
 
            remove_proxy_file(m_proxy_path);
 
1487
            remove_proxy_file(proxy_path);
1575
1488
 
1576
1489
            std::cout << Arc::IString("Succeeded to put a proxy onto MyProxy server") << std::endl;
1577
1490
 
1580
1493
    } catch (std::exception& err) {
1581
1494
        logger.msg(Arc::ERROR, err.what());
1582
1495
        tls_process_error(logger);
1583
 
        remove_proxy_file(m_proxy_path);
 
1496
        remove_proxy_file(proxy_path);
1584
1497
        return EXIT_FAILURE;
1585
1498
    }
1586
1499
 
1587
1500
    return EXIT_SUCCESS;
1588
 
 
1589
1501
}
1590